Remove unused argument from importSuggestions
[ghc.git] / compiler / rename / RnEnv.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
3
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5 -}
6
7 {-# LANGUAGE CPP, MultiWayIf #-}
8
9 module RnEnv (
10 newTopSrcBinder,
11 lookupLocatedTopBndrRn, lookupTopBndrRn,
12 lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
13 lookupLocalOccRn_maybe, lookupInfoOccRn,
14 lookupLocalOccThLvl_maybe,
15 lookupTypeOccRn, lookupKindOccRn,
16 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
17 lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, lookupExactOcc,
18 reportUnboundName, unknownNameSuggestions,
19 addNameClashErrRn,
20
21 HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
22 lookupSigCtxtOccRn,
23
24 lookupFixityRn, lookupFixityRn_help,
25 lookupFieldFixityRn, lookupTyFixityRn,
26 lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName,
27 lookupConstructorFields,
28 lookupSyntaxName, lookupSyntaxName', lookupSyntaxNames,
29 lookupIfThenElse,
30 lookupGreAvailRn,
31 getLookupOccRn,mkUnboundName, mkUnboundNameRdr, isUnboundName,
32 addUsedGRE, addUsedGREs, addUsedDataCons,
33
34 newLocalBndrRn, newLocalBndrsRn,
35 bindLocalNames, bindLocalNamesFV,
36 MiniFixityEnv,
37 addLocalFixities,
38 bindLocatedLocalsFV, bindLocatedLocalsRn,
39 extendTyVarEnvFVRn,
40
41 -- Role annotations
42 RoleAnnotEnv, emptyRoleAnnotEnv, mkRoleAnnotEnv,
43 lookupRoleAnnot, getRoleAnnots,
44
45 checkDupRdrNames, checkShadowedRdrNames,
46 checkDupNames, checkDupAndShadowedNames, dupNamesErr,
47 checkTupSize,
48 addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
49 warnUnusedMatches, warnUnusedTypePatterns,
50 warnUnusedTopBinds, warnUnusedLocalBinds,
51 mkFieldEnv,
52 dataTcOccs, kindSigErr, perhapsForallMsg, unknownSubordinateErr,
53 HsDocContext(..), pprHsDocContext,
54 inHsDocContext, withHsDocContext
55 ) where
56
57 #include "HsVersions.h"
58
59 import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe )
60 import IfaceEnv
61 import HsSyn
62 import RdrName
63 import HscTypes
64 import TcEnv
65 import TcRnMonad
66 import RdrHsSyn ( setRdrNameSpace )
67 import TysWiredIn ( starKindTyConName, unicodeStarKindTyConName )
68 import Name
69 import NameSet
70 import NameEnv
71 import Avail
72 import Module
73 import ConLike
74 import DataCon
75 import TyCon
76 import PrelNames ( mkUnboundName, isUnboundName, rOOT_MAIN, forall_tv_RDR )
77 import ErrUtils ( MsgDoc )
78 import BasicTypes ( Fixity(..), FixityDirection(..), minPrecedence,
79 defaultFixity, pprWarningTxtForMsg, SourceText(..) )
80 import SrcLoc
81 import Outputable
82 import Util
83 import Maybes
84 import BasicTypes ( TopLevelFlag(..) )
85 import ListSetOps ( removeDups )
86 import DynFlags
87 import FastString
88 import Control.Monad
89 import Data.List
90 import Data.Function ( on )
91 import ListSetOps ( minusList )
92 import Constants ( mAX_TUPLE_SIZE )
93 import qualified GHC.LanguageExtensions as LangExt
94
95 {-
96 *********************************************************
97 * *
98 Source-code binders
99 * *
100 *********************************************************
101
102 Note [Signature lazy interface loading]
103 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
104
105 GHC's lazy interface loading can be a bit confusing, so this Note is an
106 empirical description of what happens in one interesting case. When
107 compiling a signature module against an its implementation, we do NOT
108 load interface files associated with its names until after the type
109 checking phase. For example:
110
111 module ASig where
112 data T
113 f :: T -> T
114
115 Suppose we compile this with -sig-of "A is ASig":
116
117 module B where
118 data T = T
119 f T = T
120
121 module A(module B) where
122 import B
123
124 During type checking, we'll load A.hi because we need to know what the
125 RdrEnv for the module is, but we DO NOT load the interface for B.hi!
126 It's wholly unnecessary: our local definition 'data T' in ASig is all
127 the information we need to finish type checking. This is contrast to
128 type checking of ordinary Haskell files, in which we would not have the
129 local definition "data T" and would need to consult B.hi immediately.
130 (Also, this situation never occurs for hs-boot files, since you're not
131 allowed to reexport from another module.)
132
133 After type checking, we then check that the types we provided are
134 consistent with the backing implementation (in checkHiBootOrHsigIface).
135 At this point, B.hi is loaded, because we need something to compare
136 against.
137
138 I discovered this behavior when trying to figure out why type class
139 instances for Data.Map weren't in the EPS when I was type checking a
140 test very much like ASig (sigof02dm): the associated interface hadn't
141 been loaded yet! (The larger issue is a moot point, since an instance
142 declared in a signature can never be a duplicate.)
143
144 This behavior might change in the future. Consider this
145 alternate module B:
146
147 module B where
148 {-# DEPRECATED T, f "Don't use" #-}
149 data T = T
150 f T = T
151
152 One might conceivably want to report deprecation warnings when compiling
153 ASig with -sig-of B, in which case we need to look at B.hi to find the
154 deprecation warnings during renaming. At the moment, you don't get any
155 warning until you use the identifier further downstream. This would
156 require adjusting addUsedGRE so that during signature compilation,
157 we do not report deprecation warnings for LocalDef. See also
158 Note [Handling of deprecations]
159 -}
160
161 newTopSrcBinder :: Located RdrName -> RnM Name
162 newTopSrcBinder (L loc rdr_name)
163 | Just name <- isExact_maybe rdr_name
164 = -- This is here to catch
165 -- (a) Exact-name binders created by Template Haskell
166 -- (b) The PrelBase defn of (say) [] and similar, for which
167 -- the parser reads the special syntax and returns an Exact RdrName
168 -- We are at a binding site for the name, so check first that it
169 -- the current module is the correct one; otherwise GHC can get
170 -- very confused indeed. This test rejects code like
171 -- data T = (,) Int Int
172 -- unless we are in GHC.Tup
173 if isExternalName name then
174 do { this_mod <- getModule
175 ; unless (this_mod == nameModule name)
176 (addErrAt loc (badOrigBinding rdr_name))
177 ; return name }
178 else -- See Note [Binders in Template Haskell] in Convert.hs
179 do { this_mod <- getModule
180 ; externaliseName this_mod name }
181
182 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
183 = do { this_mod <- getModule
184 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
185 (addErrAt loc (badOrigBinding rdr_name))
186 -- When reading External Core we get Orig names as binders,
187 -- but they should agree with the module gotten from the monad
188 --
189 -- We can get built-in syntax showing up here too, sadly. If you type
190 -- data T = (,,,)
191 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
192 -- uses setRdrNameSpace to make it into a data constructors. At that point
193 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
194 -- Hence the badOrigBinding error message.
195 --
196 -- Except for the ":Main.main = ..." definition inserted into
197 -- the Main module; ugh!
198
199 -- Because of this latter case, we call newGlobalBinder with a module from
200 -- the RdrName, not from the environment. In principle, it'd be fine to
201 -- have an arbitrary mixture of external core definitions in a single module,
202 -- (apart from module-initialisation issues, perhaps).
203 ; newGlobalBinder rdr_mod rdr_occ loc }
204
205 | otherwise
206 = do { unless (not (isQual rdr_name))
207 (addErrAt loc (badQualBndrErr rdr_name))
208 -- Binders should not be qualified; if they are, and with a different
209 -- module name, we we get a confusing "M.T is not in scope" error later
210
211 ; stage <- getStage
212 ; if isBrackStage stage then
213 -- We are inside a TH bracket, so make an *Internal* name
214 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
215 do { uniq <- newUnique
216 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
217 else
218 do { this_mod <- getModule
219 ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc)
220 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
221 }
222
223 {-
224 *********************************************************
225 * *
226 Source code occurrences
227 * *
228 *********************************************************
229
230 Looking up a name in the RnEnv.
231
232 Note [Type and class operator definitions]
233 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
234 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
235 data a :*: b = ...
236 class a :*: b where ...
237 data (:*:) a b = ....
238 class (:*:) a b where ...
239 The latter two mean that we are not just looking for a
240 *syntactically-infix* declaration, but one that uses an operator
241 OccName. We use OccName.isSymOcc to detect that case, which isn't
242 terribly efficient, but there seems to be no better way.
243 -}
244
245 lookupTopBndrRn :: RdrName -> RnM Name
246 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
247 case nopt of
248 Just n' -> return n'
249 Nothing -> do traceRn "lookupTopBndrRn fail" (ppr n)
250 unboundName WL_LocalTop n
251
252 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
253 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
254
255 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
256 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
257 -- and there may be several imported 'f's too, which must not confuse us.
258 -- For example, this is OK:
259 -- import Foo( f )
260 -- infix 9 f -- The 'f' here does not need to be qualified
261 -- f x = x -- Nor here, of course
262 -- So we have to filter out the non-local ones.
263 --
264 -- A separate function (importsFromLocalDecls) reports duplicate top level
265 -- decls, so here it's safe just to choose an arbitrary one.
266 --
267 -- There should never be a qualified name in a binding position in Haskell,
268 -- but there can be if we have read in an external-Core file.
269 -- The Haskell parser checks for the illegal qualified name in Haskell
270 -- source files, so we don't need to do so here.
271
272 lookupTopBndrRn_maybe rdr_name
273 | Just name <- isExact_maybe rdr_name
274 = do { name' <- lookupExactOcc name; return (Just name') }
275
276 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
277 -- This deals with the case of derived bindings, where
278 -- we don't bother to call newTopSrcBinder first
279 -- We assume there is no "parent" name
280 = do { loc <- getSrcSpanM
281 ; n <- newGlobalBinder rdr_mod rdr_occ loc
282 ; return (Just n)}
283
284 | otherwise
285 = do { -- Check for operators in type or class declarations
286 -- See Note [Type and class operator definitions]
287 let occ = rdrNameOcc rdr_name
288 ; when (isTcOcc occ && isSymOcc occ)
289 (do { op_ok <- xoptM LangExt.TypeOperators
290 ; unless op_ok (addErr (opDeclErr rdr_name)) })
291
292 ; env <- getGlobalRdrEnv
293 ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
294 [gre] -> return (Just (gre_name gre))
295 _ -> return Nothing -- Ambiguous (can't happen) or unbound
296 }
297
298 -----------------------------------------------
299 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
300 -- This adds an error if the name cannot be found.
301 lookupExactOcc :: Name -> RnM Name
302 lookupExactOcc name
303 = do { result <- lookupExactOcc_either name
304 ; case result of
305 Left err -> do { addErr err
306 ; return name }
307 Right name' -> return name' }
308
309 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
310 -- This never adds an error, but it may return one.
311 lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
312 -- See Note [Looking up Exact RdrNames]
313 lookupExactOcc_either name
314 | Just thing <- wiredInNameTyThing_maybe name
315 , Just tycon <- case thing of
316 ATyCon tc -> Just tc
317 AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
318 _ -> Nothing
319 , isTupleTyCon tycon
320 = do { checkTupSize (tyConArity tycon)
321 ; return (Right name) }
322
323 | isExternalName name
324 = return (Right name)
325
326 | otherwise
327 = do { env <- getGlobalRdrEnv
328 ; let -- See Note [Splicing Exact names]
329 main_occ = nameOccName name
330 demoted_occs = case demoteOccName main_occ of
331 Just occ -> [occ]
332 Nothing -> []
333 gres = [ gre | occ <- main_occ : demoted_occs
334 , gre <- lookupGlobalRdrEnv env occ
335 , gre_name gre == name ]
336 ; case gres of
337 [gre] -> return (Right (gre_name gre))
338
339 [] -> -- See Note [Splicing Exact names]
340 do { lcl_env <- getLocalRdrEnv
341 ; if name `inLocalRdrEnvScope` lcl_env
342 then return (Right name)
343 else
344 do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
345 ; th_topnames <- readTcRef th_topnames_var
346 ; if name `elemNameSet` th_topnames
347 then return (Right name)
348 else return (Left exact_nm_err)
349 }
350 }
351 gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity]
352 }
353 where
354 exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
355 2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), "
356 , text "perhaps via newName, but did not bind it"
357 , text "If that's it, then -ddump-splices might be useful" ])
358
359 sameNameErr :: [GlobalRdrElt] -> MsgDoc
360 sameNameErr [] = panic "addSameNameErr: empty list"
361 sameNameErr gres@(_ : _)
362 = hang (text "Same exact name in multiple name-spaces:")
363 2 (vcat (map pp_one sorted_names) $$ th_hint)
364 where
365 sorted_names = sortWith nameSrcLoc (map gre_name gres)
366 pp_one name
367 = hang (pprNameSpace (occNameSpace (getOccName name))
368 <+> quotes (ppr name) <> comma)
369 2 (text "declared at:" <+> ppr (nameSrcLoc name))
370
371 th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU),"
372 , text "perhaps via newName, in different name-spaces."
373 , text "If that's it, then -ddump-splices might be useful" ]
374
375
376 -----------------------------------------------
377 lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
378 -- This is called on the method name on the left-hand side of an
379 -- instance declaration binding. eg. instance Functor T where
380 -- fmap = ...
381 -- ^^^^ called on this
382 -- Regardless of how many unqualified fmaps are in scope, we want
383 -- the one that comes from the Functor class.
384 --
385 -- Furthermore, note that we take no account of whether the
386 -- name is only in scope qualified. I.e. even if method op is
387 -- in scope as M.op, we still allow plain 'op' on the LHS of
388 -- an instance decl
389 --
390 -- The "what" parameter says "method" or "associated type",
391 -- depending on what we are looking up
392 lookupInstDeclBndr cls what rdr
393 = do { when (isQual rdr)
394 (addErr (badQualBndrErr rdr))
395 -- In an instance decl you aren't allowed
396 -- to use a qualified name for the method
397 -- (Although it'd make perfect sense.)
398 ; mb_name <- lookupSubBndrOcc
399 False -- False => we don't give deprecated
400 -- warnings when a deprecated class
401 -- method is defined. We only warn
402 -- when it's used
403 cls doc rdr
404 ; case mb_name of
405 Left err -> do { addErr err; return (mkUnboundNameRdr rdr) }
406 Right nm -> return nm }
407 where
408 doc = what <+> text "of class" <+> quotes (ppr cls)
409
410
411 -----------------------------------------------
412 lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name)
413 -- Used for TyData and TySynonym family instances only,
414 -- See Note [Family instance binders]
415 lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind
416 = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr
417 lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence*
418 = lookupLocatedOccRn tc_rdr
419
420 -----------------------------------------------
421 lookupConstructorFields :: Name -> RnM [FieldLabel]
422 -- Look up the fields of a given constructor
423 -- * For constructors from this module, use the record field env,
424 -- which is itself gathered from the (as yet un-typechecked)
425 -- data type decls
426 --
427 -- * For constructors from imported modules, use the *type* environment
428 -- since imported modles are already compiled, the info is conveniently
429 -- right there
430
431 lookupConstructorFields con_name
432 = do { this_mod <- getModule
433 ; if nameIsLocalOrFrom this_mod con_name then
434 do { field_env <- getRecFieldEnv
435 ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env)
436 ; return (lookupNameEnv field_env con_name `orElse` []) }
437 else
438 do { con <- tcLookupConLike con_name
439 ; traceTc "lookupCF 2" (ppr con)
440 ; return (conLikeFieldLabels con) } }
441
442 -----------------------------------------------
443 -- Used for record construction and pattern matching
444 -- When the -XDisambiguateRecordFields flag is on, take account of the
445 -- constructor name to disambiguate which field to use; it's just the
446 -- same as for instance decls
447 --
448 -- NB: Consider this:
449 -- module Foo where { data R = R { fld :: Int } }
450 -- module Odd where { import Foo; fld x = x { fld = 3 } }
451 -- Arguably this should work, because the reference to 'fld' is
452 -- unambiguous because there is only one field id 'fld' in scope.
453 -- But currently it's rejected.
454
455 lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual
456 -- Just tycon => use tycon to disambiguate
457 -> SDoc -> RdrName
458 -> RnM Name
459 lookupRecFieldOcc parent doc rdr_name
460 | Just tc_name <- parent
461 = do { mb_name <- lookupSubBndrOcc True tc_name doc rdr_name
462 ; case mb_name of
463 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
464 Right n -> return n }
465
466 | otherwise
467 = lookupGlobalOccRn rdr_name
468
469 lookupSubBndrOcc :: Bool
470 -> Name -- Parent
471 -> SDoc
472 -> RdrName
473 -> RnM (Either MsgDoc Name)
474 -- Find all the things the rdr-name maps to
475 -- and pick the one with the right parent namep
476 lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name
477 | Just n <- isExact_maybe rdr_name -- This happens in derived code
478 = do { n <- lookupExactOcc n
479 ; return (Right n) }
480
481 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
482 = do { n <- lookupOrig rdr_mod rdr_occ
483 ; return (Right n) }
484
485 | isUnboundName the_parent
486 -- Avoid an error cascade from malformed decls:
487 -- instance Int where { foo = e }
488 -- We have already generated an error in rnLHsInstDecl
489 = return (Right (mkUnboundNameRdr rdr_name))
490
491 | otherwise
492 = do { env <- getGlobalRdrEnv
493 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
494 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
495 -- The latter does pickGREs, but we want to allow 'x'
496 -- even if only 'M.x' is in scope
497 ; traceRn "lookupSubBndrOcc"
498 (vcat [ ppr the_parent, ppr rdr_name
499 , ppr gres, ppr (pick_gres rdr_name gres)])
500 ; case pick_gres rdr_name gres of
501 (gre:_) -> do { addUsedGRE warn_if_deprec gre
502 -- Add a usage; this is an *occurrence* site
503 -- Note [Usage for sub-bndrs]
504 ; return (Right (gre_name gre)) }
505 -- If there is more than one local GRE for the
506 -- same OccName 'f', that will be reported separately
507 -- as a duplicate top-level binding for 'f'
508 [] -> do { ns <- lookupQualifiedNameGHCi rdr_name
509 ; case ns of
510 (n:_) -> return (Right n) -- Unlikely to be more than one...?
511 [] -> return (Left (unknownSubordinateErr doc rdr_name))
512 } }
513 where
514 -- If Parent = NoParent, just do a normal lookup
515 -- If Parent = Parent p then find all GREs that
516 -- (a) have parent p
517 -- (b) for Unqual, are in scope qualified or unqualified
518 -- for Qual, are in scope with that qualification
519 pick_gres rdr_name gres
520 | isUnqual rdr_name = filter right_parent gres
521 | otherwise = filter right_parent (pickGREs rdr_name gres)
522
523 right_parent (GRE { gre_par = p })
524 | ParentIs parent <- p = parent == the_parent
525 | FldParent { par_is = parent } <- p = parent == the_parent
526 | otherwise = False
527
528 {-
529 Note [Family instance binders]
530 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
531 Consider
532 data family F a
533 data instance F T = X1 | X2
534
535 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
536 X1 and X2. (This is unlike a normal data type declaration which would
537 bind F too.) So we want an AvailTC F [X1,X2].
538
539 Now consider a similar pair:
540 class C a where
541 data G a
542 instance C S where
543 data G S = Y1 | Y2
544
545 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
546
547 But there is a small complication: in an instance decl, we don't use
548 qualified names on the LHS; instead we use the class to disambiguate.
549 Thus:
550 module M where
551 import Blib( G )
552 class C a where
553 data G a
554 instance C S where
555 data G S = Y1 | Y2
556 Even though there are two G's in scope (M.G and Blib.G), the occurrence
557 of 'G' in the 'instance C S' decl is unambiguous, because C has only
558 one associated type called G. This is exactly what happens for methods,
559 and it is only consistent to do the same thing for types. That's the
560 role of the function lookupTcdName; the (Maybe Name) give the class of
561 the encloseing instance decl, if any.
562
563 Note [Looking up Exact RdrNames]
564 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
565 Exact RdrNames are generated by Template Haskell. See Note [Binders
566 in Template Haskell] in Convert.
567
568 For data types and classes have Exact system Names in the binding
569 positions for constructors, TyCons etc. For example
570 [d| data T = MkT Int |]
571 when we splice in and Convert to HsSyn RdrName, we'll get
572 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
573 These System names are generated by Convert.thRdrName
574
575 But, constructors and the like need External Names, not System Names!
576 So we do the following
577
578 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
579 non-External Name, and make an External name for it. This is
580 the name that goes in the GlobalRdrEnv
581
582 * When looking up an occurrence of an Exact name, done in
583 RnEnv.lookupExactOcc, we find the Name with the right unique in the
584 GlobalRdrEnv, and use the one from the envt -- it will be an
585 External Name in the case of the data type/constructor above.
586
587 * Exact names are also use for purely local binders generated
588 by TH, such as \x_33. x_33
589 Both binder and occurrence are Exact RdrNames. The occurrence
590 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
591 misses, because lookupLocalRdrEnv always returns Nothing for
592 an Exact Name. Now we fall through to lookupExactOcc, which
593 will find the Name is not in the GlobalRdrEnv, so we just use
594 the Exact supplied Name.
595
596 Note [Splicing Exact names]
597 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
598 Consider the splice $(do { x <- newName "x"; return (VarE x) })
599 This will generate a (HsExpr RdrName) term that mentions the
600 Exact RdrName "x_56" (or whatever), but does not bind it. So
601 when looking such Exact names we want to check that it's in scope,
602 otherwise the type checker will get confused. To do this we need to
603 keep track of all the Names in scope, and the LocalRdrEnv does just that;
604 we consult it with RdrName.inLocalRdrEnvScope.
605
606 There is another wrinkle. With TH and -XDataKinds, consider
607 $( [d| data Nat = Zero
608 data T = MkT (Proxy 'Zero) |] )
609 After splicing, but before renaming we get this:
610 data Nat_77{tc} = Zero_78{d}
611 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
612 The occurrence of 'Zero in the data type for T has the right unique,
613 but it has a TcClsName name-space in its OccName. (This is set by
614 the ctxt_ns argument of Convert.thRdrName.) When we check that is
615 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
616 too. (An alternative would be to make the GlobalRdrEnv also have
617 a Name -> GRE mapping.)
618
619 Note [Template Haskell ambiguity]
620 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
621 The GlobalRdrEnv invariant says that if
622 occ -> [gre1, ..., gren]
623 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
624 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
625
626 So how can we get multiple gres in lookupExactOcc_maybe? Because in
627 TH we might use the same TH NameU in two different name spaces.
628 eg (Trac #7241):
629 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
630 Here we generate a type constructor and data constructor with the same
631 unique, but differnt name spaces.
632
633 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
634 mean looking up the OccName in every name-space, just in case, and that
635 seems a bit brutal. So it's just done here on lookup. But we might
636 need to revisit that choice.
637
638 Note [Usage for sub-bndrs]
639 ~~~~~~~~~~~~~~~~~~~~~~~~~~
640 If you have this
641 import qualified M( C( f ) )
642 instance M.C T where
643 f x = x
644 then is the qualified import M.f used? Obviously yes.
645 But the RdrName used in the instance decl is unqualified. In effect,
646 we fill in the qualification by looking for f's whose class is M.C
647 But when adding to the UsedRdrNames we must make that qualification
648 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
649
650 So we make up a suitable (fake) RdrName. But be careful
651 import qualified M
652 import M( C(f) )
653 instance C T where
654 f x = x
655 Here we want to record a use of 'f', not of 'M.f', otherwise
656 we'll miss the fact that the qualified import is redundant.
657
658 --------------------------------------------------
659 -- Occurrences
660 --------------------------------------------------
661 -}
662
663 getLookupOccRn :: RnM (Name -> Maybe Name)
664 getLookupOccRn
665 = do local_env <- getLocalRdrEnv
666 return (lookupLocalRdrOcc local_env . nameOccName)
667
668 mkUnboundNameRdr :: RdrName -> Name
669 mkUnboundNameRdr rdr = mkUnboundName (rdrNameOcc rdr)
670
671 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
672 lookupLocatedOccRn = wrapLocM lookupOccRn
673
674 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
675 -- Just look in the local environment
676 lookupLocalOccRn_maybe rdr_name
677 = do { local_env <- getLocalRdrEnv
678 ; return (lookupLocalRdrEnv local_env rdr_name) }
679
680 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
681 -- Just look in the local environment
682 lookupLocalOccThLvl_maybe name
683 = do { lcl_env <- getLclEnv
684 ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
685
686 -- lookupOccRn looks up an occurrence of a RdrName
687 lookupOccRn :: RdrName -> RnM Name
688 lookupOccRn rdr_name
689 = do { mb_name <- lookupOccRn_maybe rdr_name
690 ; case mb_name of
691 Just name -> return name
692 Nothing -> reportUnboundName rdr_name }
693
694 lookupKindOccRn :: RdrName -> RnM Name
695 -- Looking up a name occurring in a kind
696 lookupKindOccRn rdr_name
697 | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
698 = badVarInType rdr_name
699 | otherwise
700 = do { typeintype <- xoptM LangExt.TypeInType
701 ; if | typeintype -> lookupTypeOccRn rdr_name
702 -- With -XNoTypeInType, treat any usage of * in kinds as in scope
703 -- this is a dirty hack, but then again so was the old * kind.
704 | is_star rdr_name -> return starKindTyConName
705 | is_uni_star rdr_name -> return unicodeStarKindTyConName
706 | otherwise -> lookupOccRn rdr_name }
707
708 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
709 lookupTypeOccRn :: RdrName -> RnM Name
710 -- see Note [Demotion]
711 lookupTypeOccRn rdr_name
712 | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
713 = badVarInType rdr_name
714 | otherwise
715 = do { mb_name <- lookupOccRn_maybe rdr_name
716 ; case mb_name of {
717 Just name -> return name ;
718 Nothing -> do { dflags <- getDynFlags
719 ; lookup_demoted rdr_name dflags } } }
720
721 lookup_demoted :: RdrName -> DynFlags -> RnM Name
722 lookup_demoted rdr_name dflags
723 | Just demoted_rdr <- demoteRdrName rdr_name
724 -- Maybe it's the name of a *data* constructor
725 = do { data_kinds <- xoptM LangExt.DataKinds
726 ; mb_demoted_name <- lookupOccRn_maybe demoted_rdr
727 ; case mb_demoted_name of
728 Nothing -> unboundNameX WL_Any rdr_name star_info
729 Just demoted_name
730 | data_kinds ->
731 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
732 addWarn (Reason Opt_WarnUntickedPromotedConstructors)
733 (untickedPromConstrWarn demoted_name)
734 ; return demoted_name }
735 | otherwise -> unboundNameX WL_Any rdr_name suggest_dk }
736
737 | otherwise
738 = reportUnboundName rdr_name
739
740 where
741 suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
742 untickedPromConstrWarn name =
743 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
744 $$
745 hsep [ text "Use"
746 , quotes (char '\'' <> ppr name)
747 , text "instead of"
748 , quotes (ppr name) <> dot ]
749
750 star_info
751 | is_star rdr_name || is_uni_star rdr_name
752 = if xopt LangExt.TypeInType dflags
753 then text "NB: With TypeInType, you must import" <+>
754 ppr rdr_name <+> text "from Data.Kind"
755 else empty
756
757 | otherwise
758 = empty
759
760 is_star, is_uni_star :: RdrName -> Bool
761 is_star = (fsLit "*" ==) . occNameFS . rdrNameOcc
762 is_uni_star = (fsLit "ā˜…" ==) . occNameFS . rdrNameOcc
763
764 badVarInType :: RdrName -> RnM Name
765 badVarInType rdr_name
766 = do { addErr (text "Illegal promoted term variable in a type:"
767 <+> ppr rdr_name)
768 ; return (mkUnboundNameRdr rdr_name) }
769
770 {- Note [Promoted variables in types]
771 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
772 Consider this (Trac #12686):
773 x = True
774 data Bad = Bad 'x
775
776 The parser treats the quote in 'x as saying "use the term
777 namespace", so we'll get (Bad x{v}), with 'x' in the
778 VarName namespace. If we don't test for this, the renamer
779 will happily rename it to the x bound at top level, and then
780 the typecheck falls over because it doesn't have 'x' in scope
781 when kind-checking.
782
783 Note [Demotion]
784 ~~~~~~~~~~~~~~~
785 When the user writes:
786 data Nat = Zero | Succ Nat
787 foo :: f Zero -> Int
788
789 'Zero' in the type signature of 'foo' is parsed as:
790 HsTyVar ("Zero", TcClsName)
791
792 When the renamer hits this occurrence of 'Zero' it's going to realise
793 that it's not in scope. But because it is renaming a type, it knows
794 that 'Zero' might be a promoted data constructor, so it will demote
795 its namespace to DataName and do a second lookup.
796
797 The final result (after the renamer) will be:
798 HsTyVar ("Zero", DataName)
799 -}
800
801 -- Use this version to get tracing
802 --
803 -- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name)
804 -- lookupOccRn_maybe rdr_name
805 -- = do { mb_res <- lookupOccRn_maybe' rdr_name
806 -- ; gbl_rdr_env <- getGlobalRdrEnv
807 -- ; local_rdr_env <- getLocalRdrEnv
808 -- ; traceRn $ text "lookupOccRn_maybe" <+>
809 -- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name))
810 -- , ppr mb_res
811 -- , text "Lcl env" <+> ppr local_rdr_env
812 -- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env
813 -- , let gres' = filter isLocalGRE gres, not (null gres') ] ]
814 -- ; return mb_res }
815
816 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
817 -- lookupOccRn looks up an occurrence of a RdrName
818 lookupOccRn_maybe rdr_name
819 = do { local_env <- getLocalRdrEnv
820 ; case lookupLocalRdrEnv local_env rdr_name of {
821 Just name -> return (Just name) ;
822 Nothing -> do
823 ; lookupGlobalOccRn_maybe rdr_name } }
824
825 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
826 -- Looks up a RdrName occurrence in the top-level
827 -- environment, including using lookupQualifiedNameGHCi
828 -- for the GHCi case
829 -- No filter function; does not report an error on failure
830 -- Uses addUsedRdrName to record use and deprecations
831 lookupGlobalOccRn_maybe rdr_name
832 | Just n <- isExact_maybe rdr_name -- This happens in derived code
833 = do { n' <- lookupExactOcc n; return (Just n') }
834
835 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
836 = do { n <- lookupOrig rdr_mod rdr_occ
837 ; return (Just n) }
838
839 | otherwise
840 = do { mb_gre <- lookupGreRn_maybe rdr_name
841 ; case mb_gre of {
842 Just gre -> return (Just (gre_name gre)) ;
843 Nothing ->
844 do { ns <- lookupQualifiedNameGHCi rdr_name
845 -- This test is not expensive,
846 -- and only happens for failed lookups
847 ; case ns of
848 (n:_) -> return (Just n) -- Unlikely to be more than one...?
849 [] -> return Nothing } } }
850
851 lookupGlobalOccRn :: RdrName -> RnM Name
852 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
853 -- environment. Adds an error message if the RdrName is not in scope.
854 lookupGlobalOccRn rdr_name
855 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
856 ; case mb_name of
857 Just n -> return n
858 Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
859 ; unboundName WL_Global rdr_name } }
860
861 lookupInfoOccRn :: RdrName -> RnM [Name]
862 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
863 -- It finds all the GREs that RdrName could mean, not complaining
864 -- about ambiguity, but rather returning them all
865 -- C.f. Trac #9881
866 lookupInfoOccRn rdr_name
867 | Just n <- isExact_maybe rdr_name -- e.g. (->)
868 = return [n]
869
870 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
871 = do { n <- lookupOrig rdr_mod rdr_occ
872 ; return [n] }
873
874 | otherwise
875 = do { rdr_env <- getGlobalRdrEnv
876 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
877 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
878 ; return (ns ++ (qual_ns `minusList` ns)) }
879
880 -- | Like 'lookupOccRn_maybe', but with a more informative result if
881 -- the 'RdrName' happens to be a record selector:
882 --
883 -- * Nothing -> name not in scope (no error reported)
884 -- * Just (Left x) -> name uniquely refers to x,
885 -- or there is a name clash (reported)
886 -- * Just (Right xs) -> name refers to one or more record selectors;
887 -- if overload_ok was False, this list will be
888 -- a singleton.
889 lookupOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
890 lookupOccRn_overloaded overload_ok rdr_name
891 = do { local_env <- getLocalRdrEnv
892 ; case lookupLocalRdrEnv local_env rdr_name of {
893 Just name -> return (Just (Left name)) ;
894 Nothing -> do
895 { mb_name <- lookupGlobalOccRn_overloaded overload_ok rdr_name
896 ; case mb_name of {
897 Just name -> return (Just name) ;
898 Nothing -> do
899 { ns <- lookupQualifiedNameGHCi rdr_name
900 -- This test is not expensive,
901 -- and only happens for failed lookups
902 ; case ns of
903 (n:_) -> return $ Just $ Left n -- Unlikely to be more than one...?
904 [] -> return Nothing } } } } }
905
906 lookupGlobalOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
907 lookupGlobalOccRn_overloaded overload_ok rdr_name
908 | Just n <- isExact_maybe rdr_name -- This happens in derived code
909 = do { n' <- lookupExactOcc n; return (Just (Left n')) }
910
911 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
912 = do { n <- lookupOrig rdr_mod rdr_occ
913 ; return (Just (Left n)) }
914
915 | otherwise
916 = do { env <- getGlobalRdrEnv
917 ; case lookupGRE_RdrName rdr_name env of
918 [] -> return Nothing
919 [gre] | isRecFldGRE gre
920 -> do { addUsedGRE True gre
921 ; let
922 fld_occ :: FieldOcc Name
923 fld_occ
924 = FieldOcc (noLoc rdr_name) (gre_name gre)
925 ; return (Just (Right [fld_occ])) }
926 | otherwise
927 -> do { addUsedGRE True gre
928 ; return (Just (Left (gre_name gre))) }
929 gres | all isRecFldGRE gres && overload_ok
930 -- Don't record usage for ambiguous selectors
931 -- until we know which is meant
932 -> return
933 (Just (Right
934 (map (FieldOcc (noLoc rdr_name) . gre_name)
935 gres)))
936 gres -> do { addNameClashErrRn rdr_name gres
937 ; return (Just (Left (gre_name (head gres)))) } }
938
939
940 --------------------------------------------------
941 -- Lookup in the Global RdrEnv of the module
942 --------------------------------------------------
943
944 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
945 -- Look up the RdrName in the GlobalRdrEnv
946 -- Exactly one binding: records it as "used", return (Just gre)
947 -- No bindings: return Nothing
948 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
949 -- (This API is a bit strange; lookupGRERn2_maybe is simpler.
950 -- But it works and I don't want to fiddle too much.)
951 -- Uses addUsedRdrName to record use and deprecations
952 lookupGreRn_maybe rdr_name
953 = do { env <- getGlobalRdrEnv
954 ; case lookupGRE_RdrName rdr_name env of
955 [] -> return Nothing
956 [gre] -> do { addUsedGRE True gre
957 ; return (Just gre) }
958 gres -> do { addNameClashErrRn rdr_name gres
959 ; traceRn "lookupGreRn:name clash"
960 (ppr rdr_name $$ ppr gres $$ ppr env)
961 ; return (Just (head gres)) } }
962
963 lookupGreRn2_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
964 -- Look up the RdrName in the GlobalRdrEnv
965 -- Exactly one binding: record it as "used", return (Just gre)
966 -- No bindings: report "not in scope", return Nothing
967 -- Many bindings: report "ambiguous", return Nothing
968 -- Uses addUsedRdrName to record use and deprecations
969 lookupGreRn2_maybe rdr_name
970 = do { env <- getGlobalRdrEnv
971 ; case lookupGRE_RdrName rdr_name env of
972 [] -> do { _ <- unboundName WL_Global rdr_name
973 ; return Nothing }
974 [gre] -> do { addUsedGRE True gre
975 ; return (Just gre) }
976 gres -> do { addNameClashErrRn rdr_name gres
977 ; traceRn "lookupGreRn_maybe:name clash"
978 (ppr rdr_name $$ ppr gres $$ ppr env)
979 ; return Nothing } }
980
981 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
982 -- Used in export lists
983 -- If not found or ambiguous, add error message, and fake with UnboundName
984 -- Uses addUsedRdrName to record use and deprecations
985 lookupGreAvailRn rdr_name
986 = do { mb_gre <- lookupGreRn2_maybe rdr_name
987 ; case mb_gre of {
988 Just gre -> return (gre_name gre, availFromGRE gre) ;
989 Nothing ->
990 do { traceRn "lookupGreAvailRn" (ppr rdr_name)
991 ; let name = mkUnboundNameRdr rdr_name
992 ; return (name, avail name) } } }
993
994 {-
995 *********************************************************
996 * *
997 Deprecations
998 * *
999 *********************************************************
1000
1001 Note [Handling of deprecations]
1002 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1003 * We report deprecations at each *occurrence* of the deprecated thing
1004 (see Trac #5867)
1005
1006 * We do not report deprecations for locally-defined names. For a
1007 start, we may be exporting a deprecated thing. Also we may use a
1008 deprecated thing in the defn of another deprecated things. We may
1009 even use a deprecated thing in the defn of a non-deprecated thing,
1010 when changing a module's interface.
1011
1012 * addUsedGREs: we do not report deprecations for sub-binders:
1013 - the ".." completion for records
1014 - the ".." in an export item 'T(..)'
1015 - the things exported by a module export 'module M'
1016 -}
1017
1018 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
1019 -- Remember use of in-scope data constructors (Trac #7969)
1020 addUsedDataCons rdr_env tycon
1021 = addUsedGREs [ gre
1022 | dc <- tyConDataCons tycon
1023 , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
1024
1025 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
1026 -- Called for both local and imported things
1027 -- Add usage *and* warn if deprecated
1028 addUsedGRE warn_if_deprec gre
1029 = do { when warn_if_deprec (warnIfDeprecated gre)
1030 ; unless (isLocalGRE gre) $
1031 do { env <- getGblEnv
1032 ; traceRn "addUsedGRE" (ppr gre)
1033 ; updMutVar (tcg_used_gres env) (gre :) } }
1034
1035 addUsedGREs :: [GlobalRdrElt] -> RnM ()
1036 -- Record uses of any *imported* GREs
1037 -- Used for recording used sub-bndrs
1038 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1039 addUsedGREs gres
1040 | null imp_gres = return ()
1041 | otherwise = do { env <- getGblEnv
1042 ; traceRn "addUsedGREs" (ppr imp_gres)
1043 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
1044 where
1045 imp_gres = filterOut isLocalGRE gres
1046
1047 warnIfDeprecated :: GlobalRdrElt -> RnM ()
1048 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
1049 | (imp_spec : _) <- iss
1050 = do { dflags <- getDynFlags
1051 ; this_mod <- getModule
1052 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
1053 not (nameIsLocalOrFrom this_mod name)) $
1054 -- See Note [Handling of deprecations]
1055 do { iface <- loadInterfaceForName doc name
1056 ; case lookupImpDeprec iface gre of
1057 Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
1058 (mk_msg imp_spec txt)
1059 Nothing -> return () } }
1060 | otherwise
1061 = return ()
1062 where
1063 occ = greOccName gre
1064 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1065 doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
1066
1067 mk_msg imp_spec txt
1068 = sep [ sep [ text "In the use of"
1069 <+> pprNonVarNameSpace (occNameSpace occ)
1070 <+> quotes (ppr occ)
1071 , parens imp_msg <> colon ]
1072 , pprWarningTxtForMsg txt ]
1073 where
1074 imp_mod = importSpecModule imp_spec
1075 imp_msg = text "imported from" <+> ppr imp_mod <> extra
1076 extra | imp_mod == moduleName name_mod = Outputable.empty
1077 | otherwise = text ", but defined in" <+> ppr name_mod
1078
1079 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1080 lookupImpDeprec iface gre
1081 = mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing,
1082 case gre_par gre of -- or its parent, is warn'd
1083 ParentIs p -> mi_warn_fn iface (nameOccName p)
1084 FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p)
1085 NoParent -> Nothing
1086
1087 {-
1088 Note [Used names with interface not loaded]
1089 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1090 It's (just) possible to find a used
1091 Name whose interface hasn't been loaded:
1092
1093 a) It might be a WiredInName; in that case we may not load
1094 its interface (although we could).
1095
1096 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1097 These are seen as "used" by the renamer (if -XRebindableSyntax)
1098 is on), but the typechecker may discard their uses
1099 if in fact the in-scope fromRational is GHC.Read.fromRational,
1100 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1101 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1102 In that obscure case it won't force the interface in.
1103
1104 In both cases we simply don't permit deprecations;
1105 this is, after all, wired-in stuff.
1106
1107
1108 *********************************************************
1109 * *
1110 GHCi support
1111 * *
1112 *********************************************************
1113
1114 A qualified name on the command line can refer to any module at
1115 all: we try to load the interface if we don't already have it, just
1116 as if there was an "import qualified M" declaration for every
1117 module.
1118
1119 If we fail we just return Nothing, rather than bleating
1120 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1121 which is what loadSrcInterface does.
1122
1123 Note [Safe Haskell and GHCi]
1124 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1125 We DONT do this Safe Haskell as we need to check imports. We can
1126 and should instead check the qualified import but at the moment
1127 this requires some refactoring so leave as a TODO
1128 -}
1129
1130 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1131 lookupQualifiedNameGHCi rdr_name
1132 = -- We want to behave as we would for a source file import here,
1133 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1134 do { dflags <- getDynFlags
1135 ; is_ghci <- getIsGHCi
1136 ; go_for_it dflags is_ghci }
1137
1138 where
1139 go_for_it dflags is_ghci
1140 | Just (mod,occ) <- isQual_maybe rdr_name
1141 , is_ghci
1142 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1143 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1144 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1145 ; case res of
1146 Succeeded iface
1147 -> return [ name
1148 | avail <- mi_exports iface
1149 , name <- availNames avail
1150 , nameOccName name == occ ]
1151
1152 _ -> -- Either we couldn't load the interface, or
1153 -- we could but we didn't find the name in it
1154 do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name)
1155 ; return [] } }
1156
1157 | otherwise
1158 = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name)
1159 ; return [] }
1160
1161 doc = text "Need to find" <+> ppr rdr_name
1162
1163 {-
1164 Note [Looking up signature names]
1165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1166 lookupSigOccRn is used for type signatures and pragmas
1167 Is this valid?
1168 module A
1169 import M( f )
1170 f :: Int -> Int
1171 f x = x
1172 It's clear that the 'f' in the signature must refer to A.f
1173 The Haskell98 report does not stipulate this, but it will!
1174 So we must treat the 'f' in the signature in the same way
1175 as the binding occurrence of 'f', using lookupBndrRn
1176
1177 However, consider this case:
1178 import M( f )
1179 f :: Int -> Int
1180 g x = x
1181 We don't want to say 'f' is out of scope; instead, we want to
1182 return the imported 'f', so that later on the reanamer will
1183 correctly report "misplaced type sig".
1184
1185 Note [Signatures for top level things]
1186 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1187 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1188
1189 * The NameSet says what is bound in this group of bindings.
1190 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1191 f x = x
1192 $( ...some TH splice... )
1193 f :: Int -> Int
1194 When we encounter the signature for 'f', the binding for 'f'
1195 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1196 signature is mis-placed
1197
1198 * For type signatures the NameSet should be the names bound by the
1199 value bindings; for fixity declarations, the NameSet should also
1200 include class sigs and record selectors
1201
1202 infix 3 `f` -- Yes, ok
1203 f :: C a => a -> a -- No, not ok
1204 class C a where
1205 f :: a -> a
1206 -}
1207
1208 data HsSigCtxt
1209 = TopSigCtxt NameSet -- At top level, binding these names
1210 -- See Note [Signatures for top level things]
1211 | LocalBindCtxt NameSet -- In a local binding, binding these names
1212 | ClsDeclCtxt Name -- Class decl for this class
1213 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1214 -- bindings are for these methods
1215 | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names
1216 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1217 -- in the group
1218
1219 instance Outputable HsSigCtxt where
1220 ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns
1221 ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns
1222 ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n
1223 ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns
1224 ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns
1225 ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns
1226
1227 lookupSigOccRn :: HsSigCtxt
1228 -> Sig RdrName
1229 -> Located RdrName -> RnM (Located Name)
1230 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1231
1232 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1233 lookupSigCtxtOccRn :: HsSigCtxt
1234 -> SDoc -- ^ description of thing we're looking up,
1235 -- like "type family"
1236 -> Located RdrName -> RnM (Located Name)
1237 lookupSigCtxtOccRn ctxt what
1238 = wrapLocM $ \ rdr_name ->
1239 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1240 ; case mb_name of
1241 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
1242 Right name -> return name }
1243
1244 lookupBindGroupOcc :: HsSigCtxt
1245 -> SDoc
1246 -> RdrName -> RnM (Either MsgDoc Name)
1247 -- Looks up the RdrName, expecting it to resolve to one of the
1248 -- bound names passed in. If not, return an appropriate error message
1249 --
1250 -- See Note [Looking up signature names]
1251 lookupBindGroupOcc ctxt what rdr_name
1252 | Just n <- isExact_maybe rdr_name
1253 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1254 -- see Note [dataTcOccs and Exact Names]
1255 -- Maybe we should check the side conditions
1256 -- but it's a pain, and Exact things only show
1257 -- up when you know what you are doing
1258
1259 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1260 = do { n' <- lookupOrig rdr_mod rdr_occ
1261 ; return (Right n') }
1262
1263 | otherwise
1264 = case ctxt of
1265 HsBootCtxt ns -> lookup_top (`elemNameSet` ns)
1266 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1267 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1268 LocalBindCtxt ns -> lookup_group ns
1269 ClsDeclCtxt cls -> lookup_cls_op cls
1270 InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
1271 where
1272 lookup_cls_op cls
1273 = lookupSubBndrOcc True cls doc rdr_name
1274 where
1275 doc = text "method of class" <+> quotes (ppr cls)
1276
1277 lookup_top keep_me
1278 = do { env <- getGlobalRdrEnv
1279 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1280 ; case filter (keep_me . gre_name) all_gres of
1281 [] | null all_gres -> bale_out_with Outputable.empty
1282 | otherwise -> bale_out_with local_msg
1283 (gre:_) -> return (Right (gre_name gre)) }
1284
1285 lookup_group bound_names -- Look in the local envt (not top level)
1286 = do { local_env <- getLocalRdrEnv
1287 ; case lookupLocalRdrEnv local_env rdr_name of
1288 Just n
1289 | n `elemNameSet` bound_names -> return (Right n)
1290 | otherwise -> bale_out_with local_msg
1291 Nothing -> bale_out_with Outputable.empty }
1292
1293 bale_out_with msg
1294 = return (Left (sep [ text "The" <+> what
1295 <+> text "for" <+> quotes (ppr rdr_name)
1296 , nest 2 $ text "lacks an accompanying binding"]
1297 $$ nest 2 msg))
1298
1299 local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where")
1300 <+> quotes (ppr rdr_name) <+> text "is declared"
1301
1302
1303 ---------------
1304 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
1305 -- GHC extension: look up both the tycon and data con or variable.
1306 -- Used for top-level fixity signatures and deprecations.
1307 -- Complain if neither is in scope.
1308 -- See Note [Fixity signature lookup]
1309 lookupLocalTcNames ctxt what rdr_name
1310 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1311 ; let (errs, names) = splitEithers mb_gres
1312 ; when (null names) $ addErr (head errs) -- Bleat about one only
1313 ; return names }
1314 where
1315 lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr
1316 ; return (fmap ((,) rdr) name) }
1317
1318 dataTcOccs :: RdrName -> [RdrName]
1319 -- Return both the given name and the same name promoted to the TcClsName
1320 -- namespace. This is useful when we aren't sure which we are looking at.
1321 -- See also Note [dataTcOccs and Exact Names]
1322 dataTcOccs rdr_name
1323 | isDataOcc occ || isVarOcc occ
1324 = [rdr_name, rdr_name_tc]
1325 | otherwise
1326 = [rdr_name]
1327 where
1328 occ = rdrNameOcc rdr_name
1329 rdr_name_tc = setRdrNameSpace rdr_name tcName
1330
1331 {-
1332 Note [dataTcOccs and Exact Names]
1333 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1334 Exact RdrNames can occur in code generated by Template Haskell, and generally
1335 those references are, well, exact. However, the TH `Name` type isn't expressive
1336 enough to always track the correct namespace information, so we sometimes get
1337 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1338 for Exact RdrNames.
1339
1340 There is also an awkward situation for built-in syntax. Example in GHCi
1341 :info []
1342 This parses as the Exact RdrName for nilDataCon, but we also want
1343 the list type constructor.
1344
1345 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1346 which it always is for built in syntax.
1347
1348 *********************************************************
1349 * *
1350 Fixities
1351 * *
1352 *********************************************************
1353
1354 Note [Fixity signature lookup]
1355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1356 A fixity declaration like
1357
1358 infixr 2 ?
1359
1360 can refer to a value-level operator, e.g.:
1361
1362 (?) :: String -> String -> String
1363
1364 or a type-level operator, like:
1365
1366 data (?) a b = A a | B b
1367
1368 so we extend the lookup of the reader name '?' to the TcClsName namespace, as
1369 well as the original namespace.
1370
1371 The extended lookup is also used in other places, like resolution of
1372 deprecation declarations, and lookup of names in GHCi.
1373 -}
1374
1375 --------------------------------
1376 type MiniFixityEnv = FastStringEnv (Located Fixity)
1377 -- Mini fixity env for the names we're about
1378 -- to bind, in a single binding group
1379 --
1380 -- It is keyed by the *FastString*, not the *OccName*, because
1381 -- the single fixity decl infix 3 T
1382 -- affects both the data constructor T and the type constrctor T
1383 --
1384 -- We keep the location so that if we find
1385 -- a duplicate, we can report it sensibly
1386
1387 --------------------------------
1388 -- Used for nested fixity decls to bind names along with their fixities.
1389 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
1390
1391 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
1392 addLocalFixities mini_fix_env names thing_inside
1393 = extendFixityEnv (mapMaybe find_fixity names) thing_inside
1394 where
1395 find_fixity name
1396 = case lookupFsEnv mini_fix_env (occNameFS occ) of
1397 Just (L _ fix) -> Just (name, FixItem occ fix)
1398 Nothing -> Nothing
1399 where
1400 occ = nameOccName name
1401
1402 {-
1403 --------------------------------
1404 lookupFixity is a bit strange.
1405
1406 * Nested local fixity decls are put in the local fixity env, which we
1407 find with getFixtyEnv
1408
1409 * Imported fixities are found in the PIT
1410
1411 * Top-level fixity decls in this module may be for Names that are
1412 either Global (constructors, class operations)
1413 or Local/Exported (everything else)
1414 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
1415 We put them all in the local fixity environment
1416 -}
1417
1418 lookupFixityRn :: Name -> RnM Fixity
1419 lookupFixityRn name = lookupFixityRn' name (nameOccName name)
1420
1421 lookupFixityRn' :: Name -> OccName -> RnM Fixity
1422 lookupFixityRn' name = fmap snd . lookupFixityRn_help' name
1423
1424 -- | 'lookupFixityRn_help' returns @(True, fixity)@ if it finds a 'Fixity'
1425 -- in a local environment or from an interface file. Otherwise, it returns
1426 -- @(False, fixity)@ (e.g., for unbound 'Name's or 'Name's without
1427 -- user-supplied fixity declarations).
1428 lookupFixityRn_help :: Name
1429 -> RnM (Bool, Fixity)
1430 lookupFixityRn_help name =
1431 lookupFixityRn_help' name (nameOccName name)
1432
1433 lookupFixityRn_help' :: Name
1434 -> OccName
1435 -> RnM (Bool, Fixity)
1436 lookupFixityRn_help' name occ
1437 | isUnboundName name
1438 = return (False, Fixity NoSourceText minPrecedence InfixL)
1439 -- Minimise errors from ubound names; eg
1440 -- a>0 `foo` b>0
1441 -- where 'foo' is not in scope, should not give an error (Trac #7937)
1442
1443 | otherwise
1444 = do { local_fix_env <- getFixityEnv
1445 ; case lookupNameEnv local_fix_env name of {
1446 Just (FixItem _ fix) -> return (True, fix) ;
1447 Nothing ->
1448
1449 do { this_mod <- getModule
1450 ; if nameIsLocalOrFrom this_mod name
1451 -- Local (and interactive) names are all in the
1452 -- fixity env, and don't have entries in the HPT
1453 then return (False, defaultFixity)
1454 else lookup_imported } } }
1455 where
1456 lookup_imported
1457 -- For imported names, we have to get their fixities by doing a
1458 -- loadInterfaceForName, and consulting the Ifaces that comes back
1459 -- from that, because the interface file for the Name might not
1460 -- have been loaded yet. Why not? Suppose you import module A,
1461 -- which exports a function 'f', thus;
1462 -- module CurrentModule where
1463 -- import A( f )
1464 -- module A( f ) where
1465 -- import B( f )
1466 -- Then B isn't loaded right away (after all, it's possible that
1467 -- nothing from B will be used). When we come across a use of
1468 -- 'f', we need to know its fixity, and it's then, and only
1469 -- then, that we load B.hi. That is what's happening here.
1470 --
1471 -- loadInterfaceForName will find B.hi even if B is a hidden module,
1472 -- and that's what we want.
1473 = do { iface <- loadInterfaceForName doc name
1474 ; let mb_fix = mi_fix_fn iface occ
1475 ; let msg = case mb_fix of
1476 Nothing ->
1477 text "looking up name" <+> ppr name
1478 <+> text "in iface, but found no fixity for it."
1479 <+> text "Using default fixity instead."
1480 Just f ->
1481 text "looking up name in iface and found:"
1482 <+> vcat [ppr name, ppr f]
1483 ; traceRn "lookupFixityRn_either:" msg
1484 ; return (maybe (False, defaultFixity) (\f -> (True, f)) mb_fix) }
1485
1486 doc = text "Checking fixity for" <+> ppr name
1487
1488 ---------------
1489 lookupTyFixityRn :: Located Name -> RnM Fixity
1490 lookupTyFixityRn (L _ n) = lookupFixityRn n
1491
1492 -- | Look up the fixity of a (possibly ambiguous) occurrence of a record field
1493 -- selector. We use 'lookupFixityRn'' so that we can specifiy the 'OccName' as
1494 -- the field label, which might be different to the 'OccName' of the selector
1495 -- 'Name' if @DuplicateRecordFields@ is in use (Trac #1173). If there are
1496 -- multiple possible selectors with different fixities, generate an error.
1497 lookupFieldFixityRn :: AmbiguousFieldOcc Name -> RnM Fixity
1498 lookupFieldFixityRn (Unambiguous (L _ rdr) n)
1499 = lookupFixityRn' n (rdrNameOcc rdr)
1500 lookupFieldFixityRn (Ambiguous (L _ rdr) _) = get_ambiguous_fixity rdr
1501 where
1502 get_ambiguous_fixity :: RdrName -> RnM Fixity
1503 get_ambiguous_fixity rdr_name = do
1504 traceRn "get_ambiguous_fixity" (ppr rdr_name)
1505 rdr_env <- getGlobalRdrEnv
1506 let elts = lookupGRE_RdrName rdr_name rdr_env
1507
1508 fixities <- groupBy ((==) `on` snd) . zip elts
1509 <$> mapM lookup_gre_fixity elts
1510
1511 case fixities of
1512 -- There should always be at least one fixity.
1513 -- Something's very wrong if there are no fixity candidates, so panic
1514 [] -> panic "get_ambiguous_fixity: no candidates for a given RdrName"
1515 [ (_, fix):_ ] -> return fix
1516 ambigs -> addErr (ambiguous_fixity_err rdr_name ambigs)
1517 >> return (Fixity NoSourceText minPrecedence InfixL)
1518
1519 lookup_gre_fixity gre = lookupFixityRn' (gre_name gre) (greOccName gre)
1520
1521 ambiguous_fixity_err rn ambigs
1522 = vcat [ text "Ambiguous fixity for record field" <+> quotes (ppr rn)
1523 , hang (text "Conflicts: ") 2 . vcat .
1524 map format_ambig $ concat ambigs ]
1525
1526 format_ambig (elt, fix) = hang (ppr fix)
1527 2 (pprNameProvenance elt)
1528
1529
1530 {- *********************************************************************
1531 * *
1532 Role annotations
1533 * *
1534 ********************************************************************* -}
1535
1536 type RoleAnnotEnv = NameEnv (LRoleAnnotDecl Name)
1537
1538 mkRoleAnnotEnv :: [LRoleAnnotDecl Name] -> RoleAnnotEnv
1539 mkRoleAnnotEnv role_annot_decls
1540 = mkNameEnv [ (name, ra_decl)
1541 | ra_decl <- role_annot_decls
1542 , let name = roleAnnotDeclName (unLoc ra_decl)
1543 , not (isUnboundName name) ]
1544 -- Some of the role annots will be unbound;
1545 -- we don't wish to include these
1546
1547 emptyRoleAnnotEnv :: RoleAnnotEnv
1548 emptyRoleAnnotEnv = emptyNameEnv
1549
1550 lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl Name)
1551 lookupRoleAnnot = lookupNameEnv
1552
1553 getRoleAnnots :: [Name] -> RoleAnnotEnv -> ([LRoleAnnotDecl Name], RoleAnnotEnv)
1554 getRoleAnnots bndrs role_env
1555 = ( mapMaybe (lookupRoleAnnot role_env) bndrs
1556 , delListFromNameEnv role_env bndrs )
1557
1558
1559 {-
1560 ************************************************************************
1561 * *
1562 Rebindable names
1563 Dealing with rebindable syntax is driven by the
1564 Opt_RebindableSyntax dynamic flag.
1565
1566 In "deriving" code we don't want to use rebindable syntax
1567 so we switch off the flag locally
1568
1569 * *
1570 ************************************************************************
1571
1572 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1573 Standard Prelude, regardless of what is in scope. However, to experiment
1574 with having a language that is less coupled to the standard prelude, we're
1575 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1576 happens to be in scope. Then you can
1577 import Prelude ()
1578 import MyPrelude as Prelude
1579 to get the desired effect.
1580
1581 At the moment this just happens for
1582 * fromInteger, fromRational on literals (in expressions and patterns)
1583 * negate (in expressions)
1584 * minus (arising from n+k patterns)
1585 * "do" notation
1586
1587 We store the relevant Name in the HsSyn tree, in
1588 * HsIntegral/HsFractional/HsIsString
1589 * NegApp
1590 * NPlusKPat
1591 * HsDo
1592 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1593 fromRationalName etc), but the renamer changes this to the appropriate user
1594 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1595
1596 We treat the original (standard) names as free-vars too, because the type checker
1597 checks the type of the user thing against the type of the standard thing.
1598 -}
1599
1600 lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
1601 -- Different to lookupSyntaxName because in the non-rebindable
1602 -- case we desugar directly rather than calling an existing function
1603 -- Hence the (Maybe (SyntaxExpr Name)) return type
1604 lookupIfThenElse
1605 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1606 ; if not rebindable_on
1607 then return (Nothing, emptyFVs)
1608 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1609 ; return ( Just (mkRnSyntaxExpr ite)
1610 , unitFV ite ) } }
1611
1612 lookupSyntaxName' :: Name -- ^ The standard name
1613 -> RnM Name -- ^ Possibly a non-standard name
1614 lookupSyntaxName' std_name
1615 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1616 ; if not rebindable_on then
1617 return std_name
1618 else
1619 -- Get the similarly named thing from the local environment
1620 lookupOccRn (mkRdrUnqual (nameOccName std_name)) }
1621
1622 lookupSyntaxName :: Name -- The standard name
1623 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
1624 lookupSyntaxName std_name
1625 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1626 ; if not rebindable_on then
1627 return (mkRnSyntaxExpr std_name, emptyFVs)
1628 else
1629 -- Get the similarly named thing from the local environment
1630 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1631 ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } }
1632
1633 lookupSyntaxNames :: [Name] -- Standard names
1634 -> RnM ([HsExpr Name], FreeVars) -- See comments with HsExpr.ReboundNames
1635 -- this works with CmdTop, which wants HsExprs, not SyntaxExprs
1636 lookupSyntaxNames std_names
1637 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1638 ; if not rebindable_on then
1639 return (map (HsVar . noLoc) std_names, emptyFVs)
1640 else
1641 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1642 ; return (map (HsVar . noLoc) usr_names, mkFVs usr_names) } }
1643
1644 {-
1645 *********************************************************
1646 * *
1647 \subsection{Binding}
1648 * *
1649 *********************************************************
1650 -}
1651
1652 newLocalBndrRn :: Located RdrName -> RnM Name
1653 -- Used for non-top-level binders. These should
1654 -- never be qualified.
1655 newLocalBndrRn (L loc rdr_name)
1656 | Just name <- isExact_maybe rdr_name
1657 = return name -- This happens in code generated by Template Haskell
1658 -- See Note [Binders in Template Haskell] in Convert.hs
1659 | otherwise
1660 = do { unless (isUnqual rdr_name)
1661 (addErrAt loc (badQualBndrErr rdr_name))
1662 ; uniq <- newUnique
1663 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
1664
1665 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
1666 newLocalBndrsRn = mapM newLocalBndrRn
1667
1668 ---------------------
1669 bindLocatedLocalsRn :: [Located RdrName]
1670 -> ([Name] -> RnM a)
1671 -> RnM a
1672 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
1673 = do { checkDupRdrNames rdr_names_w_loc
1674 ; checkShadowedRdrNames rdr_names_w_loc
1675
1676 -- Make fresh Names and extend the environment
1677 ; names <- newLocalBndrsRn rdr_names_w_loc
1678 ; bindLocalNames names (enclosed_scope names) }
1679
1680 bindLocalNames :: [Name] -> RnM a -> RnM a
1681 bindLocalNames names enclosed_scope
1682 = do { lcl_env <- getLclEnv
1683 ; let th_level = thLevel (tcl_th_ctxt lcl_env)
1684 th_bndrs' = extendNameEnvList (tcl_th_bndrs lcl_env)
1685 [ (n, (NotTopLevel, th_level)) | n <- names ]
1686 rdr_env' = extendLocalRdrEnvList (tcl_rdr lcl_env) names
1687 ; setLclEnv (lcl_env { tcl_th_bndrs = th_bndrs'
1688 , tcl_rdr = rdr_env' })
1689 enclosed_scope }
1690
1691 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1692 bindLocalNamesFV names enclosed_scope
1693 = do { (result, fvs) <- bindLocalNames names enclosed_scope
1694 ; return (result, delFVs names fvs) }
1695
1696
1697 -------------------------------------
1698 -- binLocalsFVRn is the same as bindLocalsRn
1699 -- except that it deals with free vars
1700 bindLocatedLocalsFV :: [Located RdrName]
1701 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
1702 bindLocatedLocalsFV rdr_names enclosed_scope
1703 = bindLocatedLocalsRn rdr_names $ \ names ->
1704 do (thing, fvs) <- enclosed_scope names
1705 return (thing, delFVs names fvs)
1706
1707 -------------------------------------
1708
1709 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1710 -- This function is used only in rnSourceDecl on InstDecl
1711 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
1712
1713 -------------------------------------
1714 checkDupRdrNames :: [Located RdrName] -> RnM ()
1715 -- Check for duplicated names in a binding group
1716 checkDupRdrNames rdr_names_w_loc
1717 = mapM_ (dupNamesErr getLoc) dups
1718 where
1719 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
1720
1721 checkDupNames :: [Name] -> RnM ()
1722 -- Check for duplicated names in a binding group
1723 checkDupNames names = check_dup_names (filterOut isSystemName names)
1724 -- See Note [Binders in Template Haskell] in Convert
1725
1726 check_dup_names :: [Name] -> RnM ()
1727 check_dup_names names
1728 = mapM_ (dupNamesErr nameSrcSpan) dups
1729 where
1730 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
1731
1732 ---------------------
1733 checkShadowedRdrNames :: [Located RdrName] -> RnM ()
1734 checkShadowedRdrNames loc_rdr_names
1735 = do { envs <- getRdrEnvs
1736 ; checkShadowedOccs envs get_loc_occ filtered_rdrs }
1737 where
1738 filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names
1739 -- See Note [Binders in Template Haskell] in Convert
1740 get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr)
1741
1742 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
1743 checkDupAndShadowedNames envs names
1744 = do { check_dup_names filtered_names
1745 ; checkShadowedOccs envs get_loc_occ filtered_names }
1746 where
1747 filtered_names = filterOut isSystemName names
1748 -- See Note [Binders in Template Haskell] in Convert
1749 get_loc_occ name = (nameSrcSpan name, nameOccName name)
1750
1751 -------------------------------------
1752 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv)
1753 -> (a -> (SrcSpan, OccName))
1754 -> [a] -> RnM ()
1755 checkShadowedOccs (global_env,local_env) get_loc_occ ns
1756 = whenWOptM Opt_WarnNameShadowing $
1757 do { traceRn "checkShadowedOccs:shadow" (ppr (map get_loc_occ ns))
1758 ; mapM_ check_shadow ns }
1759 where
1760 check_shadow n
1761 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
1762 -- See Trac #3262
1763 | Just n <- mb_local = complain [text "bound at" <+> ppr (nameSrcLoc n)]
1764 | otherwise = do { gres' <- filterM is_shadowed_gre gres
1765 ; complain (map pprNameProvenance gres') }
1766 where
1767 (loc,occ) = get_loc_occ n
1768 mb_local = lookupLocalRdrOcc local_env occ
1769 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
1770 -- Make an Unqualified RdrName and look that up, so that
1771 -- we don't find any GREs that are in scope qualified-only
1772
1773 complain [] = return ()
1774 complain pp_locs = addWarnAt (Reason Opt_WarnNameShadowing)
1775 loc
1776 (shadowedNameWarn occ pp_locs)
1777
1778 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
1779 -- Returns False for record selectors that are shadowed, when
1780 -- punning or wild-cards are on (cf Trac #2723)
1781 is_shadowed_gre gre | isRecFldGRE gre
1782 = do { dflags <- getDynFlags
1783 ; return $ not (xopt LangExt.RecordPuns dflags
1784 || xopt LangExt.RecordWildCards dflags) }
1785 is_shadowed_gre _other = return True
1786
1787 {-
1788 ************************************************************************
1789 * *
1790 What to do when a lookup fails
1791 * *
1792 ************************************************************************
1793 -}
1794
1795 data WhereLooking = WL_Any -- Any binding
1796 | WL_Global -- Any top-level binding (local or imported)
1797 | WL_LocalTop -- Any top-level binding in this module
1798
1799 reportUnboundName :: RdrName -> RnM Name
1800 reportUnboundName rdr = unboundName WL_Any rdr
1801
1802 unboundName :: WhereLooking -> RdrName -> RnM Name
1803 unboundName wl rdr = unboundNameX wl rdr Outputable.empty
1804
1805 unboundNameX :: WhereLooking -> RdrName -> SDoc -> RnM Name
1806 unboundNameX where_look rdr_name extra
1807 = do { dflags <- getDynFlags
1808 ; let show_helpful_errors = gopt Opt_HelpfulErrors dflags
1809 what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1810 err = unknownNameErr what rdr_name $$ extra
1811 ; if not show_helpful_errors
1812 then addErr err
1813 else do { local_env <- getLocalRdrEnv
1814 ; global_env <- getGlobalRdrEnv
1815 ; impInfo <- getImports
1816 ; let suggestions = unknownNameSuggestions_ where_look
1817 dflags global_env local_env impInfo rdr_name
1818 ; addErr (err $$ suggestions) }
1819 ; return (mkUnboundNameRdr rdr_name) }
1820
1821 unknownNameErr :: SDoc -> RdrName -> SDoc
1822 unknownNameErr what rdr_name
1823 = vcat [ hang (text "Not in scope:")
1824 2 (what <+> quotes (ppr rdr_name))
1825 , extra ]
1826 where
1827 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1828 | otherwise = Outputable.empty
1829
1830 type HowInScope = Either SrcSpan ImpDeclSpec
1831 -- Left loc => locally bound at loc
1832 -- Right ispec => imported as specified by ispec
1833
1834
1835 -- | Called from the typechecker (TcErrors) when we find an unbound variable
1836 unknownNameSuggestions :: DynFlags
1837 -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
1838 -> RdrName -> SDoc
1839 unknownNameSuggestions = unknownNameSuggestions_ WL_Any
1840
1841 unknownNameSuggestions_ :: WhereLooking -> DynFlags
1842 -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
1843 -> RdrName -> SDoc
1844 unknownNameSuggestions_ where_look dflags global_env local_env imports tried_rdr_name =
1845 similarNameSuggestions where_look dflags global_env local_env tried_rdr_name $$
1846 importSuggestions imports tried_rdr_name
1847
1848
1849 similarNameSuggestions :: WhereLooking -> DynFlags
1850 -> GlobalRdrEnv -> LocalRdrEnv
1851 -> RdrName -> SDoc
1852 similarNameSuggestions where_look dflags global_env
1853 local_env tried_rdr_name
1854 = case suggest of
1855 [] -> Outputable.empty
1856 [p] -> perhaps <+> pp_item p
1857 ps -> sep [ perhaps <+> text "one of these:"
1858 , nest 2 (pprWithCommas pp_item ps) ]
1859 where
1860 all_possibilities :: [(String, (RdrName, HowInScope))]
1861 all_possibilities
1862 = [ (showPpr dflags r, (r, Left loc))
1863 | (r,loc) <- local_possibilities local_env ]
1864 ++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ]
1865
1866 suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities
1867 perhaps = text "Perhaps you meant"
1868
1869 pp_item :: (RdrName, HowInScope) -> SDoc
1870 pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined
1871 where loc' = case loc of
1872 UnhelpfulSpan l -> parens (ppr l)
1873 RealSrcSpan l -> parens (text "line" <+> int (srcSpanStartLine l))
1874 pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+> -- Imported
1875 parens (text "imported from" <+> ppr (is_mod is))
1876
1877 pp_ns :: RdrName -> SDoc
1878 pp_ns rdr | ns /= tried_ns = pprNameSpace ns
1879 | otherwise = Outputable.empty
1880 where ns = rdrNameSpace rdr
1881
1882 tried_occ = rdrNameOcc tried_rdr_name
1883 tried_is_sym = isSymOcc tried_occ
1884 tried_ns = occNameSpace tried_occ
1885 tried_is_qual = isQual tried_rdr_name
1886
1887 correct_name_space occ = nameSpacesRelated (occNameSpace occ) tried_ns
1888 && isSymOcc occ == tried_is_sym
1889 -- Treat operator and non-operators as non-matching
1890 -- This heuristic avoids things like
1891 -- Not in scope 'f'; perhaps you meant '+' (from Prelude)
1892
1893 local_ok = case where_look of { WL_Any -> True; _ -> False }
1894 local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
1895 local_possibilities env
1896 | tried_is_qual = []
1897 | not local_ok = []
1898 | otherwise = [ (mkRdrUnqual occ, nameSrcSpan name)
1899 | name <- localRdrEnvElts env
1900 , let occ = nameOccName name
1901 , correct_name_space occ]
1902
1903 gre_ok :: GlobalRdrElt -> Bool
1904 gre_ok = case where_look of
1905 WL_LocalTop -> isLocalGRE
1906 _ -> \_ -> True
1907
1908 global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
1909 global_possibilities global_env
1910 | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
1911 | gre <- globalRdrEnvElts global_env
1912 , gre_ok gre
1913 , let name = gre_name gre
1914 occ = nameOccName name
1915 , correct_name_space occ
1916 , (mod, how) <- quals_in_scope gre
1917 , let rdr_qual = mkRdrQual mod occ ]
1918
1919 | otherwise = [ (rdr_unqual, pair)
1920 | gre <- globalRdrEnvElts global_env
1921 , gre_ok gre
1922 , let name = gre_name gre
1923 occ = nameOccName name
1924 rdr_unqual = mkRdrUnqual occ
1925 , correct_name_space occ
1926 , pair <- case (unquals_in_scope gre, quals_only gre) of
1927 (how:_, _) -> [ (rdr_unqual, how) ]
1928 ([], pr:_) -> [ pr ] -- See Note [Only-quals]
1929 ([], []) -> [] ]
1930
1931 -- Note [Only-quals]
1932 -- The second alternative returns those names with the same
1933 -- OccName as the one we tried, but live in *qualified* imports
1934 -- e.g. if you have:
1935 --
1936 -- > import qualified Data.Map as Map
1937 -- > foo :: Map
1938 --
1939 -- then we suggest @Map.Map@.
1940
1941 --------------------
1942 unquals_in_scope :: GlobalRdrElt -> [HowInScope]
1943 unquals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1944 | lcl = [ Left (nameSrcSpan n) ]
1945 | otherwise = [ Right ispec
1946 | i <- is, let ispec = is_decl i
1947 , not (is_qual ispec) ]
1948
1949 --------------------
1950 quals_in_scope :: GlobalRdrElt -> [(ModuleName, HowInScope)]
1951 -- Ones for which the qualified version is in scope
1952 quals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1953 | lcl = case nameModule_maybe n of
1954 Nothing -> []
1955 Just m -> [(moduleName m, Left (nameSrcSpan n))]
1956 | otherwise = [ (is_as ispec, Right ispec)
1957 | i <- is, let ispec = is_decl i ]
1958
1959 --------------------
1960 quals_only :: GlobalRdrElt -> [(RdrName, HowInScope)]
1961 -- Ones for which *only* the qualified version is in scope
1962 quals_only (GRE { gre_name = n, gre_imp = is })
1963 = [ (mkRdrQual (is_as ispec) (nameOccName n), Right ispec)
1964 | i <- is, let ispec = is_decl i, is_qual ispec ]
1965
1966 -- | Generate helpful suggestions if a qualified name Mod.foo is not in scope.
1967 importSuggestions :: ImportAvails -> RdrName -> SDoc
1968 importSuggestions imports rdr_name
1969 | not (isQual rdr_name || isUnqual rdr_name) = Outputable.empty
1970 | null interesting_imports
1971 , Just name <- mod_name
1972 = hsep
1973 [ text "No module named"
1974 , quotes (ppr name)
1975 , text "is imported."
1976 ]
1977 | is_qualified
1978 , null helpful_imports
1979 , [(mod,_)] <- interesting_imports
1980 = hsep
1981 [ text "Module"
1982 , quotes (ppr mod)
1983 , text "does not export"
1984 , quotes (ppr occ_name) <> dot
1985 ]
1986 | is_qualified
1987 , null helpful_imports
1988 , mods <- map fst interesting_imports
1989 = hsep
1990 [ text "Neither"
1991 , quotedListWithNor (map ppr mods)
1992 , text "exports"
1993 , quotes (ppr occ_name) <> dot
1994 ]
1995 | [(mod,imv)] <- helpful_imports_non_hiding
1996 = fsep
1997 [ text "Perhaps you want to add"
1998 , quotes (ppr occ_name)
1999 , text "to the import list"
2000 , text "in the import of"
2001 , quotes (ppr mod)
2002 , parens (ppr (imv_span imv)) <> dot
2003 ]
2004 | not (null helpful_imports_non_hiding)
2005 = fsep
2006 [ text "Perhaps you want to add"
2007 , quotes (ppr occ_name)
2008 , text "to one of these import lists:"
2009 ]
2010 $$
2011 nest 2 (vcat
2012 [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
2013 | (mod,imv) <- helpful_imports_non_hiding
2014 ])
2015 | [(mod,imv)] <- helpful_imports_hiding
2016 = fsep
2017 [ text "Perhaps you want to remove"
2018 , quotes (ppr occ_name)
2019 , text "from the explicit hiding list"
2020 , text "in the import of"
2021 , quotes (ppr mod)
2022 , parens (ppr (imv_span imv)) <> dot
2023 ]
2024 | not (null helpful_imports_hiding)
2025 = fsep
2026 [ text "Perhaps you want to remove"
2027 , quotes (ppr occ_name)
2028 , text "from the hiding clauses"
2029 , text "in one of these imports:"
2030 ]
2031 $$
2032 nest 2 (vcat
2033 [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
2034 | (mod,imv) <- helpful_imports_hiding
2035 ])
2036 | otherwise
2037 = Outputable.empty
2038 where
2039 is_qualified = isQual rdr_name
2040 (mod_name, occ_name) = case rdr_name of
2041 Unqual occ_name -> (Nothing, occ_name)
2042 Qual mod_name occ_name -> (Just mod_name, occ_name)
2043 _ -> error "importSuggestions: dead code"
2044
2045
2046 -- What import statements provide "Mod" at all
2047 -- or, if this is an unqualified name, are not qualified imports
2048 interesting_imports = [ (mod, imp)
2049 | (mod, mod_imports) <- moduleEnvToList (imp_mods imports)
2050 , Just imp <- return $ pick mod_imports
2051 ]
2052
2053 -- We want to keep only one for each original module; preferably one with an
2054 -- explicit import list (for no particularly good reason)
2055 pick :: [ImportedModsVal] -> Maybe ImportedModsVal
2056 pick = listToMaybe . sortBy (compare `on` prefer) . filter select
2057 where select imv = case mod_name of Just name -> imv_name imv == name
2058 Nothing -> not (imv_qualified imv)
2059 prefer imv = (imv_is_hiding imv, imv_span imv)
2060
2061 -- Which of these would export a 'foo'
2062 -- (all of these are restricted imports, because if they were not, we
2063 -- wouldn't have an out-of-scope error in the first place)
2064 helpful_imports = filter helpful interesting_imports
2065 where helpful (_,imv)
2066 = not . null $ lookupGlobalRdrEnv (imv_all_exports imv) occ_name
2067
2068 -- Which of these do that because of an explicit hiding list resp. an
2069 -- explicit import list
2070 (helpful_imports_hiding, helpful_imports_non_hiding)
2071 = partition (imv_is_hiding . snd) helpful_imports
2072
2073 {-
2074 ************************************************************************
2075 * *
2076 \subsection{Free variable manipulation}
2077 * *
2078 ************************************************************************
2079 -}
2080
2081 -- A useful utility
2082 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
2083 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
2084 ; return (res, fvs1 `plusFV` fvs2) }
2085
2086 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
2087 mapFvRn f xs = do stuff <- mapM f xs
2088 case unzip stuff of
2089 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
2090
2091 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
2092 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
2093 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
2094
2095 -- because some of the rename functions are CPSed:
2096 -- maps the function across the list from left to right;
2097 -- collects all the free vars into one set
2098 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
2099 -> [a] -> ([b] -> RnM c) -> RnM c
2100
2101 mapFvRnCPS _ [] cont = cont []
2102 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
2103 mapFvRnCPS f xs $ \ xs' ->
2104 cont (x':xs')
2105
2106 {-
2107 ************************************************************************
2108 * *
2109 \subsection{Envt utility functions}
2110 * *
2111 ************************************************************************
2112 -}
2113
2114 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
2115 warnUnusedTopBinds gres
2116 = whenWOptM Opt_WarnUnusedTopBinds
2117 $ do env <- getGblEnv
2118 let isBoot = tcg_src env == HsBootFile
2119 let noParent gre = case gre_par gre of
2120 NoParent -> True
2121 _ -> False
2122 -- Don't warn about unused bindings with parents in
2123 -- .hs-boot files, as you are sometimes required to give
2124 -- unused bindings (trac #3449).
2125 -- HOWEVER, in a signature file, you are never obligated to put a
2126 -- definition in the main text. Thus, if you define something
2127 -- and forget to export it, we really DO want to warn.
2128 gres' = if isBoot then filter noParent gres
2129 else gres
2130 warnUnusedGREs gres'
2131
2132 warnUnusedLocalBinds, warnUnusedMatches, warnUnusedTypePatterns
2133 :: [Name] -> FreeVars -> RnM ()
2134 warnUnusedLocalBinds = check_unused Opt_WarnUnusedLocalBinds
2135 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
2136 warnUnusedTypePatterns = check_unused Opt_WarnUnusedTypePatterns
2137
2138 check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM ()
2139 check_unused flag bound_names used_names
2140 = whenWOptM flag (warnUnused flag (filterOut (`elemNameSet` used_names)
2141 bound_names))
2142
2143 -------------------------
2144 -- Helpers
2145 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
2146 warnUnusedGREs gres = mapM_ warnUnusedGRE gres
2147
2148 warnUnused :: WarningFlag -> [Name] -> RnM ()
2149 warnUnused flag names = do
2150 fld_env <- mkFieldEnv <$> getGlobalRdrEnv
2151 mapM_ (warnUnused1 flag fld_env) names
2152
2153 warnUnused1 :: WarningFlag -> NameEnv (FieldLabelString, Name) -> Name -> RnM ()
2154 warnUnused1 flag fld_env name
2155 = when (reportable name occ) $
2156 addUnusedWarning flag
2157 occ (nameSrcSpan name)
2158 (text "Defined but not used")
2159 where
2160 occ = case lookupNameEnv fld_env name of
2161 Just (fl, _) -> mkVarOccFS fl
2162 Nothing -> nameOccName name
2163
2164 warnUnusedGRE :: GlobalRdrElt -> RnM ()
2165 warnUnusedGRE gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = is })
2166 | lcl = do fld_env <- mkFieldEnv <$> getGlobalRdrEnv
2167 warnUnused1 Opt_WarnUnusedTopBinds fld_env name
2168 | otherwise = when (reportable name occ) (mapM_ warn is)
2169 where
2170 occ = greOccName gre
2171 warn spec = addUnusedWarning Opt_WarnUnusedTopBinds occ span msg
2172 where
2173 span = importSpecLoc spec
2174 pp_mod = quotes (ppr (importSpecModule spec))
2175 msg = text "Imported from" <+> pp_mod <+> ptext (sLit "but not used")
2176
2177 -- | Make a map from selector names to field labels and parent tycon
2178 -- names, to be used when reporting unused record fields.
2179 mkFieldEnv :: GlobalRdrEnv -> NameEnv (FieldLabelString, Name)
2180 mkFieldEnv rdr_env = mkNameEnv [ (gre_name gre, (lbl, par_is (gre_par gre)))
2181 | gres <- occEnvElts rdr_env
2182 , gre <- gres
2183 , Just lbl <- [greLabel gre]
2184 ]
2185
2186 -- | Should we report the fact that this 'Name' is unused? The
2187 -- 'OccName' may differ from 'nameOccName' due to
2188 -- DuplicateRecordFields.
2189 reportable :: Name -> OccName -> Bool
2190 reportable name occ
2191 | isWiredInName name = False -- Don't report unused wired-in names
2192 -- Otherwise we get a zillion warnings
2193 -- from Data.Tuple
2194 | otherwise = not (startsWithUnderscore occ)
2195
2196 addUnusedWarning :: WarningFlag -> OccName -> SrcSpan -> SDoc -> RnM ()
2197 addUnusedWarning flag occ span msg
2198 = addWarnAt (Reason flag) span $
2199 sep [msg <> colon,
2200 nest 2 $ pprNonVarNameSpace (occNameSpace occ)
2201 <+> quotes (ppr occ)]
2202
2203 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
2204 addNameClashErrRn rdr_name gres
2205 | all isLocalGRE gres && not (all isRecFldGRE gres)
2206 -- If there are two or more *local* defns, we'll have reported
2207 = return () -- that already, and we don't want an error cascade
2208 | otherwise
2209 = addErr (vcat [text "Ambiguous occurrence" <+> quotes (ppr rdr_name),
2210 text "It could refer to" <+> vcat (msg1 : msgs)])
2211 where
2212 (np1:nps) = gres
2213 msg1 = ptext (sLit "either") <+> mk_ref np1
2214 msgs = [text " or" <+> mk_ref np | np <- nps]
2215 mk_ref gre = sep [nom <> comma, pprNameProvenance gre]
2216 where nom = case gre_par gre of
2217 FldParent { par_lbl = Just lbl } -> text "the field" <+> quotes (ppr lbl)
2218 _ -> quotes (ppr (gre_name gre))
2219
2220 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
2221 shadowedNameWarn occ shadowed_locs
2222 = sep [text "This binding for" <+> quotes (ppr occ)
2223 <+> text "shadows the existing binding" <> plural shadowed_locs,
2224 nest 2 (vcat shadowed_locs)]
2225
2226 perhapsForallMsg :: SDoc
2227 perhapsForallMsg
2228 = vcat [ text "Perhaps you intended to use ExplicitForAll or similar flag"
2229 , text "to enable explicit-forall syntax: forall <tvs>. <type>"]
2230
2231 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
2232 unknownSubordinateErr doc op -- Doc is "method of class" or
2233 -- "field of constructor"
2234 = quotes (ppr op) <+> text "is not a (visible)" <+> doc
2235
2236 badOrigBinding :: RdrName -> SDoc
2237 badOrigBinding name
2238 = text "Illegal binding of built-in syntax:" <+> ppr (rdrNameOcc name)
2239 -- The rdrNameOcc is because we don't want to print Prelude.(,)
2240
2241 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
2242 dupNamesErr get_loc names
2243 = addErrAt big_loc $
2244 vcat [text "Conflicting definitions for" <+> quotes (ppr (head names)),
2245 locations]
2246 where
2247 locs = map get_loc names
2248 big_loc = foldr1 combineSrcSpans locs
2249 locations = text "Bound at:" <+> vcat (map ppr (sort locs))
2250
2251 kindSigErr :: Outputable a => a -> SDoc
2252 kindSigErr thing
2253 = hang (text "Illegal kind signature for" <+> quotes (ppr thing))
2254 2 (text "Perhaps you intended to use KindSignatures")
2255
2256 badQualBndrErr :: RdrName -> SDoc
2257 badQualBndrErr rdr_name
2258 = text "Qualified name in binding position:" <+> ppr rdr_name
2259
2260 opDeclErr :: RdrName -> SDoc
2261 opDeclErr n
2262 = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n))
2263 2 (text "Use TypeOperators to declare operators in type and declarations")
2264
2265 checkTupSize :: Int -> RnM ()
2266 checkTupSize tup_size
2267 | tup_size <= mAX_TUPLE_SIZE
2268 = return ()
2269 | otherwise
2270 = addErr (sep [text "A" <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
2271 nest 2 (parens (text "max size is" <+> int mAX_TUPLE_SIZE)),
2272 nest 2 (text "Workaround: use nested tuples or define a data type")])
2273
2274 {-
2275 ************************************************************************
2276 * *
2277 \subsection{Contexts for renaming errors}
2278 * *
2279 ************************************************************************
2280 -}
2281
2282 -- AZ:TODO: Change these all to be Name instead of RdrName.
2283 -- Merge TcType.UserTypeContext in to it.
2284 data HsDocContext
2285 = TypeSigCtx SDoc
2286 | PatCtx
2287 | SpecInstSigCtx
2288 | DefaultDeclCtx
2289 | ForeignDeclCtx (Located RdrName)
2290 | DerivDeclCtx
2291 | RuleCtx FastString
2292 | TyDataCtx (Located RdrName)
2293 | TySynCtx (Located RdrName)
2294 | TyFamilyCtx (Located RdrName)
2295 | FamPatCtx (Located RdrName) -- The patterns of a type/data family instance
2296 | ConDeclCtx [Located Name]
2297 | ClassDeclCtx (Located RdrName)
2298 | ExprWithTySigCtx
2299 | TypBrCtx
2300 | HsTypeCtx
2301 | GHCiCtx
2302 | SpliceTypeCtx (LHsType RdrName)
2303 | ClassInstanceCtx
2304 | VectDeclCtx (Located RdrName)
2305 | GenericCtx SDoc -- Maybe we want to use this more!
2306
2307 withHsDocContext :: HsDocContext -> SDoc -> SDoc
2308 withHsDocContext ctxt doc = doc $$ inHsDocContext ctxt
2309
2310 inHsDocContext :: HsDocContext -> SDoc
2311 inHsDocContext ctxt = text "In" <+> pprHsDocContext ctxt
2312
2313 pprHsDocContext :: HsDocContext -> SDoc
2314 pprHsDocContext (GenericCtx doc) = doc
2315 pprHsDocContext (TypeSigCtx doc) = text "the type signature for" <+> doc
2316 pprHsDocContext PatCtx = text "a pattern type-signature"
2317 pprHsDocContext SpecInstSigCtx = text "a SPECIALISE instance pragma"
2318 pprHsDocContext DefaultDeclCtx = text "a `default' declaration"
2319 pprHsDocContext DerivDeclCtx = text "a deriving declaration"
2320 pprHsDocContext (RuleCtx name) = text "the transformation rule" <+> ftext name
2321 pprHsDocContext (TyDataCtx tycon) = text "the data type declaration for" <+> quotes (ppr tycon)
2322 pprHsDocContext (FamPatCtx tycon) = text "a type pattern of family instance for" <+> quotes (ppr tycon)
2323 pprHsDocContext (TySynCtx name) = text "the declaration for type synonym" <+> quotes (ppr name)
2324 pprHsDocContext (TyFamilyCtx name) = text "the declaration for type family" <+> quotes (ppr name)
2325 pprHsDocContext (ClassDeclCtx name) = text "the declaration for class" <+> quotes (ppr name)
2326 pprHsDocContext ExprWithTySigCtx = text "an expression type signature"
2327 pprHsDocContext TypBrCtx = text "a Template-Haskell quoted type"
2328 pprHsDocContext HsTypeCtx = text "a type argument"
2329 pprHsDocContext GHCiCtx = text "GHCi input"
2330 pprHsDocContext (SpliceTypeCtx hs_ty) = text "the spliced type" <+> quotes (ppr hs_ty)
2331 pprHsDocContext ClassInstanceCtx = text "TcSplice.reifyInstances"
2332
2333 pprHsDocContext (ForeignDeclCtx name)
2334 = text "the foreign declaration for" <+> quotes (ppr name)
2335 pprHsDocContext (ConDeclCtx [name])
2336 = text "the definition of data constructor" <+> quotes (ppr name)
2337 pprHsDocContext (ConDeclCtx names)
2338 = text "the definition of data constructors" <+> interpp'SP names
2339 pprHsDocContext (VectDeclCtx tycon)
2340 = text "the VECTORISE pragma for type constructor" <+> quotes (ppr tycon)