2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnEnv]{Environment manipulation for the renamer monad}
7 module RnEnv where -- Export everything
9 #include "HsVersions.h"
11 import {-# SOURCE #-} RnHiFiles( loadInterface )
13 import FlattenInfo ( namesNeededForFlattening )
15 import RdrHsSyn ( RdrNameHsType, RdrNameFixitySig, extractHsTyRdrTyVars )
16 import RdrName ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
17 mkRdrUnqual, mkRdrQual, setRdrNameSpace, rdrNameOcc,
18 lookupRdrEnv, rdrEnvToList, elemRdrEnv,
19 extendRdrEnv, addListToRdrEnv, emptyRdrEnv,
20 isExact_maybe, unqualifyRdrName
22 import HsTypes ( hsTyVarName, replaceTyVarName )
23 import HscTypes ( Provenance(..), pprNameProvenance, hasBetterProv,
24 ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..),
25 GenAvailInfo(..), AvailInfo, Avails,
26 ModIface(..), NameCache(..), OrigNameCache,
27 Deprecations(..), lookupDeprec, isLocalGRE,
28 extendLocalRdrEnv, availName, availNames,
32 import Name ( Name, getName, nameIsLocalOrFrom,
33 isWiredInName, mkInternalName, mkExternalName, mkIPName,
34 nameSrcLoc, nameOccName, setNameSrcLoc, nameModule )
36 import OccName ( OccName, tcName, isDataOcc, occNameFlavour, reportIfUnused )
37 import Module ( Module, ModuleName, moduleName, mkHomeModule,
38 lookupModuleEnv, lookupModuleEnvByName, extendModuleEnv_C )
39 import PrelNames ( mkUnboundName, intTyConName,
40 boolTyConName, funTyConName,
41 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
42 eqStringName, printName, integerTyConName,
43 bindIOName, returnIOName, failIOName, thenIOName,
47 import DsMeta ( templateHaskellNames, qTyConName )
49 import TysWiredIn ( unitTyCon ) -- A little odd
50 import Finder ( findModule )
53 import SrcLoc ( SrcLoc, importedSrcLoc )
55 import ListSetOps ( removeDups, equivClasses )
56 import BasicTypes ( mapIPName, FixitySig(..) )
59 import FastString ( FastString )
62 %*********************************************************
64 \subsection{Making new names}
66 %*********************************************************
69 newTopBinder :: Module -> RdrName -> SrcLoc -> TcRn m Name
70 newTopBinder mod rdr_name loc
71 | Just name <- isExact_maybe rdr_name
75 = ASSERT( rdr_mod == moduleName mod || rdr_mod == rOOT_MAIN_Name )
76 -- When reading External Core we get Orig names as binders,
77 -- but they should agree with the module gotten from the monad
79 -- Except for the ":Main.main = ..." definition inserted into
82 -- Because of this latter case, we take the module from the RdrName,
83 -- not from the environment. In principle, it'd be fine to have an
84 -- arbitrary mixture of external core definitions in a single module,
85 -- (apart from module-initialisation issues, perhaps).
86 newGlobalName (mkHomeModule rdr_mod) (rdrNameOcc rdr_name) loc
89 = newGlobalName mod (rdrNameOcc rdr_name) loc
91 rdr_mod = rdrNameModule rdr_name
93 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
94 newGlobalName mod occ loc
95 = -- First check the cache
96 getNameCache `thenM` \ name_supply ->
97 case lookupOrigNameCache (nsNames name_supply) mod occ of
99 -- A hit in the cache! We are at the binding site of the name.
100 -- This is the moment when we know the defining SrcLoc
101 -- of the Name, so we set the SrcLoc of the name we return.
103 -- Main reason: then (bogus) multiple bindings of the same Name
104 -- get different SrcLocs can can be reported as such.
106 -- Possible other reason: it might be in the cache because we
107 -- encountered an occurrence before the binding site for an
108 -- implicitly-imported Name. Perhaps the current SrcLoc is
109 -- better... but not really: it'll still just say 'imported'
111 -- IMPORTANT: Don't mess with wired-in names.
112 -- Their wired-in-ness is in the SrcLoc
114 Just name | isWiredInName name -> returnM name
115 | otherwise -> returnM (setNameSrcLoc name loc)
117 -- Miss in the cache!
118 -- Build a completely new Name, and put it in the cache
119 Nothing -> addNewName name_supply mod occ loc
121 -- Look up a "system name" in the name cache.
122 -- This is done by the type checker...
123 lookupSysName :: Name -- Base name
124 -> (OccName -> OccName) -- Occurrence name modifier
125 -> TcRn m Name -- System name
126 lookupSysName base_name mk_sys_occ
127 = newGlobalName (nameModule base_name)
128 (mk_sys_occ (nameOccName base_name))
129 (nameSrcLoc base_name)
132 newGlobalNameFromRdrName rdr_name -- Qualified original name
133 = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
135 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
136 -- This one starts with a ModuleName, not a Module, because
137 -- we may be simply looking at an occurrence M.x in an interface file.
139 -- Used for *occurrences*. Even if we get a miss in the
140 -- original-name cache, we make a new External Name.
141 -- We get its Module either from the OrigNameCache, or (if this
142 -- is the first Name from that module) from the Finder
144 -- In the case of a miss, we have to make up the SrcLoc, but that's
145 -- OK: it must be an implicitly-imported Name, and that never occurs
146 -- in an error message.
148 newGlobalName2 mod_name occ
149 = getNameCache `thenM` \ name_supply ->
151 new_name mod = addNewName name_supply mod occ importedSrcLoc
153 case lookupModuleEnvByName (nsNames name_supply) mod_name of
154 Just (mod, occ_env) ->
155 -- There are some names from this module already
156 -- Next, look up in the OccNameEnv
157 case lookupFM occ_env occ of
158 Just name -> returnM name
159 Nothing -> new_name mod
161 Nothing -> -- No names from this module yet
162 ioToTcRn (findModule mod_name) `thenM` \ mb_loc ->
164 Right (mod, _) -> new_name mod
166 getDOpts `thenM` \ dflags ->
167 addErr (noIfaceErr dflags mod_name False files) `thenM_`
168 -- Things have really gone wrong at this point,
169 -- so having the wrong package info in the
170 -- Module is the least of our worries.
171 new_name (mkHomeModule mod_name)
174 newIPName rdr_name_ip
175 = getNameCache `thenM` \ name_supply ->
177 ipcache = nsIPs name_supply
179 case lookupFM ipcache key of
180 Just name_ip -> returnM name_ip
181 Nothing -> setNameCache new_ns `thenM_`
184 (us', us1) = splitUniqSupply (nsUniqs name_supply)
185 uniq = uniqFromSupply us1
186 name_ip = mapIPName mk_name rdr_name_ip
187 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
188 new_ipcache = addToFM ipcache key name_ip
189 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
191 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
193 -- A local helper function
194 addNewName name_supply mod occ loc
195 = setNameCache new_name_supply `thenM_`
198 (new_name_supply, name) = newExternalName name_supply mod occ loc
201 newExternalName :: NameCache -> Module -> OccName -> SrcLoc
203 -- Allocate a new unique, manufacture a new External Name,
204 -- put it in the cache, and return the two
205 newExternalName name_supply mod occ loc
206 = (new_name_supply, name)
208 (us', us1) = splitUniqSupply (nsUniqs name_supply)
209 uniq = uniqFromSupply us1
210 name = mkExternalName uniq mod occ loc
211 new_cache = extend_name_cache (nsNames name_supply) mod occ name
212 new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
214 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
215 lookupOrigNameCache nc mod occ
216 = case lookupModuleEnv nc mod of
218 Just (_, occ_env) -> lookupFM occ_env occ
220 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
221 extendOrigNameCache nc name
222 = extend_name_cache nc (nameModule name) (nameOccName name) name
224 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
225 extend_name_cache nc mod occ name
226 = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
228 combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
231 %*********************************************************
233 \subsection{Looking up names}
235 %*********************************************************
237 Looking up a name in the RnEnv.
240 lookupBndrRn rdr_name
241 = getLocalRdrEnv `thenM` \ local_env ->
242 case lookupRdrEnv local_env rdr_name of
243 Just name -> returnM name
244 Nothing -> lookupTopBndrRn rdr_name
246 lookupTopBndrRn rdr_name
247 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
248 -- and there may be several imported 'f's too, which must not confuse us.
249 -- So we have to filter out the non-local ones.
250 -- A separate function (importsFromLocalDecls) reports duplicate top level
251 -- decls, so here it's safe just to choose an arbitrary one.
253 -- There should never be a qualified name in a binding position in Haskell,
254 -- but there can be if we have read in an external-Core file.
255 -- The Haskell parser checks for the illegal qualified name in Haskell
256 -- source files, so we don't need to do so here.
258 = getModeRn `thenM` \ mode ->
261 getSrcLocM `thenM` \ loc ->
262 newTopBinder mod rdr_name loc
264 other -> lookupTopSrcBndr rdr_name
266 lookupTopSrcBndr :: RdrName -> TcRn m Name
267 lookupTopSrcBndr rdr_name
268 = lookupTopSrcBndr_maybe rdr_name `thenM` \ maybe_name ->
270 Just name -> returnM name
271 Nothing -> unboundName rdr_name
274 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
275 -- Look up a source-code binder
277 -- Ignores imported names; for example, this is OK:
279 -- infix 9 f -- The 'f' here does not need to be qualified
280 -- f x = x -- Nor here, of course
282 lookupTopSrcBndr_maybe rdr_name
283 | Just name <- isExact_maybe rdr_name
284 -- This is here just to catch the PrelBase defn of (say) [] and similar
285 -- The parser reads the special syntax and returns an Exact RdrName
286 -- But the global_env contains only Qual RdrNames, so we won't
287 -- find it there; instead just get the name via the Orig route
289 -- We are at a binding site for the name, so check first that it
290 -- the current module is the correct one; otherwise GHC can get
291 -- very confused indeed. This test rejects code like
292 -- data T = (,) Int Int
293 -- unless we are in GHC.Tup
294 = getModule `thenM` \ mod ->
295 checkErr (moduleName mod == moduleName (nameModule name))
296 (badOrigBinding rdr_name) `thenM_`
300 = getGlobalRdrEnv `thenM` \ global_env ->
301 case lookupRdrEnv global_env rdr_name of
302 Nothing -> returnM Nothing
303 Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
304 [] -> returnM Nothing
305 (n:ns) -> returnM (Just n)
308 -- lookupSigOccRn is used for type signatures and pragmas
314 -- It's clear that the 'f' in the signature must refer to A.f
315 -- The Haskell98 report does not stipulate this, but it will!
316 -- So we must treat the 'f' in the signature in the same way
317 -- as the binding occurrence of 'f', using lookupBndrRn
318 lookupSigOccRn :: RdrName -> RnM Name
319 lookupSigOccRn = lookupBndrRn
321 -- lookupInstDeclBndr is used for the binders in an
322 -- instance declaration. Here we use the class name to
325 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
326 -- We use the selector name as the binder
327 lookupInstDeclBndr cls_name rdr_name
329 = -- Find all the things the class op name maps to
330 -- and pick the one with the right parent name
331 getGblEnv `thenM` \ gbl_env ->
333 avail_env = imp_env (tcg_imports gbl_env)
334 occ = rdrNameOcc rdr_name
336 case lookupAvailEnv_maybe avail_env cls_name of
338 -- If the class itself isn't in scope, then cls_name will
339 -- be unboundName, and there'll already be an error for
340 -- that in the error list. Example:
341 -- e.g. import Prelude hiding( Ord )
342 -- instance Ord T where ...
343 -- The program is wrong, but that should not cause a crash.
344 returnM (mkUnboundName rdr_name)
346 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
347 (n:ns)-> ASSERT( null ns ) returnM n
348 [] -> unboundName rdr_name
350 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
353 | otherwise -- Occurs in derived instances, where we just
354 -- refer directly to the right method, and avail_env
356 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
357 -- NB: qualified names are rejected by the parser
358 lookupOrigName rdr_name
361 lookupSysBndr :: RdrName -> RnM Name
362 -- Used for the 'system binders' in a data type or class declaration
363 -- Do *not* look up in the RdrEnv; these system binders are never in scope
364 -- Instead, get the module from the monad... but remember that
365 -- where the module is depends on whether we are renaming source or
366 -- interface file stuff
367 lookupSysBndr rdr_name
368 = getSrcLocM `thenM` \ loc ->
369 getModeRn `thenM` \ mode ->
371 InterfaceMode mod -> newTopBinder mod rdr_name loc
372 other -> getModule `thenM` \ mod ->
373 newTopBinder mod rdr_name loc
375 -- lookupOccRn looks up an occurrence of a RdrName
376 lookupOccRn :: RdrName -> RnM Name
378 = getLocalRdrEnv `thenM` \ local_env ->
379 case lookupRdrEnv local_env rdr_name of
380 Just name -> returnM name
381 Nothing -> lookupGlobalOccRn rdr_name
383 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
384 -- environment. It's used only for
385 -- record field names
386 -- class op names in class and instance decls
388 lookupGlobalOccRn rdr_name
389 = getModeRn `thenM` \ mode ->
391 InterfaceMode mod -> lookupIfaceName mod rdr_name
392 SourceMode -> lookupSrcName rdr_name
395 | not (isQual rdr_name) ->
396 lookupSrcName rdr_name
398 -- We allow qualified names on the command line to refer to
399 -- *any* name exported by any module in scope, just as if
400 -- there was an "import qualified M" declaration for every
403 -- First look up the name in the normal environment. If
404 -- it isn't there, we manufacture a new occurrence of an
407 lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
409 Just name -> returnM name
410 Nothing -> lookupQualifiedName rdr_name
412 -- A qualified name on the command line can refer to any module at all: we
413 -- try to load the interface if we don't already have it.
414 lookupQualifiedName :: RdrName -> TcRn m Name
415 lookupQualifiedName rdr_name
417 mod = rdrNameModule rdr_name
418 occ = rdrNameOcc rdr_name
420 loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
421 case [ name | (_,avails) <- mi_exports iface,
423 name <- availNames avail,
424 nameOccName name == occ ] of
425 (n:ns) -> ASSERT (null ns) returnM n
426 _ -> unboundName rdr_name
428 lookupSrcName :: RdrName -> TcRn m Name
429 lookupSrcName rdr_name
430 = lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
432 Nothing -> unboundName rdr_name
433 Just name -> returnM name
435 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
436 lookupSrcName_maybe rdr_name
437 | Just name <- isExact_maybe rdr_name -- Can occur in source code too
438 = returnM (Just name)
440 | isOrig rdr_name -- An original name
441 = newGlobalNameFromRdrName rdr_name `thenM` \ name ->
445 = lookupGRE rdr_name `thenM` \ mb_gre ->
447 Nothing -> returnM Nothing
448 Just gre -> returnM (Just (gre_name gre))
450 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
452 = getGlobalRdrEnv `thenM` \ global_env ->
453 case lookupRdrEnv global_env rdr_name of
454 Just [gre] -> case gre_deprec gre of
455 Nothing -> returnM (Just gre)
456 Just _ -> warnDeprec gre `thenM_`
458 Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff `thenM_`
460 Nothing -> return Nothing
462 lookupIfaceName :: Module -> RdrName -> TcRn m Name
463 -- An Unqual is allowed; interface files contain
464 -- unqualified names for locally-defined things, such as
465 -- constructors of a data type.
466 lookupIfaceName mod rdr_name
467 | isUnqual rdr_name = newGlobalName mod (rdrNameOcc rdr_name) importedSrcLoc
468 | otherwise = lookupOrigName rdr_name
470 lookupOrigName :: RdrName -> TcRn m Name
471 -- Just for original or exact names
472 lookupOrigName rdr_name
473 | Just n <- isExact_maybe rdr_name
474 -- This happens in derived code, which we
475 -- rename in InterfaceMode
478 | otherwise -- Usually Orig, but can be a Qual when
479 -- we are reading a .hi-boot file
480 = newGlobalNameFromRdrName rdr_name
483 dataTcOccs :: RdrName -> [RdrName]
484 -- If the input is a data constructor, return both it and a type
485 -- constructor. This is useful when we aren't sure which we are
488 -- ToDo: If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
489 -- and we don't have a systematic way to find the TyCon's Name from
490 -- the DataCon's name. Sigh
492 | isDataOcc occ = [rdr_name_tc, rdr_name]
493 | otherwise = [rdr_name]
495 occ = rdrNameOcc rdr_name
496 rdr_name_tc = setRdrNameSpace rdr_name tcName
500 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
501 returnM (mkUnboundName rdr_name)
504 %*********************************************************
508 %*********************************************************
511 --------------------------------
512 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
513 -- Used for nested fixity decls
514 -- No need to worry about type constructors here,
515 -- Should check for duplicates but we don't
516 bindLocalFixities fixes thing_inside
517 | null fixes = thing_inside
518 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
519 extendFixityEnv new_bit thing_inside
521 rn_sig (FixitySig v fix src_loc)
522 = addSrcLoc src_loc $
523 lookupSigOccRn v `thenM` \ new_v ->
524 returnM (new_v, FixitySig new_v fix src_loc)
527 --------------------------------
528 lookupFixity is a bit strange.
530 * Nested local fixity decls are put in the local fixity env, which we
531 find with getFixtyEnv
533 * Imported fixities are found in the HIT or PIT
535 * Top-level fixity decls in this module may be for Names that are
536 either Global (constructors, class operations)
537 or Local/Exported (everything else)
538 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
539 We put them all in the local fixity environment
542 lookupFixityRn :: Name -> RnM Fixity
544 = getModule `thenM` \ this_mod ->
545 if nameIsLocalOrFrom this_mod name
546 then -- It's defined in this module
547 getFixityEnv `thenM` \ local_fix_env ->
548 returnM (lookupFixity local_fix_env name)
550 else -- It's imported
551 -- For imported names, we have to get their fixities by doing a
552 -- loadHomeInterface, and consulting the Ifaces that comes back
553 -- from that, because the interface file for the Name might not
554 -- have been loaded yet. Why not? Suppose you import module A,
555 -- which exports a function 'f', thus;
556 -- module CurrentModule where
558 -- module A( f ) where
560 -- Then B isn't loaded right away (after all, it's possible that
561 -- nothing from B will be used). When we come across a use of
562 -- 'f', we need to know its fixity, and it's then, and only
563 -- then, that we load B.hi. That is what's happening here.
564 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
565 returnM (lookupFixity (mi_fixities iface) name)
567 doc = ptext SLIT("Checking fixity for") <+> ppr name
568 name_mod = moduleName (nameModule name)
572 %*********************************************************
574 \subsection{Implicit free vars and sugar names}
576 %*********************************************************
578 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
579 mentioned explicitly, but which might be needed by the type checker.
582 implicitStmtFVs source_fvs -- Compiling a statement
583 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
585 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName,
587 -- These are all needed implicitly when compiling a statement
588 -- See TcModule.tc_stmts
589 -- Reason for integerTyConName: consider this in GHCi
591 -- We get an ambigous constraint (Show a), which we now default just like
592 -- numeric types... but unless we have the instance decl for Integer we
593 -- won't find a valid default!
595 implicitModuleFVs source_fvs
596 = mkTemplateHaskellFVs source_fvs `plusFV`
597 namesNeededForFlattening `plusFV`
601 thProxyName :: NameSet
602 mkTemplateHaskellFVs :: NameSet -> NameSet
603 -- This is a bit of a hack. When we see the Template-Haskell construct
605 -- we are going to need lots of the ``smart constructors'' defined in
606 -- the main Template Haskell data type module. Rather than treat them
607 -- all as free vars at every occurrence site, we just make the Q type
608 -- consructor a free var.... and then use that here to haul in the others
611 --------------- Template Haskell enabled --------------
612 thProxyName = unitFV qTyConName
614 mkTemplateHaskellFVs source_fvs
615 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
616 | otherwise = emptyFVs
619 --------------- Template Haskell disabled --------------
621 thProxyName = emptyFVs
622 mkTemplateHaskellFVs source_fvs = emptyFVs
624 --------------------------------------------------------
626 -- ubiquitous_names are loaded regardless, because
627 -- they are needed in virtually every program
629 = mkFVs [unpackCStringName, unpackCStringFoldrName,
630 unpackCStringUtf8Name, eqStringName,
631 -- Virtually every program has error messages in it somewhere
632 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
633 -- Add occurrences for very frequently used types.
634 -- (e.g. we don't want to be bothered with making
635 -- funTyCon a free var at every function application!)
638 %************************************************************************
640 \subsection{Re-bindable desugaring names}
642 %************************************************************************
644 Haskell 98 says that when you say "3" you get the "fromInteger" from the
645 Standard Prelude, regardless of what is in scope. However, to experiment
646 with having a language that is less coupled to the standard prelude, we're
647 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
648 happens to be in scope. Then you can
650 import MyPrelude as Prelude
651 to get the desired effect.
653 At the moment this just happens for
654 * fromInteger, fromRational on literals (in expressions and patterns)
655 * negate (in expressions)
656 * minus (arising from n+k patterns)
659 We store the relevant Name in the HsSyn tree, in
660 * HsIntegral/HsFractional
664 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
665 fromRationalName etc), but the renamer changes this to the appropriate user
666 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
668 We treat the orignal (standard) names as free-vars too, because the type checker
669 checks the type of the user thing against the type of the standard thing.
672 lookupSyntaxName :: Name -- The standard name
673 -> RnM (Name, FreeVars) -- Possibly a non-standard name
674 lookupSyntaxName std_name
675 = doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
676 if not no_prelude then normal_case
678 getModeRn `thenM` \ mode ->
679 if isInterfaceMode mode then normal_case
680 -- Happens for 'derived' code where we don't want to rebind
682 -- Get the similarly named thing from the local environment
683 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
684 returnM (usr_name, mkFVs [usr_name, std_name])
686 normal_case = returnM (std_name, unitFV std_name)
688 lookupSyntaxNames :: [Name] -- Standard names
689 -> RnM (ReboundNames Name, FreeVars) -- See comments with HsExpr.ReboundNames
690 lookupSyntaxNames std_names
691 = doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
692 if not no_prelude then normal_case
694 getModeRn `thenM` \ mode ->
695 if isInterfaceMode mode then normal_case
697 -- Get the similarly named thing from the local environment
698 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
700 returnM (std_names `zip` map HsVar usr_names, mkFVs std_names `plusFV` mkFVs usr_names)
702 normal_case = returnM (std_names `zip` map HsVar std_names, mkFVs std_names)
706 %*********************************************************
710 %*********************************************************
713 newLocalsRn :: [(RdrName,SrcLoc)]
715 newLocalsRn rdr_names_w_loc
716 = newUniqueSupply `thenM` \ us ->
718 uniqs = uniqsFromSupply us
719 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
720 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
726 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
727 -> [(RdrName,SrcLoc)]
730 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
731 = getModeRn `thenM` \ mode ->
732 getLocalRdrEnv `thenM` \ local_env ->
733 getGlobalRdrEnv `thenM` \ global_env ->
735 -- Check for duplicate names
736 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
738 -- Warn about shadowing, but only in source modules
740 check_shadow (rdr_name,loc)
741 | rdr_name `elemRdrEnv` local_env
742 || rdr_name `elemRdrEnv` global_env
743 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
749 SourceMode -> ifOptM Opt_WarnNameShadowing $
750 mappM_ check_shadow rdr_names_w_loc
754 newLocalsRn rdr_names_w_loc `thenM` \ names ->
756 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
758 setLocalRdrEnv new_local_env (enclosed_scope names)
760 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
761 -- A specialised variant when renaming stuff from interface
762 -- files (of which there is a lot)
764 -- * no checks for shadowing
766 -- * deal with free vars
767 bindCoreLocalRn rdr_name enclosed_scope
768 = getSrcLocM `thenM` \ loc ->
769 getLocalRdrEnv `thenM` \ name_env ->
770 newUnique `thenM` \ uniq ->
772 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
773 new_name_env = extendRdrEnv name_env rdr_name name
775 setLocalRdrEnv new_name_env (enclosed_scope name)
777 bindCoreLocalsRn [] thing_inside = thing_inside []
778 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
779 bindCoreLocalsRn bs $ \ names' ->
780 thing_inside (name':names')
782 bindLocalNames names enclosed_scope
783 = getLocalRdrEnv `thenM` \ name_env ->
784 setLocalRdrEnv (extendLocalRdrEnv name_env names)
787 bindLocalNamesFV names enclosed_scope
788 = bindLocalNames names $
789 enclosed_scope `thenM` \ (thing, fvs) ->
790 returnM (thing, delListFromNameSet fvs names)
793 -------------------------------------
794 bindLocalRn doc rdr_name enclosed_scope
795 = getSrcLocM `thenM` \ loc ->
796 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
800 bindLocalsRn doc rdr_names enclosed_scope
801 = getSrcLocM `thenM` \ loc ->
802 bindLocatedLocalsRn doc
803 (rdr_names `zip` repeat loc)
806 -- binLocalsFVRn is the same as bindLocalsRn
807 -- except that it deals with free vars
808 bindLocalsFV doc rdr_names enclosed_scope
809 = bindLocalsRn doc rdr_names $ \ names ->
810 enclosed_scope names `thenM` \ (thing, fvs) ->
811 returnM (thing, delListFromNameSet fvs names)
813 -------------------------------------
814 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
815 -- This tiresome function is used only in rnSourceDecl on InstDecl
816 extendTyVarEnvFVRn tyvars enclosed_scope
817 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
818 returnM (thing, delListFromNameSet fvs tyvars)
820 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
821 -> ([HsTyVarBndr Name] -> RnM a)
823 bindTyVarsRn doc_str tyvar_names enclosed_scope
824 = getSrcLocM `thenM` \ loc ->
826 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
828 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
829 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
831 bindPatSigTyVars :: [RdrNameHsType] -> ([Name] -> RnM a) -> RnM a
832 -- Find the type variables in the pattern type
833 -- signatures that must be brought into scope
835 bindPatSigTyVars tys thing_inside
836 = getLocalRdrEnv `thenM` \ name_env ->
837 getSrcLocM `thenM` \ loc ->
839 forall_tyvars = nub [ tv | ty <- tys,
840 tv <- extractHsTyRdrTyVars ty,
841 not (tv `elemFM` name_env)
843 -- The 'nub' is important. For example:
844 -- f (x :: t) (y :: t) = ....
845 -- We don't want to complain about binding t twice!
847 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
848 doc_sig = text "In a pattern type-signature"
850 bindLocatedLocalsRn doc_sig located_tyvars thing_inside
852 bindPatSigTyVarsFV :: [RdrNameHsType]
855 bindPatSigTyVarsFV tys thing_inside
856 = bindPatSigTyVars tys $ \ tvs ->
857 thing_inside `thenM` \ (result,fvs) ->
858 returnM (result, fvs `delListFromNameSet` tvs)
860 -------------------------------------
861 checkDupOrQualNames, checkDupNames :: SDoc
862 -> [(RdrName, SrcLoc)]
864 -- Works in any variant of the renamer monad
866 checkDupOrQualNames doc_str rdr_names_w_loc
867 = -- Qualified names in patterns are now rejected by the parser
868 -- but I'm not 100% certain that it finds all cases, so I've left
869 -- this check in for now. Should go eventually.
870 -- Hmm. Sooner rather than later.. data type decls
871 -- mappM_ (qualNameErr doc_str) quals `thenM_`
872 checkDupNames doc_str rdr_names_w_loc
874 quals = filter (isQual . fst) rdr_names_w_loc
876 checkDupNames doc_str rdr_names_w_loc
877 = -- Check for duplicated names in a binding group
878 mappM_ (dupNamesErr doc_str) dups
880 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
884 %************************************************************************
886 \subsection{GlobalRdrEnv}
888 %************************************************************************
891 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
892 -> Bool -- True <=> want unqualified import
893 -> (Name -> Provenance)
894 -> Avails -- Whats imported
898 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
901 -- Make the name environment. We're talking about a
902 -- single module here, so there must be no name clashes.
903 -- In practice there only ever will be if it's the module
906 -- Add qualified names for the things that are available
907 -- (Qualified names are always imported)
908 gbl_env1 = foldl add_avail emptyRdrEnv avails
910 -- Add unqualified names
911 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
912 | otherwise = gbl_env1
914 add_unqual env (qual_name, elts)
915 = foldl add_one env elts
917 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
918 unqual_name = unqualifyRdrName qual_name
919 -- The qualified import should only have added one
920 -- binding for each qualified name! But if there's an error in
921 -- the module (multiple bindings for the same name) we may get
922 -- duplicates. So the simple thing is to do the fold.
924 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
925 add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
927 add_name parent env name -- Add qualified name only
928 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
930 occ = nameOccName name
931 elt = GRE {gre_name = name,
932 gre_parent = if name == parent
935 gre_prov = mk_provenance name,
936 gre_deprec = lookupDeprec deprecs name}
940 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
941 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
943 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
944 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
946 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
947 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
949 combine_globals :: [GlobalRdrElt] -- Old
950 -> [GlobalRdrElt] -- New
952 combine_globals ns_old ns_new -- ns_new is often short
953 = foldr add ns_old ns_new
955 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
958 choose n m | n `beats` m = n
961 g1 `beats` g2 = gre_name g1 == gre_name g2 &&
962 gre_prov g1 `hasBetterProv` gre_prov g2
964 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
965 is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
966 is_duplicate g1 g2 = gre_name g1 == gre_name g2
969 We treat two bindings of a locally-defined name as a duplicate,
970 because they might be two separate, local defns and we want to report
971 and error for that, {\em not} eliminate a duplicate.
973 On the other hand, if you import the same name from two different
974 import statements, we {\em do} want to eliminate the duplicate, not report
977 If a module imports itself then there might be a local defn and an imported
978 defn of the same name; in this case the names will compare as equal, but
979 will still have different provenances.
982 %************************************************************************
984 \subsection{Free variable manipulation}
986 %************************************************************************
990 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
992 (ys, fvs_s) = unzip stuff
994 returnM (ys, plusFVs fvs_s)
998 %************************************************************************
1000 \subsection{Envt utility functions}
1002 %************************************************************************
1005 warnUnusedModules :: [ModuleName] -> TcRn m ()
1006 warnUnusedModules mods
1007 = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
1009 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
1010 text "is imported, but nothing from it is used",
1011 parens (ptext SLIT("except perhaps instances visible in") <+>
1014 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
1015 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1016 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
1018 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
1019 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
1020 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
1022 -------------------------
1024 warnUnusedGREs gres = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1025 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
1027 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
1028 warnUnusedBinds names
1029 = mappM_ warnUnusedGroup groups
1031 -- Group by provenance
1032 groups = equivClasses cmp (filter reportable names)
1033 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
1035 reportable (name,_) = reportIfUnused (nameOccName name)
1038 -------------------------
1040 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
1041 warnUnusedGroup names
1042 = addSrcLoc def_loc $
1044 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) names)))]
1046 (name1, prov1) = head names
1047 loc1 = nameSrcLoc name1
1048 (def_loc, msg) = case prov1 of
1049 LocalDef -> (loc1, unused_msg)
1050 NonLocalDef (UserImport mod loc _) -> (loc, imp_from mod)
1052 unused_msg = text "Defined but not used"
1053 imp_from mod = text "Imported from" <+> quotes (ppr mod) <+> text "but not used"
1057 addNameClashErrRn rdr_name (np1:nps)
1058 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1059 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1061 msg1 = ptext SLIT("either") <+> mk_ref np1
1062 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1063 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1065 shadowedNameWarn shadow
1066 = hsep [ptext SLIT("This binding for"),
1067 quotes (ppr shadow),
1068 ptext SLIT("shadows an existing binding")]
1071 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1073 flavour = occNameFlavour (rdrNameOcc name)
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 qualNameErr descriptor (name,loc)
1081 addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1084 dupNamesErr descriptor ((name,loc) : dup_things)
1086 addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1090 noIfaceErr dflags mod_name boot_file files
1091 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
1095 | verbosity dflags < 3 =
1096 text "(use -v to see a list of the files searched for)"
1098 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1100 warnDeprec :: GlobalRdrElt -> TcRn m ()
1101 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1102 = ifOptM Opt_WarnDeprecations $
1103 addWarn (sep [ text (occNameFlavour (nameOccName name)) <+>
1104 quotes (ppr name) <+> text "is deprecated:",