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, lookupGlobalOccRn,
12 lookupLocalDataTcNames, lookupSrcOcc_maybe,
14 lookupFixityRn, lookupTyFixityRn,
15 lookupInstDeclBndr, lookupRecordBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable, lookupImportedName,
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, 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, isBrackStage )
46 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
47 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
51 import DataCon ( dataConFieldLabels )
53 import Module ( Module, ModuleName )
54 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
55 consDataConKey, hasKey, forall_tv_RDR )
57 import BasicTypes ( IPName, mapIPName, Fixity )
58 import ErrUtils ( Message )
63 import ListSetOps ( removeDups )
72 thenM :: Monad a => a b -> (b -> a c) -> a c
75 thenM_ :: Monad a => a b -> a c -> a c
78 returnM :: Monad m => a -> m a
81 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
84 mappM_ :: (Monad m) => (a -> m b) -> [a] -> m ()
87 checkM :: Monad m => Bool -> m () -> m ()
91 %*********************************************************
95 %*********************************************************
98 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
99 newTopSrcBinder this_mod (L loc rdr_name)
100 | Just name <- isExact_maybe rdr_name
101 = -- This is here to catch
102 -- (a) Exact-name binders created by Template Haskell
103 -- (b) The PrelBase defn of (say) [] and similar, for which
104 -- the parser reads the special syntax and returns an Exact RdrName
105 -- We are at a binding site for the name, so check first that it
106 -- the current module is the correct one; otherwise GHC can get
107 -- very confused indeed. This test rejects code like
108 -- data T = (,) Int Int
109 -- unless we are in GHC.Tup
110 ASSERT2( isExternalName name, ppr name )
111 do { checkM (this_mod == nameModule name)
112 (addErrAt loc (badOrigBinding rdr_name))
116 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
117 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
118 (addErrAt loc (badOrigBinding rdr_name))
119 -- When reading External Core we get Orig names as binders,
120 -- but they should agree with the module gotten from the monad
122 -- We can get built-in syntax showing up here too, sadly. If you type
124 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
125 -- uses setRdrNameSpace to make it into a data constructors. At that point
126 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
127 -- Hence the badOrigBinding error message.
129 -- Except for the ":Main.main = ..." definition inserted into
130 -- the Main module; ugh!
132 -- Because of this latter case, we call newGlobalBinder with a module from
133 -- the RdrName, not from the environment. In principle, it'd be fine to
134 -- have an arbitrary mixture of external core definitions in a single module,
135 -- (apart from module-initialisation issues, perhaps).
136 ; newGlobalBinder rdr_mod rdr_occ loc }
137 --TODO, should pass the whole span
140 = do { checkM (not (isQual rdr_name))
141 (addErrAt loc (badQualBndrErr rdr_name))
142 -- Binders should not be qualified; if they are, and with a different
143 -- module name, we we get a confusing "M.T is not in scope" error later
146 ; if isBrackStage stage then
147 -- We are inside a TH bracket, so make an *Internal* name
148 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
149 do { uniq <- newUnique
150 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
153 newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
156 %*********************************************************
158 Source code occurrences
160 %*********************************************************
162 Looking up a name in the RnEnv.
165 lookupTopBndrRn :: RdrName -> RnM Name
166 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
169 Nothing -> do traceRn $ text "lookupTopBndrRn"
172 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
173 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
175 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
176 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
177 -- and there may be several imported 'f's too, which must not confuse us.
178 -- For example, this is OK:
180 -- infix 9 f -- The 'f' here does not need to be qualified
181 -- f x = x -- Nor here, of course
182 -- So we have to filter out the non-local ones.
184 -- A separate function (importsFromLocalDecls) reports duplicate top level
185 -- decls, so here it's safe just to choose an arbitrary one.
187 -- There should never be a qualified name in a binding position in Haskell,
188 -- but there can be if we have read in an external-Core file.
189 -- The Haskell parser checks for the illegal qualified name in Haskell
190 -- source files, so we don't need to do so here.
192 lookupTopBndrRn_maybe rdr_name
193 | Just name <- isExact_maybe rdr_name
194 = returnM (Just name)
196 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
197 -- This deals with the case of derived bindings, where
198 -- we don't bother to call newTopSrcBinder first
199 -- We assume there is no "parent" name
200 = do { loc <- getSrcSpanM
201 ; n <- newGlobalBinder rdr_mod rdr_occ loc
205 = do { mb_gre <- lookupGreLocalRn rdr_name
207 Nothing -> returnM Nothing
208 Just gre -> returnM (Just $ gre_name gre) }
211 -----------------------------------------------
212 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
213 -- This is called on the method name on the left-hand side of an
214 -- instance declaration binding. eg. instance Functor T where
216 -- ^^^^ called on this
217 -- Regardless of how many unqualified fmaps are in scope, we want
218 -- the one that comes from the Functor class.
220 -- Furthermore, note that we take no account of whether the
221 -- name is only in scope qualified. I.e. even if method op is
222 -- in scope as M.op, we still allow plain 'op' on the LHS of
224 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
226 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
227 is_op (GRE {gre_par = ParentIs n}) = n == cls
230 -----------------------------------------------
231 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
232 -- Used for record construction and pattern matching
233 -- When the -fdisambiguate-record-fields flag is on, take account of the
234 -- constructor name to disambiguate which field to use; it's just the
235 -- same as for instance decls
236 lookupRecordBndr Nothing rdr_name
237 = lookupLocatedGlobalOccRn rdr_name
238 lookupRecordBndr (Just (L _ data_con)) rdr_name
239 = do { flag_on <- doptM Opt_DisambiguateRecordFields
241 then lookupLocatedGlobalOccRn rdr_name
243 fields <- lookupConstructorFields data_con
244 ; let is_field gre = gre_name gre `elem` fields
245 ; lookup_located_sub_bndr is_field doc rdr_name
248 doc = ptext (sLit "field of constructor") <+> quotes (ppr data_con)
251 lookupConstructorFields :: Name -> RnM [Name]
252 -- Look up the fields of a given constructor
253 -- * For constructors from this module, use the record field env,
254 -- which is itself gathered from the (as yet un-typechecked)
257 -- * For constructors from imported modules, use the *type* environment
258 -- since imported modles are already compiled, the info is conveniently
261 lookupConstructorFields con_name
262 = do { this_mod <- getModule
263 ; if nameIsLocalOrFrom this_mod con_name then
264 do { field_env <- getRecFieldEnv
265 ; return (lookupNameEnv field_env con_name `orElse` []) }
267 do { con <- tcLookupDataCon con_name
268 ; return (dataConFieldLabels con) } }
270 -----------------------------------------------
271 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
272 -> SDoc -> Located RdrName
273 -> RnM (Located Name)
274 lookup_located_sub_bndr is_good doc rdr_name
275 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
277 lookup_sub_bndr :: (GlobalRdrElt -> Bool) -> SDoc -> RdrName -> RnM Name
278 lookup_sub_bndr is_good doc rdr_name
279 | isUnqual rdr_name -- Find all the things the rdr-name maps to
280 = do { -- and pick the one with the right parent name
281 ; env <- getGlobalRdrEnv
282 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
283 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
284 -- The latter does pickGREs, but we want to allow 'x'
285 -- even if only 'M.x' is in scope
286 [gre] -> return (gre_name gre)
287 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
288 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
289 ; return (mkUnboundName rdr_name) }
290 gres -> do { addNameClashErrRn rdr_name gres
291 ; return (gre_name (head gres)) }
294 | otherwise -- Occurs in derived instances, where we just
295 -- refer directly to the right method
296 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
297 -- NB: qualified names are rejected by the parser
298 lookupImportedName rdr_name
300 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
301 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
303 -- Looking up family names in type instances is a subtle affair. The family
304 -- may be imported, in which case we need to lookup the occurence of a global
305 -- name. Alternatively, the family may be in the same binding group (and in
306 -- fact in a declaration processed later), and we need to create a new top
309 -- So, also this is strictly speaking an occurence, we cannot raise an error
310 -- message yet for instances without a family declaration. This will happen
311 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
313 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
314 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
315 = do { mb_gre <- lookupGreRn_maybe rdr_name
317 Just gre -> returnM (gre_name gre)
318 Nothing -> newTopSrcBinder mod lrdr_name }
320 --------------------------------------------------
322 --------------------------------------------------
324 getLookupOccRn :: RnM (Name -> Maybe Name)
326 = getLocalRdrEnv `thenM` \ local_env ->
327 return (lookupLocalRdrOcc local_env . nameOccName)
329 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
330 lookupLocatedOccRn = wrapLocM lookupOccRn
332 -- lookupOccRn looks up an occurrence of a RdrName
333 lookupOccRn :: RdrName -> RnM Name
335 = getLocalRdrEnv `thenM` \ local_env ->
336 case lookupLocalRdrEnv local_env rdr_name of
337 Just name -> returnM name
338 Nothing -> lookupGlobalOccRn rdr_name
340 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
341 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
343 lookupGlobalOccRn :: RdrName -> RnM Name
344 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
345 -- environment. It's used only for
346 -- record field names
347 -- class op names in class and instance decls
349 lookupGlobalOccRn rdr_name
350 | not (isSrcRdrName rdr_name)
351 = lookupImportedName rdr_name
355 -- First look up the name in the normal environment.
356 mb_gre <- lookupGreRn_maybe rdr_name
358 Just gre -> returnM (gre_name gre) ;
361 -- We allow qualified names on the command line to refer to
362 -- *any* name exported by any module in scope, just as if
363 -- there was an "import qualified M" declaration for every
365 allow_qual <- doptM Opt_ImplicitImportQualified
367 -- This test is not expensive,
368 -- and only happens for failed lookups
369 if isQual rdr_name && allow_qual && mod == iNTERACTIVE
370 then lookupQualifiedName rdr_name
371 else unboundName rdr_name
374 lookupImportedName :: RdrName -> TcRnIf m n Name
375 -- Lookup the occurrence of an imported name
376 -- The RdrName is *always* qualified or Exact
377 -- Treat it as an original name, and conjure up the Name
378 -- Usually it's Exact or Orig, but it can be Qual if it
379 -- comes from an hi-boot file. (This minor infelicity is
380 -- just to reduce duplication in the parser.)
381 lookupImportedName rdr_name
382 | Just n <- isExact_maybe rdr_name
383 -- This happens in derived code
386 -- Always Orig, even when reading a .hi-boot file
387 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
388 = lookupOrig rdr_mod rdr_occ
391 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
393 unboundName :: RdrName -> RnM Name
395 = do { addErr (unknownNameErr rdr_name)
396 ; env <- getGlobalRdrEnv;
397 ; traceRn (vcat [unknownNameErr rdr_name,
398 ptext (sLit "Global envt is:"),
399 nest 3 (pprGlobalRdrEnv env)])
400 ; returnM (mkUnboundName rdr_name) }
402 --------------------------------------------------
403 -- Lookup in the Global RdrEnv of the module
404 --------------------------------------------------
406 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
407 -- No filter function; does not report an error on failure
408 lookupSrcOcc_maybe rdr_name
409 = do { mb_gre <- lookupGreRn_maybe rdr_name
411 Nothing -> returnM Nothing
412 Just gre -> returnM (Just (gre_name gre)) }
414 -------------------------
415 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
416 -- Just look up the RdrName in the GlobalRdrEnv
417 lookupGreRn_maybe rdr_name
418 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
420 lookupGreRn :: RdrName -> RnM GlobalRdrElt
421 -- If not found, add error message, and return a fake GRE
423 = do { mb_gre <- lookupGreRn_maybe rdr_name
425 Just gre -> return gre ;
427 { traceRn $ text "lookupGreRn"
428 ; name <- unboundName rdr_name
429 ; return (GRE { gre_name = name, gre_par = NoParent,
430 gre_prov = LocalDef }) }}}
432 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
433 -- Similar, but restricted to locally-defined things
434 lookupGreLocalRn rdr_name
435 = lookupGreRn_help rdr_name lookup_fn
437 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
439 lookupGreRn_help :: RdrName -- Only used in error message
440 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
441 -> RnM (Maybe GlobalRdrElt)
442 -- Checks for exactly one match; reports deprecations
443 -- Returns Nothing, without error, if too few
444 lookupGreRn_help rdr_name lookup
445 = do { env <- getGlobalRdrEnv
447 [] -> returnM Nothing
448 [gre] -> returnM (Just gre)
449 gres -> do { addNameClashErrRn rdr_name gres
450 ; returnM (Just (head gres)) } }
452 ------------------------------
454 ------------------------------
456 -- A qualified name on the command line can refer to any module at all: we
457 -- try to load the interface if we don't already have it.
458 lookupQualifiedName :: RdrName -> RnM Name
459 lookupQualifiedName rdr_name
460 | Just (mod,occ) <- isQual_maybe rdr_name
461 -- Note: we want to behave as we would for a source file import here,
462 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
463 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
466 (mod,avails) <- mi_exports iface,
468 name <- availNames avail,
470 ((mod,occ):ns) -> ASSERT (null ns)
472 _ -> unboundName rdr_name
475 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
477 doc = ptext (sLit "Need to find") <+> ppr rdr_name
480 lookupSigOccRn is used for type signatures and pragmas
486 It's clear that the 'f' in the signature must refer to A.f
487 The Haskell98 report does not stipulate this, but it will!
488 So we must treat the 'f' in the signature in the same way
489 as the binding occurrence of 'f', using lookupBndrRn
491 However, consider this case:
495 We don't want to say 'f' is out of scope; instead, we want to
496 return the imported 'f', so that later on the reanamer will
497 correctly report "misplaced type sig".
500 lookupSigOccRn :: Maybe NameSet -- Just ns => source file; these are the binders
502 -- Nothing => hs-boot file; signatures without
503 -- binders are expected
505 -> Located RdrName -> RnM (Located Name)
506 lookupSigOccRn mb_bound_names sig
507 = wrapLocM $ \ rdr_name ->
508 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
510 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
511 Right name -> return name }
513 lookupBindGroupOcc :: Maybe NameSet -- Just ns => source file; these are the binders
515 -- Nothing => hs-boot file; signatures without
516 -- binders are expected
518 -> RdrName -> RnM (Either Message Name)
519 -- Looks up the RdrName, expecting it to resolve to one of the
520 -- bound names passed in. If not, return an appropriate error message
521 lookupBindGroupOcc mb_bound_names what rdr_name
522 = do { local_env <- getLocalRdrEnv
523 ; case lookupLocalRdrEnv local_env rdr_name of
524 Just n -> check_local_name n
525 Nothing -> do -- Not defined in a nested scope
527 { env <- getGlobalRdrEnv
528 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
529 ; case (filter isLocalGRE gres) of
530 (gre:_) -> check_local_name (gre_name gre)
531 -- If there is more than one local GRE for the
532 -- same OccName, that will be reported separately
533 [] | null gres -> bale_out_with empty
534 | otherwise -> bale_out_with import_msg
537 check_local_name name -- The name is in scope, and not imported
538 = case mb_bound_names of
539 Just bound_names | not (name `elemNameSet` bound_names)
540 -> bale_out_with local_msg
541 _other -> return (Right name)
544 = return (Left (sep [ ptext (sLit "The") <+> what
545 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
546 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
549 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
550 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
552 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
553 <+> ptext (sLit "for an imported value")
556 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
557 -- GHC extension: look up both the tycon and data con
558 -- for con-like things
559 -- Complain if neither is in scope
560 lookupLocalDataTcNames bound_names what rdr_name
561 | Just n <- isExact_maybe rdr_name
562 -- Special case for (:), which doesn't get into the GlobalRdrEnv
563 = return [n] -- For this we don't need to try the tycon too
565 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
566 (dataTcOccs rdr_name)
567 ; let (errs, names) = splitEithers mb_gres
568 ; when (null names) (addErr (head errs)) -- Bleat about one only
571 dataTcOccs :: RdrName -> [RdrName]
572 -- If the input is a data constructor, return both it and a type
573 -- constructor. This is useful when we aren't sure which we are
576 | Just n <- isExact_maybe rdr_name -- Ghastly special case
577 , n `hasKey` consDataConKey = [rdr_name] -- see note below
578 | isDataOcc occ = [rdr_name, rdr_name_tc]
579 | otherwise = [rdr_name]
581 occ = rdrNameOcc rdr_name
582 rdr_name_tc = setRdrNameSpace rdr_name tcName
584 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
585 -- and setRdrNameSpace generates an Orig, which is fine
586 -- But it's not fine for (:), because there *is* no corresponding type
587 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
588 -- appear to be in scope (because Orig's simply allocate a new name-cache
589 -- entry) and then we get an error when we use dataTcOccs in
590 -- TcRnDriver.tcRnGetInfo. Large sigh.
594 %*********************************************************
598 %*********************************************************
601 --------------------------------
602 type FastStringEnv a = UniqFM a -- Keyed by FastString
605 emptyFsEnv :: FastStringEnv a
606 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
607 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
609 emptyFsEnv = emptyUFM
610 lookupFsEnv = lookupUFM
611 extendFsEnv = addToUFM
613 --------------------------------
614 type MiniFixityEnv = FastStringEnv (Located Fixity)
615 -- Mini fixity env for the names we're about
616 -- to bind, in a single binding group
618 -- It is keyed by the *FastString*, not the *OccName*, because
619 -- the single fixity decl infix 3 T
620 -- affects both the data constructor T and the type constrctor T
622 -- We keep the location so that if we find
623 -- a duplicate, we can report it sensibly
625 --------------------------------
626 -- Used for nested fixity decls to bind names along with their fixities.
627 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
628 -- Also check for unused binders
629 bindLocalNamesFV_WithFixities :: [Name]
631 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
632 bindLocalNamesFV_WithFixities names fixities thing_inside
633 = bindLocalNamesFV names $
634 extendFixityEnv boundFixities $
637 -- find the names that have fixity decls
638 boundFixities = foldr
640 -- check whether this name has a fixity decl
641 case lookupFsEnv fixities (occNameFS (nameOccName name)) of
642 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
643 Nothing -> acc) [] names
644 -- bind the names; extend the fixity env; do the thing inside
647 --------------------------------
648 lookupFixity is a bit strange.
650 * Nested local fixity decls are put in the local fixity env, which we
651 find with getFixtyEnv
653 * Imported fixities are found in the HIT or PIT
655 * Top-level fixity decls in this module may be for Names that are
656 either Global (constructors, class operations)
657 or Local/Exported (everything else)
658 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
659 We put them all in the local fixity environment
662 lookupFixityRn :: Name -> RnM Fixity
664 = getModule `thenM` \ this_mod ->
665 if nameIsLocalOrFrom this_mod name
666 then do -- It's defined in this module
667 local_fix_env <- getFixityEnv
668 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
669 vcat [ppr name, ppr local_fix_env])
670 return $ lookupFixity local_fix_env name
671 else -- It's imported
672 -- For imported names, we have to get their fixities by doing a
673 -- loadInterfaceForName, and consulting the Ifaces that comes back
674 -- from that, because the interface file for the Name might not
675 -- have been loaded yet. Why not? Suppose you import module A,
676 -- which exports a function 'f', thus;
677 -- module CurrentModule where
679 -- module A( f ) where
681 -- Then B isn't loaded right away (after all, it's possible that
682 -- nothing from B will be used). When we come across a use of
683 -- 'f', we need to know its fixity, and it's then, and only
684 -- then, that we load B.hi. That is what's happening here.
686 -- loadInterfaceForName will find B.hi even if B is a hidden module,
687 -- and that's what we want.
688 loadInterfaceForName doc name `thenM` \ iface -> do {
689 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
690 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
691 returnM (mi_fix_fn iface (nameOccName name))
694 doc = ptext (sLit "Checking fixity for") <+> ppr name
697 lookupTyFixityRn :: Located Name -> RnM Fixity
698 lookupTyFixityRn (L _ n) = lookupFixityRn n
702 %************************************************************************
705 Dealing with rebindable syntax is driven by the
706 Opt_NoImplicitPrelude dynamic flag.
708 In "deriving" code we don't want to use rebindable syntax
709 so we switch off the flag locally
712 %************************************************************************
714 Haskell 98 says that when you say "3" you get the "fromInteger" from the
715 Standard Prelude, regardless of what is in scope. However, to experiment
716 with having a language that is less coupled to the standard prelude, we're
717 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
718 happens to be in scope. Then you can
720 import MyPrelude as Prelude
721 to get the desired effect.
723 At the moment this just happens for
724 * fromInteger, fromRational on literals (in expressions and patterns)
725 * negate (in expressions)
726 * minus (arising from n+k patterns)
729 We store the relevant Name in the HsSyn tree, in
730 * HsIntegral/HsFractional/HsIsString
734 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
735 fromRationalName etc), but the renamer changes this to the appropriate user
736 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
738 We treat the orignal (standard) names as free-vars too, because the type checker
739 checks the type of the user thing against the type of the standard thing.
742 lookupSyntaxName :: Name -- The standard name
743 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
744 lookupSyntaxName std_name
745 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
746 if implicit_prelude then normal_case
748 -- Get the similarly named thing from the local environment
749 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
750 returnM (HsVar usr_name, unitFV usr_name)
752 normal_case = returnM (HsVar std_name, emptyFVs)
754 lookupSyntaxTable :: [Name] -- Standard names
755 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
756 lookupSyntaxTable std_names
757 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
758 if implicit_prelude then normal_case
760 -- Get the similarly named thing from the local environment
761 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
763 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
765 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
769 %*********************************************************
773 %*********************************************************
776 newLocalsRn :: [Located RdrName] -> RnM [Name]
777 newLocalsRn rdr_names_w_loc
778 = newUniqueSupply `thenM` \ us ->
779 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
781 mk (L loc rdr_name) uniq
782 | Just name <- isExact_maybe rdr_name = name
783 -- This happens in code generated by Template Haskell
784 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
785 -- We only bind unqualified names here
786 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
787 mkInternalName uniq (rdrNameOcc rdr_name) loc
789 ---------------------
790 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
791 checkDupAndShadowedRdrNames doc loc_rdr_names
792 = do { checkDupRdrNames doc loc_rdr_names
794 ; checkShadowedNames doc envs
795 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
797 ---------------------
798 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
802 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
803 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
805 -- Make fresh Names and extend the environment
806 newLocalsRn rdr_names_w_loc `thenM` \names ->
807 bindLocalNames names (enclosed_scope names)
809 bindLocalNames :: [Name] -> RnM a -> RnM a
810 bindLocalNames names enclosed_scope
811 = getLocalRdrEnv `thenM` \ name_env ->
812 setLocalRdrEnv (extendLocalRdrEnv name_env names)
815 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
816 bindLocalNamesFV names enclosed_scope
817 = do { (result, fvs) <- bindLocalNames names enclosed_scope
818 ; returnM (result, delListFromNameSet fvs names) }
821 -------------------------------------
822 -- binLocalsFVRn is the same as bindLocalsRn
823 -- except that it deals with free vars
824 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
825 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
826 bindLocatedLocalsFV doc rdr_names enclosed_scope
827 = bindLocatedLocalsRn doc rdr_names $ \ names ->
828 enclosed_scope names `thenM` \ (thing, fvs) ->
829 returnM (thing, delListFromNameSet fvs names)
831 -------------------------------------
832 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
833 -> ([LHsTyVarBndr Name] -> RnM a)
835 -- Haskell-98 binding of type variables; e.g. within a data type decl
836 bindTyVarsRn doc_str tyvar_names enclosed_scope
838 located_tyvars = hsLTyVarLocNames tyvar_names
840 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
841 enclosed_scope (zipWith replace tyvar_names names)
843 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
845 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
846 -- Find the type variables in the pattern type
847 -- signatures that must be brought into scope
848 bindPatSigTyVars tys thing_inside
849 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
850 ; if not scoped_tyvars then
853 do { name_env <- getLocalRdrEnv
854 ; let locd_tvs = [ tv | ty <- tys
855 , tv <- extractHsTyRdrTyVars ty
856 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
857 nubbed_tvs = nubBy eqLocated locd_tvs
858 -- The 'nub' is important. For example:
859 -- f (x :: t) (y :: t) = ....
860 -- We don't want to complain about binding t twice!
862 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
864 doc_sig = text "In a pattern type-signature"
866 bindPatSigTyVarsFV :: [LHsType RdrName]
869 bindPatSigTyVarsFV tys thing_inside
870 = bindPatSigTyVars tys $ \ tvs ->
871 thing_inside `thenM` \ (result,fvs) ->
872 returnM (result, fvs `delListFromNameSet` tvs)
874 bindSigTyVarsFV :: [Name]
877 bindSigTyVarsFV tvs thing_inside
878 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
879 ; if not scoped_tyvars then
882 bindLocalNamesFV tvs thing_inside }
884 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
885 -- This function is used only in rnSourceDecl on InstDecl
886 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
888 -------------------------------------
889 checkDupRdrNames :: SDoc
892 checkDupRdrNames doc_str rdr_names_w_loc
893 = -- Check for duplicated names in a binding group
894 mappM_ (dupNamesErr getLoc doc_str) dups
896 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
898 checkDupNames :: SDoc
901 checkDupNames doc_str names
902 = -- Check for duplicated names in a binding group
903 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
905 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
907 -------------------------------------
908 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
909 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
910 = ifOptM Opt_WarnNameShadowing $
911 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
912 ; mappM_ check_shadow loc_rdr_names }
914 check_shadow (loc, occ)
915 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
916 | not (null gres) = complain (map pprNameProvenance gres)
917 | otherwise = return ()
919 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
920 mb_local = lookupLocalRdrOcc local_env occ
921 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
922 -- Make an Unqualified RdrName and look that up, so that
923 -- we don't find any GREs that are in scope qualified-only
927 %************************************************************************
929 \subsection{Free variable manipulation}
931 %************************************************************************
935 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
936 mapFvRn f xs = do stuff <- mappM f xs
938 (ys, fvs_s) -> returnM (ys, plusFVs fvs_s)
940 -- because some of the rename functions are CPSed:
941 -- maps the function across the list from left to right;
942 -- collects all the free vars into one set
943 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
944 -> [a] -> ([b] -> RnM c) -> RnM c
946 mapFvRnCPS _ [] cont = cont []
947 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
948 mapFvRnCPS f xs $ \ xs' ->
953 %************************************************************************
955 \subsection{Envt utility functions}
957 %************************************************************************
960 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
961 warnUnusedModules mods
962 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
964 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
965 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
966 <+> text "is imported, but nothing from it is used,",
967 nest 2 (ptext (sLit "except perhaps instances visible in")
969 ptext (sLit "To suppress this warning, use:")
970 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
973 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
974 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
975 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
977 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
978 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
979 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
981 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
982 check_unused flag bound_names used_names
983 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
985 -------------------------
987 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
989 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
991 warnUnusedLocals :: [Name] -> RnM ()
992 warnUnusedLocals names
993 = warnUnusedBinds [(n,LocalDef) | n<-names]
995 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
996 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
997 where reportable (name,_)
998 | isWiredInName name = False -- Don't report unused wired-in names
999 -- Otherwise we get a zillion warnings
1001 | otherwise = reportIfUnused (nameOccName name)
1003 -------------------------
1005 warnUnusedName :: (Name, Provenance) -> RnM ()
1006 warnUnusedName (name, LocalDef)
1007 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
1008 (ptext (sLit "Defined but not used"))
1010 warnUnusedName (name, Imported is)
1013 warn spec = addUnusedWarning name span msg
1015 span = importSpecLoc spec
1016 pp_mod = quotes (ppr (importSpecModule spec))
1017 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1019 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1020 addUnusedWarning name span msg
1023 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1024 <+> quotes (ppr name)]
1028 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1029 addNameClashErrRn rdr_name names
1030 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1031 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1034 msg1 = ptext (sLit "either") <+> mk_ref np1
1035 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1036 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1038 shadowedNameWarn :: SDoc -> OccName -> [SDoc] -> SDoc
1039 shadowedNameWarn doc occ shadowed_locs
1040 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1041 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1042 nest 2 (vcat shadowed_locs)]
1045 unknownNameErr :: RdrName -> SDoc
1046 unknownNameErr rdr_name
1047 = vcat [ hang (ptext (sLit "Not in scope:"))
1048 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1049 <+> quotes (ppr rdr_name))
1052 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1055 perhapsForallMsg :: SDoc
1057 = vcat [ ptext (sLit "Perhaps you intended to use -XRankNTypes or similar flag")
1058 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1060 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1061 unknownSubordinateErr doc op -- Doc is "method of class" or
1062 -- "field of constructor"
1063 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1065 badOrigBinding :: RdrName -> SDoc
1067 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1068 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1070 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1071 dupNamesErr get_loc descriptor names
1072 = addErrAt big_loc $
1073 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1074 locations, descriptor]
1076 locs = map get_loc names
1077 big_loc = foldr1 combineSrcSpans locs
1078 one_line = isOneLineSpan big_loc
1079 locations | one_line = empty
1080 | otherwise = ptext (sLit "Bound at:") <+>
1081 vcat (map ppr (sortLe (<=) locs))
1083 badQualBndrErr :: RdrName -> SDoc
1084 badQualBndrErr rdr_name
1085 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name