2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
4 \section[RnEnv]{Environment manipulation for the renamer monad}
8 newTopSrcBinder, lookupFamInstDeclBndr,
9 lookupLocatedTopBndrRn, lookupTopBndrRn,
10 lookupLocatedOccRn, lookupOccRn,
11 lookupLocatedGlobalOccRn,
12 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
13 lookupLocalDataTcNames, lookupSigOccRn,
14 lookupFixityRn, lookupTyFixityRn,
15 lookupInstDeclBndr, lookupSubBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable,
17 lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
18 getLookupOccRn, addUsedRdrNames,
20 newLocalBndrRn, newLocalBndrsRn, newIPNameRn,
21 bindLocalName, bindLocalNames, bindLocalNamesFV,
22 MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
23 bindLocalNamesFV_WithFixities,
24 bindLocatedLocalsFV, bindLocatedLocalsRn,
25 bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
26 bindTyVarsRn, extendTyVarEnvFVRn,
28 checkDupRdrNames, checkDupNames, checkShadowedNames,
29 checkDupAndShadowedRdrNames,
31 warnUnusedMatches, warnUnusedModules, warnUnusedImports,
32 warnUnusedTopBinds, warnUnusedLocalBinds,
33 dataTcOccs, unknownNameErr, kindSigErr, perhapsForallMsg
36 #include "HsVersions.h"
38 import LoadIface ( loadInterfaceForName, loadSrcInterface )
39 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
41 import RdrHsSyn ( extractHsTyRdrTyVars )
43 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity)
44 import TcEnv ( tcLookupDataCon, tcLookupField, isBrackStage )
46 import Id ( isRecordSelector )
47 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
48 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
52 import DataCon ( dataConFieldLabels )
54 import Module ( Module, ModuleName )
55 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
56 consDataConKey, forall_tv_RDR )
59 import ErrUtils ( Message )
64 import ListSetOps ( removeDups )
69 import qualified Data.Set as Set
74 thenM :: Monad a => a b -> (b -> a c) -> a c
78 %*********************************************************
82 %*********************************************************
85 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
86 newTopSrcBinder this_mod (L loc rdr_name)
87 | Just name <- isExact_maybe rdr_name
88 = -- This is here to catch
89 -- (a) Exact-name binders created by Template Haskell
90 -- (b) The PrelBase defn of (say) [] and similar, for which
91 -- the parser reads the special syntax and returns an Exact RdrName
92 -- We are at a binding site for the name, so check first that it
93 -- the current module is the correct one; otherwise GHC can get
94 -- very confused indeed. This test rejects code like
95 -- data T = (,) Int Int
96 -- unless we are in GHC.Tup
97 ASSERT2( isExternalName name, ppr name )
98 do { unless (this_mod == nameModule name)
99 (addErrAt loc (badOrigBinding rdr_name))
103 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
104 = do { unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
105 (addErrAt loc (badOrigBinding rdr_name))
106 -- When reading External Core we get Orig names as binders,
107 -- but they should agree with the module gotten from the monad
109 -- We can get built-in syntax showing up here too, sadly. If you type
111 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
112 -- uses setRdrNameSpace to make it into a data constructors. At that point
113 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
114 -- Hence the badOrigBinding error message.
116 -- Except for the ":Main.main = ..." definition inserted into
117 -- the Main module; ugh!
119 -- Because of this latter case, we call newGlobalBinder with a module from
120 -- the RdrName, not from the environment. In principle, it'd be fine to
121 -- have an arbitrary mixture of external core definitions in a single module,
122 -- (apart from module-initialisation issues, perhaps).
123 ; newGlobalBinder rdr_mod rdr_occ loc }
124 --TODO, should pass the whole span
127 = do { unless (not (isQual rdr_name))
128 (addErrAt loc (badQualBndrErr rdr_name))
129 -- Binders should not be qualified; if they are, and with a different
130 -- module name, we we get a confusing "M.T is not in scope" error later
133 ; if isBrackStage stage then
134 -- We are inside a TH bracket, so make an *Internal* name
135 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
136 do { uniq <- newUnique
137 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
140 newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
143 %*********************************************************
145 Source code occurrences
147 %*********************************************************
149 Looking up a name in the RnEnv.
151 Note [Type and class operator definitions]
152 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
153 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
155 class a :*: b where ...
156 data (:*:) a b = ....
157 class (:*:) a b where ...
158 The latter two mean that we are not just looking for a
159 *syntactically-infix* declaration, but one that uses an operator
160 OccName. We use OccName.isSymOcc to detect that case, which isn't
161 terribly efficient, but there seems to be no better way.
164 lookupTopBndrRn :: RdrName -> RnM Name
165 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
168 Nothing -> do traceRn $ text "lookupTopBndrRn"
171 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
172 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
174 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
175 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
176 -- and there may be several imported 'f's too, which must not confuse us.
177 -- For example, this is OK:
179 -- infix 9 f -- The 'f' here does not need to be qualified
180 -- f x = x -- Nor here, of course
181 -- So we have to filter out the non-local ones.
183 -- A separate function (importsFromLocalDecls) reports duplicate top level
184 -- decls, so here it's safe just to choose an arbitrary one.
186 -- There should never be a qualified name in a binding position in Haskell,
187 -- but there can be if we have read in an external-Core file.
188 -- The Haskell parser checks for the illegal qualified name in Haskell
189 -- source files, so we don't need to do so here.
191 lookupTopBndrRn_maybe rdr_name
192 | Just name <- isExact_maybe rdr_name
195 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
196 -- This deals with the case of derived bindings, where
197 -- we don't bother to call newTopSrcBinder first
198 -- We assume there is no "parent" name
199 = do { loc <- getSrcSpanM
200 ; n <- newGlobalBinder rdr_mod rdr_occ loc
204 = do { -- Check for operators in type or class declarations
205 -- See Note [Type and class operator definitions]
206 let occ = rdrNameOcc rdr_name
207 ; when (isTcOcc occ && isSymOcc occ)
208 (do { op_ok <- doptM Opt_TypeOperators
209 ; unless op_ok (addErr (opDeclErr rdr_name)) })
211 ; mb_gre <- lookupGreLocalRn rdr_name
213 Nothing -> return Nothing
214 Just gre -> return (Just $ gre_name gre) }
217 -----------------------------------------------
218 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
219 -- This is called on the method name on the left-hand side of an
220 -- instance declaration binding. eg. instance Functor T where
222 -- ^^^^ called on this
223 -- Regardless of how many unqualified fmaps are in scope, we want
224 -- the one that comes from the Functor class.
226 -- Furthermore, note that we take no account of whether the
227 -- name is only in scope qualified. I.e. even if method op is
228 -- in scope as M.op, we still allow plain 'op' on the LHS of
230 lookupInstDeclBndr cls rdr
231 = do { when (isQual rdr)
232 (addErr (badQualBndrErr rdr))
233 -- In an instance decl you aren't allowed
234 -- to use a qualified name for the method
235 -- (Although it'd make perfect sense.)
236 ; lookupSubBndr (ParentIs cls) doc rdr }
238 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
240 -----------------------------------------------
241 lookupConstructorFields :: Name -> RnM [Name]
242 -- Look up the fields of a given constructor
243 -- * For constructors from this module, use the record field env,
244 -- which is itself gathered from the (as yet un-typechecked)
247 -- * For constructors from imported modules, use the *type* environment
248 -- since imported modles are already compiled, the info is conveniently
251 lookupConstructorFields con_name
252 = do { this_mod <- getModule
253 ; if nameIsLocalOrFrom this_mod con_name then
254 do { RecFields field_env _ <- getRecFieldEnv
255 ; return (lookupNameEnv field_env con_name `orElse` []) }
257 do { con <- tcLookupDataCon con_name
258 ; return (dataConFieldLabels con) } }
260 -----------------------------------------------
261 -- Used for record construction and pattern matching
262 -- When the -XDisambiguateRecordFields flag is on, take account of the
263 -- constructor name to disambiguate which field to use; it's just the
264 -- same as for instance decls
266 -- NB: Consider this:
267 -- module Foo where { data R = R { fld :: Int } }
268 -- module Odd where { import Foo; fld x = x { fld = 3 } }
269 -- Arguably this should work, because the reference to 'fld' is
270 -- unambiguous because there is only one field id 'fld' in scope.
271 -- But currently it's rejected.
273 lookupSubBndr :: Parent -- NoParent => just look it up as usual
274 -- ParentIs p => use p to disambiguate
277 lookupSubBndr parent doc rdr_name
278 | Just n <- isExact_maybe rdr_name -- This happens in derived code
281 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
282 = lookupOrig rdr_mod rdr_occ
284 | otherwise -- Find all the things the rdr-name maps to
285 = do { -- and pick the one with the right parent name
286 ; env <- getGlobalRdrEnv
287 ; let gres = (lookupGlobalRdrEnv env (rdrNameOcc rdr_name))
288 ; case pick parent gres of
289 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
290 -- The latter does pickGREs, but we want to allow 'x'
291 -- even if only 'M.x' is in scope
292 [gre] -> do { addUsedRdrName gre rdr_name
293 ; return (gre_name gre) }
294 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
295 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> (ppr rdr_name $$ ppr gres))
296 ; return (mkUnboundName rdr_name) }
297 gres -> do { addNameClashErrRn rdr_name gres
298 ; return (gre_name (head gres)) } }
300 pick NoParent gres -- Normal lookup
301 = pickGREs rdr_name gres
302 pick (ParentIs p) gres -- Disambiguating lookup
303 | isUnqual rdr_name = filter (right_parent p) gres
304 | otherwise = filter (right_parent p) (pickGREs rdr_name gres)
306 right_parent p (GRE { gre_par = ParentIs p' }) = p==p'
307 right_parent _ _ = False
309 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
310 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
312 -- If the family is declared locally, it will not yet be in the main
313 -- environment; hence, we pass in an extra one here, which we check first.
314 -- See "Note [Looking up family names in family instances]" in 'RnNames'.
316 lookupFamInstDeclBndr :: GlobalRdrEnv -> Located RdrName -> RnM Name
317 lookupFamInstDeclBndr tyclGroupEnv (L loc rdr_name)
319 case lookupGRE_RdrName rdr_name tyclGroupEnv of
320 (gre:_) -> return $ gre_name gre
321 -- if there is more than one, an error will be raised elsewhere
322 [] -> lookupOccRn rdr_name
325 --------------------------------------------------
327 --------------------------------------------------
329 getLookupOccRn :: RnM (Name -> Maybe Name)
331 = getLocalRdrEnv `thenM` \ local_env ->
332 return (lookupLocalRdrOcc local_env . nameOccName)
334 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
335 lookupLocatedOccRn = wrapLocM lookupOccRn
337 -- lookupOccRn looks up an occurrence of a RdrName
338 lookupOccRn :: RdrName -> RnM Name
340 = getLocalRdrEnv `thenM` \ local_env ->
341 case lookupLocalRdrEnv local_env rdr_name of
342 Just name -> return name
343 Nothing -> lookupGlobalOccRn rdr_name
345 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
346 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
348 lookupGlobalOccRn :: RdrName -> RnM Name
349 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
350 -- environment. Adds an error message if the RdrName is not in scope.
351 -- Also has a special case for GHCi.
353 lookupGlobalOccRn rdr_name
354 = do { -- First look up the name in the normal environment.
355 mb_name <- lookupGlobalOccRn_maybe rdr_name
360 { -- We allow qualified names on the command line to refer to
361 -- *any* name exported by any module in scope, just as if there
362 -- was an "import qualified M" declaration for every module.
363 allow_qual <- doptM Opt_ImplicitImportQualified
365 -- This test is not expensive,
366 -- and only happens for failed lookups
367 ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
368 then lookupQualifiedName rdr_name
369 else unboundName rdr_name } } }
371 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
372 -- No filter function; does not report an error on failure
374 lookupGlobalOccRn_maybe rdr_name
375 | Just n <- isExact_maybe rdr_name -- This happens in derived code
378 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
379 = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
382 = do { mb_gre <- lookupGreRn_maybe rdr_name
384 Nothing -> return Nothing
385 Just gre -> return (Just (gre_name gre)) }
388 unboundName :: RdrName -> RnM Name
390 = do { addErr (unknownNameErr rdr_name)
391 ; env <- getGlobalRdrEnv;
392 ; traceRn (vcat [unknownNameErr rdr_name,
393 ptext (sLit "Global envt is:"),
394 nest 3 (pprGlobalRdrEnv env)])
395 ; return (mkUnboundName rdr_name) }
397 --------------------------------------------------
398 -- Lookup in the Global RdrEnv of the module
399 --------------------------------------------------
401 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
402 -- Just look up the RdrName in the GlobalRdrEnv
403 lookupGreRn_maybe rdr_name
404 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
406 lookupGreRn :: RdrName -> RnM GlobalRdrElt
407 -- If not found, add error message, and return a fake GRE
409 = do { mb_gre <- lookupGreRn_maybe rdr_name
411 Just gre -> return gre ;
413 { traceRn $ text "lookupGreRn"
414 ; name <- unboundName rdr_name
415 ; return (GRE { gre_name = name, gre_par = NoParent,
416 gre_prov = LocalDef }) }}}
418 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
419 -- Similar, but restricted to locally-defined things
420 lookupGreLocalRn rdr_name
421 = lookupGreRn_help rdr_name lookup_fn
423 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
425 lookupGreRn_help :: RdrName -- Only used in error message
426 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
427 -> RnM (Maybe GlobalRdrElt)
428 -- Checks for exactly one match; reports deprecations
429 -- Returns Nothing, without error, if too few
430 lookupGreRn_help rdr_name lookup
431 = do { env <- getGlobalRdrEnv
434 [gre] -> do { addUsedRdrName gre rdr_name
435 ; return (Just gre) }
436 gres -> do { addNameClashErrRn rdr_name gres
437 ; return (Just (head gres)) } }
439 addUsedRdrName :: GlobalRdrElt -> RdrName -> RnM ()
440 -- Record usage of imported RdrNames
441 addUsedRdrName gre rdr
442 | isLocalGRE gre = return ()
443 | otherwise = do { env <- getGblEnv
444 ; updMutVar (tcg_used_rdrnames env)
445 (\s -> Set.insert rdr s) }
447 addUsedRdrNames :: [RdrName] -> RnM ()
448 -- Record used sub-binders
449 -- We don't check for imported-ness here, because it's inconvenient
450 -- and not stritly necessary.
452 = do { env <- getGblEnv
453 ; updMutVar (tcg_used_rdrnames env)
454 (\s -> foldr Set.insert s rdrs) }
456 ------------------------------
458 ------------------------------
460 -- A qualified name on the command line can refer to any module at all: we
461 -- try to load the interface if we don't already have it.
462 lookupQualifiedName :: RdrName -> RnM Name
463 lookupQualifiedName rdr_name
464 | Just (mod,occ) <- isQual_maybe rdr_name
465 -- Note: we want to behave as we would for a source file import here,
466 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
467 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
470 (mod,avails) <- mi_exports iface,
472 name <- availNames avail,
474 ((mod,occ):ns) -> ASSERT (null ns)
476 _ -> unboundName rdr_name
479 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
481 doc = ptext (sLit "Need to find") <+> ppr rdr_name
484 lookupSigOccRn is used for type signatures and pragmas
490 It's clear that the 'f' in the signature must refer to A.f
491 The Haskell98 report does not stipulate this, but it will!
492 So we must treat the 'f' in the signature in the same way
493 as the binding occurrence of 'f', using lookupBndrRn
495 However, consider this case:
499 We don't want to say 'f' is out of scope; instead, we want to
500 return the imported 'f', so that later on the reanamer will
501 correctly report "misplaced type sig".
504 lookupSigOccRn :: Maybe NameSet -- Just ns => source file; these are the binders
506 -- Nothing => hs-boot file; signatures without
507 -- binders are expected
509 -> Located RdrName -> RnM (Located Name)
510 lookupSigOccRn mb_bound_names sig
511 = wrapLocM $ \ rdr_name ->
512 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
514 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
515 Right name -> return name }
517 lookupBindGroupOcc :: Maybe NameSet -- Just ns => source file; these are the binders
519 -- Nothing => hs-boot file; signatures without
520 -- binders are expected
522 -> RdrName -> RnM (Either Message Name)
523 -- Looks up the RdrName, expecting it to resolve to one of the
524 -- bound names passed in. If not, return an appropriate error message
525 lookupBindGroupOcc mb_bound_names what rdr_name
526 = do { local_env <- getLocalRdrEnv
527 ; case lookupLocalRdrEnv local_env rdr_name of
528 Just n -> check_local_name n
529 Nothing -> do -- Not defined in a nested scope
531 { env <- getGlobalRdrEnv
532 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
533 ; case (filter isLocalGRE gres) of
534 (gre:_) -> check_local_name (gre_name gre)
535 -- If there is more than one local GRE for the
536 -- same OccName, that will be reported separately
537 [] | null gres -> bale_out_with empty
538 | otherwise -> bale_out_with import_msg
541 check_local_name name -- The name is in scope, and not imported
542 = case mb_bound_names of
543 Just bound_names | not (name `elemNameSet` bound_names)
544 -> bale_out_with local_msg
545 _other -> return (Right name)
548 = return (Left (sep [ ptext (sLit "The") <+> what
549 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
550 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
553 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
554 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
556 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
557 <+> ptext (sLit "for an imported value")
560 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
561 -- GHC extension: look up both the tycon and data con
562 -- for con-like things
563 -- Complain if neither is in scope
564 lookupLocalDataTcNames bound_names what rdr_name
565 | Just n <- isExact_maybe rdr_name
566 -- Special case for (:), which doesn't get into the GlobalRdrEnv
567 = return [n] -- For this we don't need to try the tycon too
569 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
570 (dataTcOccs rdr_name)
571 ; let (errs, names) = splitEithers mb_gres
572 ; when (null names) (addErr (head errs)) -- Bleat about one only
575 dataTcOccs :: RdrName -> [RdrName]
576 -- If the input is a data constructor, return both it and a type
577 -- constructor. This is useful when we aren't sure which we are
580 | Just n <- isExact_maybe rdr_name -- Ghastly special case
581 , n `hasKey` consDataConKey = [rdr_name] -- see note below
582 | isDataOcc occ = [rdr_name, rdr_name_tc]
583 | otherwise = [rdr_name]
585 occ = rdrNameOcc rdr_name
586 rdr_name_tc = setRdrNameSpace rdr_name tcName
588 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
589 -- and setRdrNameSpace generates an Orig, which is fine
590 -- But it's not fine for (:), because there *is* no corresponding type
591 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
592 -- appear to be in scope (because Orig's simply allocate a new name-cache
593 -- entry) and then we get an error when we use dataTcOccs in
594 -- TcRnDriver.tcRnGetInfo. Large sigh.
598 %*********************************************************
602 %*********************************************************
605 --------------------------------
606 type FastStringEnv a = UniqFM a -- Keyed by FastString
609 emptyFsEnv :: FastStringEnv a
610 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
611 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
613 emptyFsEnv = emptyUFM
614 lookupFsEnv = lookupUFM
615 extendFsEnv = addToUFM
617 --------------------------------
618 type MiniFixityEnv = FastStringEnv (Located Fixity)
619 -- Mini fixity env for the names we're about
620 -- to bind, in a single binding group
622 -- It is keyed by the *FastString*, not the *OccName*, because
623 -- the single fixity decl infix 3 T
624 -- affects both the data constructor T and the type constrctor T
626 -- We keep the location so that if we find
627 -- a duplicate, we can report it sensibly
629 --------------------------------
630 -- Used for nested fixity decls to bind names along with their fixities.
631 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
632 -- Also check for unused binders
633 bindLocalNamesFV_WithFixities :: [Name]
635 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
636 bindLocalNamesFV_WithFixities names fixities thing_inside
637 = bindLocalNamesFV names $
638 extendFixityEnv boundFixities $
641 -- find the names that have fixity decls
642 boundFixities = foldr
644 -- check whether this name has a fixity decl
645 case lookupFsEnv fixities (occNameFS (nameOccName name)) of
646 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
647 Nothing -> acc) [] names
648 -- bind the names; extend the fixity env; do the thing inside
651 --------------------------------
652 lookupFixity is a bit strange.
654 * Nested local fixity decls are put in the local fixity env, which we
655 find with getFixtyEnv
657 * Imported fixities are found in the HIT or PIT
659 * Top-level fixity decls in this module may be for Names that are
660 either Global (constructors, class operations)
661 or Local/Exported (everything else)
662 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
663 We put them all in the local fixity environment
666 lookupFixityRn :: Name -> RnM Fixity
668 = getModule `thenM` \ this_mod ->
669 if nameIsLocalOrFrom this_mod name
670 then do -- It's defined in this module
671 local_fix_env <- getFixityEnv
672 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
673 vcat [ppr name, ppr local_fix_env])
674 return $ lookupFixity local_fix_env name
675 else -- It's imported
676 -- For imported names, we have to get their fixities by doing a
677 -- loadInterfaceForName, and consulting the Ifaces that comes back
678 -- from that, because the interface file for the Name might not
679 -- have been loaded yet. Why not? Suppose you import module A,
680 -- which exports a function 'f', thus;
681 -- module CurrentModule where
683 -- module A( f ) where
685 -- Then B isn't loaded right away (after all, it's possible that
686 -- nothing from B will be used). When we come across a use of
687 -- 'f', we need to know its fixity, and it's then, and only
688 -- then, that we load B.hi. That is what's happening here.
690 -- loadInterfaceForName will find B.hi even if B is a hidden module,
691 -- and that's what we want.
692 loadInterfaceForName doc name `thenM` \ iface -> do {
693 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
694 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
695 return (mi_fix_fn iface (nameOccName name))
698 doc = ptext (sLit "Checking fixity for") <+> ppr name
701 lookupTyFixityRn :: Located Name -> RnM Fixity
702 lookupTyFixityRn (L _ n) = lookupFixityRn n
706 %************************************************************************
709 Dealing with rebindable syntax is driven by the
710 Opt_NoImplicitPrelude dynamic flag.
712 In "deriving" code we don't want to use rebindable syntax
713 so we switch off the flag locally
716 %************************************************************************
718 Haskell 98 says that when you say "3" you get the "fromInteger" from the
719 Standard Prelude, regardless of what is in scope. However, to experiment
720 with having a language that is less coupled to the standard prelude, we're
721 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
722 happens to be in scope. Then you can
724 import MyPrelude as Prelude
725 to get the desired effect.
727 At the moment this just happens for
728 * fromInteger, fromRational on literals (in expressions and patterns)
729 * negate (in expressions)
730 * minus (arising from n+k patterns)
733 We store the relevant Name in the HsSyn tree, in
734 * HsIntegral/HsFractional/HsIsString
738 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
739 fromRationalName etc), but the renamer changes this to the appropriate user
740 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
742 We treat the orignal (standard) names as free-vars too, because the type checker
743 checks the type of the user thing against the type of the standard thing.
746 lookupSyntaxName :: Name -- The standard name
747 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
748 lookupSyntaxName std_name
749 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
750 if implicit_prelude then normal_case
752 -- Get the similarly named thing from the local environment
753 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
754 return (HsVar usr_name, unitFV usr_name)
756 normal_case = return (HsVar std_name, emptyFVs)
758 lookupSyntaxTable :: [Name] -- Standard names
759 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
760 lookupSyntaxTable std_names
761 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
762 if implicit_prelude then normal_case
764 -- Get the similarly named thing from the local environment
765 mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
767 return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
769 normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
773 %*********************************************************
777 %*********************************************************
780 newLocalBndrRn :: Located RdrName -> RnM Name
781 -- Used for non-top-level binders. These should
782 -- never be qualified.
783 newLocalBndrRn (L loc rdr_name)
784 | Just name <- isExact_maybe rdr_name
785 = return name -- This happens in code generated by Template Haskell
786 -- although I'm not sure why. Perhpas it's the call
787 -- in RnPat.newName LetMk?
789 = do { unless (isUnqual rdr_name)
790 (addErrAt loc (badQualBndrErr rdr_name))
792 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
794 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
795 newLocalBndrsRn = mapM newLocalBndrRn
797 ---------------------
798 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
799 checkDupAndShadowedRdrNames doc loc_rdr_names
800 = do { checkDupRdrNames doc loc_rdr_names
802 ; checkShadowedNames doc envs
803 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
805 ---------------------
806 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
810 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
811 = do { checkDupAndShadowedRdrNames doc_str rdr_names_w_loc
813 -- Make fresh Names and extend the environment
814 ; names <- newLocalBndrsRn rdr_names_w_loc
815 ; bindLocalNames names (enclosed_scope names) }
817 bindLocalNames :: [Name] -> RnM a -> RnM a
818 bindLocalNames names enclosed_scope
819 = do { name_env <- getLocalRdrEnv
820 ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
823 bindLocalName :: Name -> RnM a -> RnM a
824 bindLocalName name enclosed_scope
825 = do { name_env <- getLocalRdrEnv
826 ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
829 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
830 bindLocalNamesFV names enclosed_scope
831 = do { (result, fvs) <- bindLocalNames names enclosed_scope
832 ; return (result, delListFromNameSet fvs names) }
835 -------------------------------------
836 -- binLocalsFVRn is the same as bindLocalsRn
837 -- except that it deals with free vars
838 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
839 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
840 bindLocatedLocalsFV doc rdr_names enclosed_scope
841 = bindLocatedLocalsRn doc rdr_names $ \ names ->
842 enclosed_scope names `thenM` \ (thing, fvs) ->
843 return (thing, delListFromNameSet fvs names)
845 -------------------------------------
846 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
847 -> ([LHsTyVarBndr Name] -> RnM a)
849 -- Haskell-98 binding of type variables; e.g. within a data type decl
850 bindTyVarsRn doc_str tyvar_names enclosed_scope
851 = bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
852 do { kind_sigs_ok <- doptM Opt_KindSignatures
853 ; unless (null kinded_tyvars || kind_sigs_ok)
854 (mapM_ (addErr . kindSigErr) kinded_tyvars)
855 ; enclosed_scope (zipWith replace tyvar_names names) }
857 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
858 located_tyvars = hsLTyVarLocNames tyvar_names
859 kinded_tyvars = [n | L _ (KindedTyVar n _) <- tyvar_names]
861 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
862 -- Find the type variables in the pattern type
863 -- signatures that must be brought into scope
864 bindPatSigTyVars tys thing_inside
865 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
866 ; if not scoped_tyvars then
869 do { name_env <- getLocalRdrEnv
870 ; let locd_tvs = [ tv | ty <- tys
871 , tv <- extractHsTyRdrTyVars ty
872 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
873 nubbed_tvs = nubBy eqLocated locd_tvs
874 -- The 'nub' is important. For example:
875 -- f (x :: t) (y :: t) = ....
876 -- We don't want to complain about binding t twice!
878 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
880 doc_sig = text "In a pattern type-signature"
882 bindPatSigTyVarsFV :: [LHsType RdrName]
885 bindPatSigTyVarsFV tys thing_inside
886 = bindPatSigTyVars tys $ \ tvs ->
887 thing_inside `thenM` \ (result,fvs) ->
888 return (result, fvs `delListFromNameSet` tvs)
890 bindSigTyVarsFV :: [Name]
893 bindSigTyVarsFV tvs thing_inside
894 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
895 ; if not scoped_tyvars then
898 bindLocalNamesFV tvs thing_inside }
900 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
901 -- This function is used only in rnSourceDecl on InstDecl
902 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
904 -------------------------------------
905 checkDupRdrNames :: SDoc
908 checkDupRdrNames doc_str rdr_names_w_loc
909 = -- Check for duplicated names in a binding group
910 mapM_ (dupNamesErr getLoc doc_str) dups
912 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
914 checkDupNames :: SDoc
917 checkDupNames doc_str names
918 = -- Check for duplicated names in a binding group
919 mapM_ (dupNamesErr nameSrcSpan doc_str) dups
921 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
923 -------------------------------------
924 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
925 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
926 = ifOptM Opt_WarnNameShadowing $
927 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
928 ; mapM_ check_shadow loc_rdr_names }
930 check_shadow (loc, occ)
931 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
933 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
934 | otherwise = do { gres' <- filterM is_shadowed_gre gres
935 ; complain (map pprNameProvenance gres') }
937 complain [] = return ()
938 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
939 mb_local = lookupLocalRdrOcc local_env occ
940 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
941 -- Make an Unqualified RdrName and look that up, so that
942 -- we don't find any GREs that are in scope qualified-only
944 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
945 -- Returns False for record selectors that are shadowed, when
946 -- punning or wild-cards are on (cf Trac #2723)
947 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
948 = do { dflags <- getDOpts
949 ; if (dopt Opt_RecordPuns dflags || dopt Opt_RecordWildCards dflags)
950 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
952 is_shadowed_gre _other = return True
954 is_rec_fld gre -- Return True for record selector ids
955 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
956 ; return (gre_name gre `elemNameSet` fld_set) }
957 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
958 ; return (isRecordSelector sel_id) }
962 %************************************************************************
964 \subsection{Free variable manipulation}
966 %************************************************************************
970 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
971 mapFvRn f xs = do stuff <- mapM f xs
973 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
975 -- because some of the rename functions are CPSed:
976 -- maps the function across the list from left to right;
977 -- collects all the free vars into one set
978 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
979 -> [a] -> ([b] -> RnM c) -> RnM c
981 mapFvRnCPS _ [] cont = cont []
982 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
983 mapFvRnCPS f xs $ \ xs' ->
988 %************************************************************************
990 \subsection{Envt utility functions}
992 %************************************************************************
995 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
996 warnUnusedModules mods
997 = ifOptM Opt_WarnUnusedImports (mapM_ bleat mods)
999 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
1000 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
1001 <+> text "is imported, but nothing from it is used,",
1002 nest 2 (ptext (sLit "except perhaps instances visible in")
1003 <+> quotes (ppr m)),
1004 ptext (sLit "To suppress this warning, use:")
1005 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
1008 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1009 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1010 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
1012 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1013 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1014 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1016 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1017 check_unused flag bound_names used_names
1018 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1020 -------------------------
1022 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1024 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1026 warnUnusedLocals :: [Name] -> RnM ()
1027 warnUnusedLocals names
1028 = warnUnusedBinds [(n,LocalDef) | n<-names]
1030 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1031 warnUnusedBinds names = mapM_ warnUnusedName (filter reportable names)
1032 where reportable (name,_)
1033 | isWiredInName name = False -- Don't report unused wired-in names
1034 -- Otherwise we get a zillion warnings
1036 | otherwise = not (startsWithUnderscore (nameOccName name))
1038 -------------------------
1040 warnUnusedName :: (Name, Provenance) -> RnM ()
1041 warnUnusedName (name, LocalDef)
1042 = addUnusedWarning name (nameSrcSpan name)
1043 (ptext (sLit "Defined but not used"))
1045 warnUnusedName (name, Imported is)
1048 warn spec = addUnusedWarning name span msg
1050 span = importSpecLoc spec
1051 pp_mod = quotes (ppr (importSpecModule spec))
1052 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1054 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1055 addUnusedWarning name span msg
1058 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1059 <+> quotes (ppr name)]
1063 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1064 addNameClashErrRn rdr_name names
1065 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1066 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1069 msg1 = ptext (sLit "either") <+> mk_ref np1
1070 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1071 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1073 shadowedNameWarn :: SDoc -> OccName -> [SDoc] -> SDoc
1074 shadowedNameWarn doc occ shadowed_locs
1075 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1076 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1077 nest 2 (vcat shadowed_locs)]
1080 unknownNameErr :: RdrName -> SDoc
1081 unknownNameErr rdr_name
1082 = vcat [ hang (ptext (sLit "Not in scope:"))
1083 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1084 <+> quotes (ppr rdr_name))
1087 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1090 perhapsForallMsg :: SDoc
1092 = vcat [ ptext (sLit "Perhaps you intended to use -XRankNTypes or similar flag")
1093 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1095 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1096 unknownSubordinateErr doc op -- Doc is "method of class" or
1097 -- "field of constructor"
1098 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1100 badOrigBinding :: RdrName -> SDoc
1102 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1103 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1105 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1106 dupNamesErr get_loc descriptor names
1107 = addErrAt big_loc $
1108 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1109 locations, descriptor]
1111 locs = map get_loc names
1112 big_loc = foldr1 combineSrcSpans locs
1113 one_line = isOneLineSpan big_loc
1114 locations | one_line = empty
1115 | otherwise = ptext (sLit "Bound at:") <+>
1116 vcat (map ppr (sortLe (<=) locs))
1118 kindSigErr :: Outputable a => a -> SDoc
1120 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1121 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1124 badQualBndrErr :: RdrName -> SDoc
1125 badQualBndrErr rdr_name
1126 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1128 opDeclErr :: RdrName -> SDoc
1130 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1131 2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))