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, lookupRecordBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable,
17 lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
20 newLocalsRn, newIPNameRn,
21 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,
38 #include "HsVersions.h"
40 import LoadIface ( loadInterfaceForName, loadSrcInterface )
41 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
43 import RdrHsSyn ( extractHsTyRdrTyVars )
45 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity)
46 import TcEnv ( tcLookupDataCon, tcLookupField, isBrackStage )
48 import Id ( isRecordSelector )
49 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
50 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
54 import DataCon ( dataConFieldLabels )
56 import Module ( Module, ModuleName )
57 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
58 consDataConKey, hasKey, forall_tv_RDR )
60 import BasicTypes ( IPName, mapIPName, Fixity )
61 import ErrUtils ( Message )
66 import ListSetOps ( removeDups )
75 thenM :: Monad a => a b -> (b -> a c) -> a c
78 thenM_ :: Monad a => a b -> a c -> a c
81 returnM :: Monad m => a -> m a
84 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
87 mappM_ :: (Monad m) => (a -> m b) -> [a] -> m ()
90 checkM :: Monad m => Bool -> m () -> m ()
94 %*********************************************************
98 %*********************************************************
101 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
102 newTopSrcBinder this_mod (L loc rdr_name)
103 | Just name <- isExact_maybe rdr_name
104 = -- This is here to catch
105 -- (a) Exact-name binders created by Template Haskell
106 -- (b) The PrelBase defn of (say) [] and similar, for which
107 -- the parser reads the special syntax and returns an Exact RdrName
108 -- We are at a binding site for the name, so check first that it
109 -- the current module is the correct one; otherwise GHC can get
110 -- very confused indeed. This test rejects code like
111 -- data T = (,) Int Int
112 -- unless we are in GHC.Tup
113 ASSERT2( isExternalName name, ppr name )
114 do { checkM (this_mod == nameModule name)
115 (addErrAt loc (badOrigBinding rdr_name))
119 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
120 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
121 (addErrAt loc (badOrigBinding rdr_name))
122 -- When reading External Core we get Orig names as binders,
123 -- but they should agree with the module gotten from the monad
125 -- We can get built-in syntax showing up here too, sadly. If you type
127 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
128 -- uses setRdrNameSpace to make it into a data constructors. At that point
129 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
130 -- Hence the badOrigBinding error message.
132 -- Except for the ":Main.main = ..." definition inserted into
133 -- the Main module; ugh!
135 -- Because of this latter case, we call newGlobalBinder with a module from
136 -- the RdrName, not from the environment. In principle, it'd be fine to
137 -- have an arbitrary mixture of external core definitions in a single module,
138 -- (apart from module-initialisation issues, perhaps).
139 ; newGlobalBinder rdr_mod rdr_occ loc }
140 --TODO, should pass the whole span
143 = do { checkM (not (isQual rdr_name))
144 (addErrAt loc (badQualBndrErr rdr_name))
145 -- Binders should not be qualified; if they are, and with a different
146 -- module name, we we get a confusing "M.T is not in scope" error later
149 ; if isBrackStage stage then
150 -- We are inside a TH bracket, so make an *Internal* name
151 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
152 do { uniq <- newUnique
153 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
156 newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
159 %*********************************************************
161 Source code occurrences
163 %*********************************************************
165 Looking up a name in the RnEnv.
168 lookupTopBndrRn :: RdrName -> RnM Name
169 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
172 Nothing -> do traceRn $ text "lookupTopBndrRn"
175 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
176 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
178 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
179 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
180 -- and there may be several imported 'f's too, which must not confuse us.
181 -- For example, this is OK:
183 -- infix 9 f -- The 'f' here does not need to be qualified
184 -- f x = x -- Nor here, of course
185 -- So we have to filter out the non-local ones.
187 -- A separate function (importsFromLocalDecls) reports duplicate top level
188 -- decls, so here it's safe just to choose an arbitrary one.
190 -- There should never be a qualified name in a binding position in Haskell,
191 -- but there can be if we have read in an external-Core file.
192 -- The Haskell parser checks for the illegal qualified name in Haskell
193 -- source files, so we don't need to do so here.
195 lookupTopBndrRn_maybe rdr_name
196 | Just name <- isExact_maybe rdr_name
197 = returnM (Just name)
199 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
200 -- This deals with the case of derived bindings, where
201 -- we don't bother to call newTopSrcBinder first
202 -- We assume there is no "parent" name
203 = do { loc <- getSrcSpanM
204 ; n <- newGlobalBinder rdr_mod rdr_occ loc
208 = do { mb_gre <- lookupGreLocalRn rdr_name
210 Nothing -> returnM Nothing
211 Just gre -> returnM (Just $ gre_name gre) }
214 -----------------------------------------------
215 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
216 -- This is called on the method name on the left-hand side of an
217 -- instance declaration binding. eg. instance Functor T where
219 -- ^^^^ called on this
220 -- Regardless of how many unqualified fmaps are in scope, we want
221 -- the one that comes from the Functor class.
223 -- Furthermore, note that we take no account of whether the
224 -- name is only in scope qualified. I.e. even if method op is
225 -- in scope as M.op, we still allow plain 'op' on the LHS of
227 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
229 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
230 is_op (GRE {gre_par = ParentIs n}) = n == cls
233 -----------------------------------------------
234 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
235 -- Used for record construction and pattern matching
236 -- When the -XDisambiguateRecordFields flag is on, take account of the
237 -- constructor name to disambiguate which field to use; it's just the
238 -- same as for instance decls
240 -- NB: Consider this:
241 -- module Foo where { data R = R { fld :: Int } }
242 -- module Odd where { import Foo; fld x = x { fld = 3 } }
243 -- Arguably this should work, because the reference to 'fld' is
244 -- unambiguous because there is only one field id 'fld' in scope.
245 -- But currently it's rejected.
246 lookupRecordBndr Nothing rdr_name
247 = lookupLocatedGlobalOccRn rdr_name
248 lookupRecordBndr (Just (L _ data_con)) rdr_name
249 = do { flag_on <- doptM Opt_DisambiguateRecordFields
251 then lookupLocatedGlobalOccRn rdr_name
253 fields <- lookupConstructorFields data_con
254 ; let is_field gre = gre_name gre `elem` fields
255 ; lookup_located_sub_bndr is_field doc rdr_name
258 doc = ptext (sLit "field of constructor") <+> quotes (ppr data_con)
261 lookupConstructorFields :: Name -> RnM [Name]
262 -- Look up the fields of a given constructor
263 -- * For constructors from this module, use the record field env,
264 -- which is itself gathered from the (as yet un-typechecked)
267 -- * For constructors from imported modules, use the *type* environment
268 -- since imported modles are already compiled, the info is conveniently
271 lookupConstructorFields con_name
272 = do { this_mod <- getModule
273 ; if nameIsLocalOrFrom this_mod con_name then
274 do { RecFields field_env _ <- getRecFieldEnv
275 ; return (lookupNameEnv field_env con_name `orElse` []) }
277 do { con <- tcLookupDataCon con_name
278 ; return (dataConFieldLabels con) } }
280 -----------------------------------------------
281 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
282 -> SDoc -> Located RdrName
283 -> RnM (Located Name)
284 lookup_located_sub_bndr is_good doc rdr_name
285 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
287 lookup_sub_bndr :: (GlobalRdrElt -> Bool) -> SDoc -> RdrName -> RnM Name
288 lookup_sub_bndr is_good doc rdr_name
289 | isUnqual rdr_name -- Find all the things the rdr-name maps to
290 = do { -- and pick the one with the right parent name
291 ; env <- getGlobalRdrEnv
292 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
293 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
294 -- The latter does pickGREs, but we want to allow 'x'
295 -- even if only 'M.x' is in scope
296 [gre] -> return (gre_name gre)
297 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
298 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
299 ; return (mkUnboundName rdr_name) }
300 gres -> do { addNameClashErrRn rdr_name gres
301 ; return (gre_name (head gres)) }
304 | otherwise -- Occurs in derived instances, where we just
305 -- refer directly to the right method with an Orig
306 -- And record fields can be Quals: C { F.f = x }
307 = lookupGlobalOccRn rdr_name
309 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
310 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
312 -- Looking up family names in type instances is a subtle affair. The family
313 -- may be imported, in which case we need to lookup the occurence of a global
314 -- name. Alternatively, the family may be in the same binding group (and in
315 -- fact in a declaration processed later), and we need to create a new top
318 -- So, also this is strictly speaking an occurence, we cannot raise an error
319 -- message yet for instances without a family declaration. This will happen
320 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
322 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
323 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
324 = do { mb_gre <- lookupGreRn_maybe rdr_name
326 Just gre -> returnM (gre_name gre)
327 Nothing -> newTopSrcBinder mod lrdr_name }
329 --------------------------------------------------
331 --------------------------------------------------
333 getLookupOccRn :: RnM (Name -> Maybe Name)
335 = getLocalRdrEnv `thenM` \ local_env ->
336 return (lookupLocalRdrOcc local_env . nameOccName)
338 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
339 lookupLocatedOccRn = wrapLocM lookupOccRn
341 -- lookupOccRn looks up an occurrence of a RdrName
342 lookupOccRn :: RdrName -> RnM Name
344 = getLocalRdrEnv `thenM` \ local_env ->
345 case lookupLocalRdrEnv local_env rdr_name of
346 Just name -> returnM name
347 Nothing -> lookupGlobalOccRn rdr_name
349 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
350 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
352 lookupGlobalOccRn :: RdrName -> RnM Name
353 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
354 -- environment. Adds an error message if the RdrName is not in scope.
355 -- Also has a special case for GHCi.
357 lookupGlobalOccRn rdr_name
358 = do { -- First look up the name in the normal environment.
359 mb_name <- lookupGlobalOccRn_maybe rdr_name
364 { -- We allow qualified names on the command line to refer to
365 -- *any* name exported by any module in scope, just as if there
366 -- was an "import qualified M" declaration for every module.
367 allow_qual <- doptM Opt_ImplicitImportQualified
369 -- This test is not expensive,
370 -- and only happens for failed lookups
371 ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
372 then lookupQualifiedName rdr_name
373 else unboundName rdr_name } } }
375 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
376 -- No filter function; does not report an error on failure
378 lookupGlobalOccRn_maybe rdr_name
379 | Just n <- isExact_maybe rdr_name -- This happens in derived code
382 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
383 = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
386 = do { mb_gre <- lookupGreRn_maybe rdr_name
388 Nothing -> return Nothing
389 Just gre -> return (Just (gre_name gre)) }
392 unboundName :: RdrName -> RnM Name
394 = do { addErr (unknownNameErr rdr_name)
395 ; env <- getGlobalRdrEnv;
396 ; traceRn (vcat [unknownNameErr rdr_name,
397 ptext (sLit "Global envt is:"),
398 nest 3 (pprGlobalRdrEnv env)])
399 ; returnM (mkUnboundName rdr_name) }
401 --------------------------------------------------
402 -- Lookup in the Global RdrEnv of the module
403 --------------------------------------------------
405 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
406 -- Just look up the RdrName in the GlobalRdrEnv
407 lookupGreRn_maybe rdr_name
408 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
410 lookupGreRn :: RdrName -> RnM GlobalRdrElt
411 -- If not found, add error message, and return a fake GRE
413 = do { mb_gre <- lookupGreRn_maybe rdr_name
415 Just gre -> return gre ;
417 { traceRn $ text "lookupGreRn"
418 ; name <- unboundName rdr_name
419 ; return (GRE { gre_name = name, gre_par = NoParent,
420 gre_prov = LocalDef }) }}}
422 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
423 -- Similar, but restricted to locally-defined things
424 lookupGreLocalRn rdr_name
425 = lookupGreRn_help rdr_name lookup_fn
427 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
429 lookupGreRn_help :: RdrName -- Only used in error message
430 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
431 -> RnM (Maybe GlobalRdrElt)
432 -- Checks for exactly one match; reports deprecations
433 -- Returns Nothing, without error, if too few
434 lookupGreRn_help rdr_name lookup
435 = do { env <- getGlobalRdrEnv
437 [] -> returnM Nothing
438 [gre] -> returnM (Just gre)
439 gres -> do { addNameClashErrRn rdr_name gres
440 ; returnM (Just (head gres)) } }
442 ------------------------------
444 ------------------------------
446 -- A qualified name on the command line can refer to any module at all: we
447 -- try to load the interface if we don't already have it.
448 lookupQualifiedName :: RdrName -> RnM Name
449 lookupQualifiedName rdr_name
450 | Just (mod,occ) <- isQual_maybe rdr_name
451 -- Note: we want to behave as we would for a source file import here,
452 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
453 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
456 (mod,avails) <- mi_exports iface,
458 name <- availNames avail,
460 ((mod,occ):ns) -> ASSERT (null ns)
462 _ -> unboundName rdr_name
465 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
467 doc = ptext (sLit "Need to find") <+> ppr rdr_name
470 lookupSigOccRn is used for type signatures and pragmas
476 It's clear that the 'f' in the signature must refer to A.f
477 The Haskell98 report does not stipulate this, but it will!
478 So we must treat the 'f' in the signature in the same way
479 as the binding occurrence of 'f', using lookupBndrRn
481 However, consider this case:
485 We don't want to say 'f' is out of scope; instead, we want to
486 return the imported 'f', so that later on the reanamer will
487 correctly report "misplaced type sig".
490 lookupSigOccRn :: Maybe NameSet -- Just ns => source file; these are the binders
492 -- Nothing => hs-boot file; signatures without
493 -- binders are expected
495 -> Located RdrName -> RnM (Located Name)
496 lookupSigOccRn mb_bound_names sig
497 = wrapLocM $ \ rdr_name ->
498 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
500 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
501 Right name -> return name }
503 lookupBindGroupOcc :: Maybe NameSet -- Just ns => source file; these are the binders
505 -- Nothing => hs-boot file; signatures without
506 -- binders are expected
508 -> RdrName -> RnM (Either Message Name)
509 -- Looks up the RdrName, expecting it to resolve to one of the
510 -- bound names passed in. If not, return an appropriate error message
511 lookupBindGroupOcc mb_bound_names what rdr_name
512 = do { local_env <- getLocalRdrEnv
513 ; case lookupLocalRdrEnv local_env rdr_name of
514 Just n -> check_local_name n
515 Nothing -> do -- Not defined in a nested scope
517 { env <- getGlobalRdrEnv
518 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
519 ; case (filter isLocalGRE gres) of
520 (gre:_) -> check_local_name (gre_name gre)
521 -- If there is more than one local GRE for the
522 -- same OccName, that will be reported separately
523 [] | null gres -> bale_out_with empty
524 | otherwise -> bale_out_with import_msg
527 check_local_name name -- The name is in scope, and not imported
528 = case mb_bound_names of
529 Just bound_names | not (name `elemNameSet` bound_names)
530 -> bale_out_with local_msg
531 _other -> return (Right name)
534 = return (Left (sep [ ptext (sLit "The") <+> what
535 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
536 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
539 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
540 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
542 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
543 <+> ptext (sLit "for an imported value")
546 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
547 -- GHC extension: look up both the tycon and data con
548 -- for con-like things
549 -- Complain if neither is in scope
550 lookupLocalDataTcNames bound_names what rdr_name
551 | Just n <- isExact_maybe rdr_name
552 -- Special case for (:), which doesn't get into the GlobalRdrEnv
553 = return [n] -- For this we don't need to try the tycon too
555 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
556 (dataTcOccs rdr_name)
557 ; let (errs, names) = splitEithers mb_gres
558 ; when (null names) (addErr (head errs)) -- Bleat about one only
561 dataTcOccs :: RdrName -> [RdrName]
562 -- If the input is a data constructor, return both it and a type
563 -- constructor. This is useful when we aren't sure which we are
566 | Just n <- isExact_maybe rdr_name -- Ghastly special case
567 , n `hasKey` consDataConKey = [rdr_name] -- see note below
568 | isDataOcc occ = [rdr_name, rdr_name_tc]
569 | otherwise = [rdr_name]
571 occ = rdrNameOcc rdr_name
572 rdr_name_tc = setRdrNameSpace rdr_name tcName
574 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
575 -- and setRdrNameSpace generates an Orig, which is fine
576 -- But it's not fine for (:), because there *is* no corresponding type
577 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
578 -- appear to be in scope (because Orig's simply allocate a new name-cache
579 -- entry) and then we get an error when we use dataTcOccs in
580 -- TcRnDriver.tcRnGetInfo. Large sigh.
584 %*********************************************************
588 %*********************************************************
591 --------------------------------
592 type FastStringEnv a = UniqFM a -- Keyed by FastString
595 emptyFsEnv :: FastStringEnv a
596 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
597 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
599 emptyFsEnv = emptyUFM
600 lookupFsEnv = lookupUFM
601 extendFsEnv = addToUFM
603 --------------------------------
604 type MiniFixityEnv = FastStringEnv (Located Fixity)
605 -- Mini fixity env for the names we're about
606 -- to bind, in a single binding group
608 -- It is keyed by the *FastString*, not the *OccName*, because
609 -- the single fixity decl infix 3 T
610 -- affects both the data constructor T and the type constrctor T
612 -- We keep the location so that if we find
613 -- a duplicate, we can report it sensibly
615 --------------------------------
616 -- Used for nested fixity decls to bind names along with their fixities.
617 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
618 -- Also check for unused binders
619 bindLocalNamesFV_WithFixities :: [Name]
621 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
622 bindLocalNamesFV_WithFixities names fixities thing_inside
623 = bindLocalNamesFV names $
624 extendFixityEnv boundFixities $
627 -- find the names that have fixity decls
628 boundFixities = foldr
630 -- check whether this name has a fixity decl
631 case lookupFsEnv fixities (occNameFS (nameOccName name)) of
632 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
633 Nothing -> acc) [] names
634 -- bind the names; extend the fixity env; do the thing inside
637 --------------------------------
638 lookupFixity is a bit strange.
640 * Nested local fixity decls are put in the local fixity env, which we
641 find with getFixtyEnv
643 * Imported fixities are found in the HIT or PIT
645 * Top-level fixity decls in this module may be for Names that are
646 either Global (constructors, class operations)
647 or Local/Exported (everything else)
648 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
649 We put them all in the local fixity environment
652 lookupFixityRn :: Name -> RnM Fixity
654 = getModule `thenM` \ this_mod ->
655 if nameIsLocalOrFrom this_mod name
656 then do -- It's defined in this module
657 local_fix_env <- getFixityEnv
658 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
659 vcat [ppr name, ppr local_fix_env])
660 return $ lookupFixity local_fix_env name
661 else -- It's imported
662 -- For imported names, we have to get their fixities by doing a
663 -- loadInterfaceForName, and consulting the Ifaces that comes back
664 -- from that, because the interface file for the Name might not
665 -- have been loaded yet. Why not? Suppose you import module A,
666 -- which exports a function 'f', thus;
667 -- module CurrentModule where
669 -- module A( f ) where
671 -- Then B isn't loaded right away (after all, it's possible that
672 -- nothing from B will be used). When we come across a use of
673 -- 'f', we need to know its fixity, and it's then, and only
674 -- then, that we load B.hi. That is what's happening here.
676 -- loadInterfaceForName will find B.hi even if B is a hidden module,
677 -- and that's what we want.
678 loadInterfaceForName doc name `thenM` \ iface -> do {
679 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
680 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
681 returnM (mi_fix_fn iface (nameOccName name))
684 doc = ptext (sLit "Checking fixity for") <+> ppr name
687 lookupTyFixityRn :: Located Name -> RnM Fixity
688 lookupTyFixityRn (L _ n) = lookupFixityRn n
692 %************************************************************************
695 Dealing with rebindable syntax is driven by the
696 Opt_NoImplicitPrelude dynamic flag.
698 In "deriving" code we don't want to use rebindable syntax
699 so we switch off the flag locally
702 %************************************************************************
704 Haskell 98 says that when you say "3" you get the "fromInteger" from the
705 Standard Prelude, regardless of what is in scope. However, to experiment
706 with having a language that is less coupled to the standard prelude, we're
707 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
708 happens to be in scope. Then you can
710 import MyPrelude as Prelude
711 to get the desired effect.
713 At the moment this just happens for
714 * fromInteger, fromRational on literals (in expressions and patterns)
715 * negate (in expressions)
716 * minus (arising from n+k patterns)
719 We store the relevant Name in the HsSyn tree, in
720 * HsIntegral/HsFractional/HsIsString
724 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
725 fromRationalName etc), but the renamer changes this to the appropriate user
726 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
728 We treat the orignal (standard) names as free-vars too, because the type checker
729 checks the type of the user thing against the type of the standard thing.
732 lookupSyntaxName :: Name -- The standard name
733 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
734 lookupSyntaxName std_name
735 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
736 if implicit_prelude then normal_case
738 -- Get the similarly named thing from the local environment
739 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
740 returnM (HsVar usr_name, unitFV usr_name)
742 normal_case = returnM (HsVar std_name, emptyFVs)
744 lookupSyntaxTable :: [Name] -- Standard names
745 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
746 lookupSyntaxTable std_names
747 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
748 if implicit_prelude then normal_case
750 -- Get the similarly named thing from the local environment
751 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
753 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
755 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
759 %*********************************************************
763 %*********************************************************
766 newLocalsRn :: [Located RdrName] -> RnM [Name]
767 newLocalsRn rdr_names_w_loc
768 = newUniqueSupply `thenM` \ us ->
769 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
771 mk (L loc rdr_name) uniq
772 | Just name <- isExact_maybe rdr_name = name
773 -- This happens in code generated by Template Haskell
774 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
775 -- We only bind unqualified names here
776 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
777 mkInternalName uniq (rdrNameOcc rdr_name) loc
779 ---------------------
780 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
781 checkDupAndShadowedRdrNames doc loc_rdr_names
782 = do { checkDupRdrNames doc loc_rdr_names
784 ; checkShadowedNames doc envs
785 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
787 ---------------------
788 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
792 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
793 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
795 -- Make fresh Names and extend the environment
796 newLocalsRn rdr_names_w_loc `thenM` \names ->
797 bindLocalNames names (enclosed_scope names)
799 bindLocalNames :: [Name] -> RnM a -> RnM a
800 bindLocalNames names enclosed_scope
801 = getLocalRdrEnv `thenM` \ name_env ->
802 setLocalRdrEnv (extendLocalRdrEnv name_env names)
805 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
806 bindLocalNamesFV names enclosed_scope
807 = do { (result, fvs) <- bindLocalNames names enclosed_scope
808 ; returnM (result, delListFromNameSet fvs names) }
811 -------------------------------------
812 -- binLocalsFVRn is the same as bindLocalsRn
813 -- except that it deals with free vars
814 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
815 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
816 bindLocatedLocalsFV doc rdr_names enclosed_scope
817 = bindLocatedLocalsRn doc rdr_names $ \ names ->
818 enclosed_scope names `thenM` \ (thing, fvs) ->
819 returnM (thing, delListFromNameSet fvs names)
821 -------------------------------------
822 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
823 -> ([LHsTyVarBndr Name] -> RnM a)
825 -- Haskell-98 binding of type variables; e.g. within a data type decl
826 bindTyVarsRn doc_str tyvar_names enclosed_scope
827 = bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
828 do { kind_sigs_ok <- doptM Opt_KindSignatures
829 ; checkM (null kinded_tyvars || kind_sigs_ok)
830 (mapM_ (addErr . kindSigErr) kinded_tyvars)
831 ; enclosed_scope (zipWith replace tyvar_names names) }
833 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
834 located_tyvars = hsLTyVarLocNames tyvar_names
835 kinded_tyvars = [n | L _ (KindedTyVar n _) <- tyvar_names]
837 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
838 -- Find the type variables in the pattern type
839 -- signatures that must be brought into scope
840 bindPatSigTyVars tys thing_inside
841 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
842 ; if not scoped_tyvars then
845 do { name_env <- getLocalRdrEnv
846 ; let locd_tvs = [ tv | ty <- tys
847 , tv <- extractHsTyRdrTyVars ty
848 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
849 nubbed_tvs = nubBy eqLocated locd_tvs
850 -- The 'nub' is important. For example:
851 -- f (x :: t) (y :: t) = ....
852 -- We don't want to complain about binding t twice!
854 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
856 doc_sig = text "In a pattern type-signature"
858 bindPatSigTyVarsFV :: [LHsType RdrName]
861 bindPatSigTyVarsFV tys thing_inside
862 = bindPatSigTyVars tys $ \ tvs ->
863 thing_inside `thenM` \ (result,fvs) ->
864 returnM (result, fvs `delListFromNameSet` tvs)
866 bindSigTyVarsFV :: [Name]
869 bindSigTyVarsFV tvs thing_inside
870 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
871 ; if not scoped_tyvars then
874 bindLocalNamesFV tvs thing_inside }
876 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
877 -- This function is used only in rnSourceDecl on InstDecl
878 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
880 -------------------------------------
881 checkDupRdrNames :: SDoc
884 checkDupRdrNames doc_str rdr_names_w_loc
885 = -- Check for duplicated names in a binding group
886 mappM_ (dupNamesErr getLoc doc_str) dups
888 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
890 checkDupNames :: SDoc
893 checkDupNames doc_str names
894 = -- Check for duplicated names in a binding group
895 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
897 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
899 -------------------------------------
900 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
901 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
902 = ifOptM Opt_WarnNameShadowing $
903 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
904 ; mappM_ check_shadow loc_rdr_names }
906 check_shadow (loc, occ)
907 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
908 | otherwise = do { gres' <- filterM is_shadowed_gre gres
909 ; complain (map pprNameProvenance gres') }
911 complain [] = return ()
912 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
913 mb_local = lookupLocalRdrOcc local_env occ
914 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
915 -- Make an Unqualified RdrName and look that up, so that
916 -- we don't find any GREs that are in scope qualified-only
918 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
919 -- Returns False for record selectors that are shadowed, when
920 -- punning or wild-cards are on (cf Trac #2723)
921 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
922 = do { dflags <- getDOpts
923 ; if (dopt Opt_RecordPuns dflags || dopt Opt_RecordWildCards dflags)
924 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
926 is_shadowed_gre _other = return True
928 is_rec_fld gre -- Return True for record selector ids
929 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
930 ; return (gre_name gre `elemNameSet` fld_set) }
931 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
932 ; return (isRecordSelector sel_id) }
936 %************************************************************************
938 \subsection{Free variable manipulation}
940 %************************************************************************
944 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
945 mapFvRn f xs = do stuff <- mappM f xs
947 (ys, fvs_s) -> returnM (ys, plusFVs fvs_s)
949 -- because some of the rename functions are CPSed:
950 -- maps the function across the list from left to right;
951 -- collects all the free vars into one set
952 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
953 -> [a] -> ([b] -> RnM c) -> RnM c
955 mapFvRnCPS _ [] cont = cont []
956 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
957 mapFvRnCPS f xs $ \ xs' ->
962 %************************************************************************
964 \subsection{Envt utility functions}
966 %************************************************************************
969 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
970 warnUnusedModules mods
971 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
973 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
974 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
975 <+> text "is imported, but nothing from it is used,",
976 nest 2 (ptext (sLit "except perhaps instances visible in")
978 ptext (sLit "To suppress this warning, use:")
979 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
982 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
983 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
984 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
986 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
987 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
988 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
990 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
991 check_unused flag bound_names used_names
992 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
994 -------------------------
996 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
998 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1000 warnUnusedLocals :: [Name] -> RnM ()
1001 warnUnusedLocals names
1002 = warnUnusedBinds [(n,LocalDef) | n<-names]
1004 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1005 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
1006 where reportable (name,_)
1007 | isWiredInName name = False -- Don't report unused wired-in names
1008 -- Otherwise we get a zillion warnings
1010 | otherwise = reportIfUnused (nameOccName name)
1012 -------------------------
1014 warnUnusedName :: (Name, Provenance) -> RnM ()
1015 warnUnusedName (name, LocalDef)
1016 = addUnusedWarning name (nameSrcSpan name)
1017 (ptext (sLit "Defined but not used"))
1019 warnUnusedName (name, Imported is)
1022 warn spec = addUnusedWarning name span msg
1024 span = importSpecLoc spec
1025 pp_mod = quotes (ppr (importSpecModule spec))
1026 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1028 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1029 addUnusedWarning name span msg
1032 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1033 <+> quotes (ppr name)]
1037 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1038 addNameClashErrRn rdr_name names
1039 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1040 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1043 msg1 = ptext (sLit "either") <+> mk_ref np1
1044 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1045 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1047 shadowedNameWarn :: SDoc -> OccName -> [SDoc] -> SDoc
1048 shadowedNameWarn doc occ shadowed_locs
1049 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1050 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1051 nest 2 (vcat shadowed_locs)]
1054 unknownNameErr :: RdrName -> SDoc
1055 unknownNameErr rdr_name
1056 = vcat [ hang (ptext (sLit "Not in scope:"))
1057 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1058 <+> quotes (ppr rdr_name))
1061 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1064 perhapsForallMsg :: SDoc
1066 = vcat [ ptext (sLit "Perhaps you intended to use -XRankNTypes or similar flag")
1067 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1069 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1070 unknownSubordinateErr doc op -- Doc is "method of class" or
1071 -- "field of constructor"
1072 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1074 badOrigBinding :: RdrName -> SDoc
1076 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1077 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1079 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1080 dupNamesErr get_loc descriptor names
1081 = addErrAt big_loc $
1082 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1083 locations, descriptor]
1085 locs = map get_loc names
1086 big_loc = foldr1 combineSrcSpans locs
1087 one_line = isOneLineSpan big_loc
1088 locations | one_line = empty
1089 | otherwise = ptext (sLit "Bound at:") <+>
1090 vcat (map ppr (sortLe (<=) locs))
1092 kindSigErr :: Outputable a => a -> SDoc
1094 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1095 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1098 badQualBndrErr :: RdrName -> SDoc
1099 badQualBndrErr rdr_name
1100 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name