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 | isDataOcc occ = [rdr_name, rdr_name_tc]
489 | otherwise = [rdr_name]
491 occ = rdrNameOcc rdr_name
492 rdr_name_tc = setRdrNameSpace rdr_name tcName
496 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
497 returnM (mkUnboundName rdr_name)
500 %*********************************************************
504 %*********************************************************
507 --------------------------------
508 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
509 -- Used for nested fixity decls
510 -- No need to worry about type constructors here,
511 -- Should check for duplicates but we don't
512 bindLocalFixities fixes thing_inside
513 | null fixes = thing_inside
514 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
515 extendFixityEnv new_bit thing_inside
517 rn_sig (FixitySig v fix src_loc)
518 = addSrcLoc src_loc $
519 lookupSigOccRn v `thenM` \ new_v ->
520 returnM (new_v, FixitySig new_v fix src_loc)
523 --------------------------------
524 lookupFixity is a bit strange.
526 * Nested local fixity decls are put in the local fixity env, which we
527 find with getFixtyEnv
529 * Imported fixities are found in the HIT or PIT
531 * Top-level fixity decls in this module may be for Names that are
532 either Global (constructors, class operations)
533 or Local/Exported (everything else)
534 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
535 We put them all in the local fixity environment
538 lookupFixityRn :: Name -> RnM Fixity
540 = getModule `thenM` \ this_mod ->
541 if nameIsLocalOrFrom this_mod name
542 then -- It's defined in this module
543 getFixityEnv `thenM` \ local_fix_env ->
544 returnM (lookupFixity local_fix_env name)
546 else -- It's imported
547 -- For imported names, we have to get their fixities by doing a
548 -- loadHomeInterface, and consulting the Ifaces that comes back
549 -- from that, because the interface file for the Name might not
550 -- have been loaded yet. Why not? Suppose you import module A,
551 -- which exports a function 'f', thus;
552 -- module CurrentModule where
554 -- module A( f ) where
556 -- Then B isn't loaded right away (after all, it's possible that
557 -- nothing from B will be used). When we come across a use of
558 -- 'f', we need to know its fixity, and it's then, and only
559 -- then, that we load B.hi. That is what's happening here.
560 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
561 returnM (lookupFixity (mi_fixities iface) name)
563 doc = ptext SLIT("Checking fixity for") <+> ppr name
564 name_mod = moduleName (nameModule name)
568 %*********************************************************
570 \subsection{Implicit free vars and sugar names}
572 %*********************************************************
574 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
575 mentioned explicitly, but which might be needed by the type checker.
578 implicitStmtFVs source_fvs -- Compiling a statement
579 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
581 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName,
583 -- These are all needed implicitly when compiling a statement
584 -- See TcModule.tc_stmts
585 -- Reason for integerTyConName: consider this in GHCi
587 -- We get an ambigous constraint (Show a), which we now default just like
588 -- numeric types... but unless we have the instance decl for Integer we
589 -- won't find a valid default!
591 implicitModuleFVs source_fvs
592 = mkTemplateHaskellFVs source_fvs `plusFV`
593 namesNeededForFlattening `plusFV`
597 thProxyName :: NameSet
598 mkTemplateHaskellFVs :: NameSet -> NameSet
599 -- This is a bit of a hack. When we see the Template-Haskell construct
601 -- we are going to need lots of the ``smart constructors'' defined in
602 -- the main Template Haskell data type module. Rather than treat them
603 -- all as free vars at every occurrence site, we just make the Q type
604 -- consructor a free var.... and then use that here to haul in the others
607 --------------- Template Haskell enabled --------------
608 thProxyName = unitFV qTyConName
610 mkTemplateHaskellFVs source_fvs
611 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
612 | otherwise = emptyFVs
615 --------------- Template Haskell disabled --------------
617 thProxyName = emptyFVs
618 mkTemplateHaskellFVs source_fvs = emptyFVs
620 --------------------------------------------------------
622 -- ubiquitous_names are loaded regardless, because
623 -- they are needed in virtually every program
625 = mkFVs [unpackCStringName, unpackCStringFoldrName,
626 unpackCStringUtf8Name, eqStringName,
627 -- Virtually every program has error messages in it somewhere
628 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
629 -- Add occurrences for very frequently used types.
630 -- (e.g. we don't want to be bothered with making
631 -- funTyCon a free var at every function application!)
634 %************************************************************************
636 \subsection{Re-bindable desugaring names}
638 %************************************************************************
640 Haskell 98 says that when you say "3" you get the "fromInteger" from the
641 Standard Prelude, regardless of what is in scope. However, to experiment
642 with having a language that is less coupled to the standard prelude, we're
643 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
644 happens to be in scope. Then you can
646 import MyPrelude as Prelude
647 to get the desired effect.
649 At the moment this just happens for
650 * fromInteger, fromRational on literals (in expressions and patterns)
651 * negate (in expressions)
652 * minus (arising from n+k patterns)
655 We store the relevant Name in the HsSyn tree, in
656 * HsIntegral/HsFractional
660 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
661 fromRationalName etc), but the renamer changes this to the appropriate user
662 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
664 We treat the orignal (standard) names as free-vars too, because the type checker
665 checks the type of the user thing against the type of the standard thing.
668 lookupSyntaxName :: Name -- The standard name
669 -> RnM (Name, FreeVars) -- Possibly a non-standard name
670 lookupSyntaxName std_name
671 = doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
672 if not no_prelude then normal_case
674 getModeRn `thenM` \ mode ->
675 if isInterfaceMode mode then normal_case
676 -- Happens for 'derived' code where we don't want to rebind
678 -- Get the similarly named thing from the local environment
679 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
680 returnM (usr_name, mkFVs [usr_name, std_name])
682 normal_case = returnM (std_name, unitFV std_name)
684 lookupSyntaxNames :: [Name] -- Standard names
685 -> RnM (ReboundNames Name, FreeVars) -- See comments with HsExpr.ReboundNames
686 lookupSyntaxNames std_names
687 = doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
688 if not no_prelude then normal_case
690 getModeRn `thenM` \ mode ->
691 if isInterfaceMode mode then normal_case
693 -- Get the similarly named thing from the local environment
694 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
696 returnM (std_names `zip` map HsVar usr_names, mkFVs std_names `plusFV` mkFVs usr_names)
698 normal_case = returnM (std_names `zip` map HsVar std_names, mkFVs std_names)
702 %*********************************************************
706 %*********************************************************
709 newLocalsRn :: [(RdrName,SrcLoc)]
711 newLocalsRn rdr_names_w_loc
712 = newUniqueSupply `thenM` \ us ->
714 uniqs = uniqsFromSupply us
715 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
716 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
722 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
723 -> [(RdrName,SrcLoc)]
726 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
727 = getModeRn `thenM` \ mode ->
728 getLocalRdrEnv `thenM` \ local_env ->
729 getGlobalRdrEnv `thenM` \ global_env ->
731 -- Check for duplicate names
732 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
734 -- Warn about shadowing, but only in source modules
736 check_shadow (rdr_name,loc)
737 | rdr_name `elemRdrEnv` local_env
738 || rdr_name `elemRdrEnv` global_env
739 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
745 SourceMode -> ifOptM Opt_WarnNameShadowing $
746 mappM_ check_shadow rdr_names_w_loc
750 newLocalsRn rdr_names_w_loc `thenM` \ names ->
752 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
754 setLocalRdrEnv new_local_env (enclosed_scope names)
756 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
757 -- A specialised variant when renaming stuff from interface
758 -- files (of which there is a lot)
760 -- * no checks for shadowing
762 -- * deal with free vars
763 bindCoreLocalRn rdr_name enclosed_scope
764 = getSrcLocM `thenM` \ loc ->
765 getLocalRdrEnv `thenM` \ name_env ->
766 newUnique `thenM` \ uniq ->
768 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
769 new_name_env = extendRdrEnv name_env rdr_name name
771 setLocalRdrEnv new_name_env (enclosed_scope name)
773 bindCoreLocalsRn [] thing_inside = thing_inside []
774 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
775 bindCoreLocalsRn bs $ \ names' ->
776 thing_inside (name':names')
778 bindLocalNames names enclosed_scope
779 = getLocalRdrEnv `thenM` \ name_env ->
780 setLocalRdrEnv (extendLocalRdrEnv name_env names)
783 bindLocalNamesFV names enclosed_scope
784 = bindLocalNames names $
785 enclosed_scope `thenM` \ (thing, fvs) ->
786 returnM (thing, delListFromNameSet fvs names)
789 -------------------------------------
790 bindLocalRn doc rdr_name enclosed_scope
791 = getSrcLocM `thenM` \ loc ->
792 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
796 bindLocalsRn doc rdr_names enclosed_scope
797 = getSrcLocM `thenM` \ loc ->
798 bindLocatedLocalsRn doc
799 (rdr_names `zip` repeat loc)
802 -- binLocalsFVRn is the same as bindLocalsRn
803 -- except that it deals with free vars
804 bindLocalsFV doc rdr_names enclosed_scope
805 = bindLocalsRn doc rdr_names $ \ names ->
806 enclosed_scope names `thenM` \ (thing, fvs) ->
807 returnM (thing, delListFromNameSet fvs names)
809 -------------------------------------
810 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
811 -- This tiresome function is used only in rnSourceDecl on InstDecl
812 extendTyVarEnvFVRn tyvars enclosed_scope
813 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
814 returnM (thing, delListFromNameSet fvs tyvars)
816 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
817 -> ([HsTyVarBndr Name] -> RnM a)
819 bindTyVarsRn doc_str tyvar_names enclosed_scope
820 = getSrcLocM `thenM` \ loc ->
822 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
824 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
825 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
827 bindPatSigTyVars :: [RdrNameHsType] -> ([Name] -> RnM a) -> RnM a
828 -- Find the type variables in the pattern type
829 -- signatures that must be brought into scope
831 bindPatSigTyVars tys thing_inside
832 = getLocalRdrEnv `thenM` \ name_env ->
833 getSrcLocM `thenM` \ loc ->
835 forall_tyvars = nub [ tv | ty <- tys,
836 tv <- extractHsTyRdrTyVars ty,
837 not (tv `elemFM` name_env)
839 -- The 'nub' is important. For example:
840 -- f (x :: t) (y :: t) = ....
841 -- We don't want to complain about binding t twice!
843 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
844 doc_sig = text "In a pattern type-signature"
846 bindLocatedLocalsRn doc_sig located_tyvars thing_inside
848 bindPatSigTyVarsFV :: [RdrNameHsType]
851 bindPatSigTyVarsFV tys thing_inside
852 = bindPatSigTyVars tys $ \ tvs ->
853 thing_inside `thenM` \ (result,fvs) ->
854 returnM (result, fvs `delListFromNameSet` tvs)
856 -------------------------------------
857 checkDupOrQualNames, checkDupNames :: SDoc
858 -> [(RdrName, SrcLoc)]
860 -- Works in any variant of the renamer monad
862 checkDupOrQualNames doc_str rdr_names_w_loc
863 = -- Qualified names in patterns are now rejected by the parser
864 -- but I'm not 100% certain that it finds all cases, so I've left
865 -- this check in for now. Should go eventually.
866 -- Hmm. Sooner rather than later.. data type decls
867 -- mappM_ (qualNameErr doc_str) quals `thenM_`
868 checkDupNames doc_str rdr_names_w_loc
870 quals = filter (isQual . fst) rdr_names_w_loc
872 checkDupNames doc_str rdr_names_w_loc
873 = -- Check for duplicated names in a binding group
874 mappM_ (dupNamesErr doc_str) dups
876 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
880 %************************************************************************
882 \subsection{GlobalRdrEnv}
884 %************************************************************************
887 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
888 -> Bool -- True <=> want unqualified import
889 -> (Name -> Provenance)
890 -> Avails -- Whats imported
894 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
897 -- Make the name environment. We're talking about a
898 -- single module here, so there must be no name clashes.
899 -- In practice there only ever will be if it's the module
902 -- Add qualified names for the things that are available
903 -- (Qualified names are always imported)
904 gbl_env1 = foldl add_avail emptyRdrEnv avails
906 -- Add unqualified names
907 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
908 | otherwise = gbl_env1
910 add_unqual env (qual_name, elts)
911 = foldl add_one env elts
913 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
914 unqual_name = unqualifyRdrName qual_name
915 -- The qualified import should only have added one
916 -- binding for each qualified name! But if there's an error in
917 -- the module (multiple bindings for the same name) we may get
918 -- duplicates. So the simple thing is to do the fold.
920 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
921 add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
923 add_name parent env name -- Add qualified name only
924 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
926 occ = nameOccName name
927 elt = GRE {gre_name = name,
928 gre_parent = if name == parent
931 gre_prov = mk_provenance name,
932 gre_deprec = lookupDeprec deprecs name}
936 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
937 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
939 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
940 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
942 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
943 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
945 combine_globals :: [GlobalRdrElt] -- Old
946 -> [GlobalRdrElt] -- New
948 combine_globals ns_old ns_new -- ns_new is often short
949 = foldr add ns_old ns_new
951 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
954 choose n m | n `beats` m = n
957 g1 `beats` g2 = gre_name g1 == gre_name g2 &&
958 gre_prov g1 `hasBetterProv` gre_prov g2
960 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
961 is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
962 is_duplicate g1 g2 = gre_name g1 == gre_name g2
965 We treat two bindings of a locally-defined name as a duplicate,
966 because they might be two separate, local defns and we want to report
967 and error for that, {\em not} eliminate a duplicate.
969 On the other hand, if you import the same name from two different
970 import statements, we {\em do} want to eliminate the duplicate, not report
973 If a module imports itself then there might be a local defn and an imported
974 defn of the same name; in this case the names will compare as equal, but
975 will still have different provenances.
978 %************************************************************************
980 \subsection{Free variable manipulation}
982 %************************************************************************
986 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
988 (ys, fvs_s) = unzip stuff
990 returnM (ys, plusFVs fvs_s)
994 %************************************************************************
996 \subsection{Envt utility functions}
998 %************************************************************************
1001 warnUnusedModules :: [ModuleName] -> TcRn m ()
1002 warnUnusedModules mods
1003 = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
1005 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
1006 text "is imported, but nothing from it is used",
1007 parens (ptext SLIT("except perhaps instances visible in") <+>
1010 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
1011 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1012 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
1014 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
1015 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
1016 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
1018 -------------------------
1020 warnUnusedGREs gres = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1021 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
1023 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
1024 warnUnusedBinds names
1025 = mappM_ warnUnusedGroup groups
1027 -- Group by provenance
1028 groups = equivClasses cmp (filter reportable names)
1029 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
1031 reportable (name,_) = reportIfUnused (nameOccName name)
1034 -------------------------
1036 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
1037 warnUnusedGroup names
1038 = addSrcLoc def_loc $
1040 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) names)))]
1042 (name1, prov1) = head names
1043 loc1 = nameSrcLoc name1
1044 (def_loc, msg) = case prov1 of
1045 LocalDef -> (loc1, unused_msg)
1046 NonLocalDef (UserImport mod loc _) -> (loc, imp_from mod)
1048 unused_msg = text "Defined but not used"
1049 imp_from mod = text "Imported from" <+> quotes (ppr mod) <+> text "but not used"
1053 addNameClashErrRn rdr_name (np1:nps)
1054 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1055 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1057 msg1 = ptext SLIT("either") <+> mk_ref np1
1058 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1059 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1061 shadowedNameWarn shadow
1062 = hsep [ptext SLIT("This binding for"),
1063 quotes (ppr shadow),
1064 ptext SLIT("shadows an existing binding")]
1067 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1069 flavour = occNameFlavour (rdrNameOcc name)
1072 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1073 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1075 qualNameErr descriptor (name,loc)
1077 addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1080 dupNamesErr descriptor ((name,loc) : dup_things)
1082 addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1086 noIfaceErr dflags mod_name boot_file files
1087 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
1091 | verbosity dflags < 3 =
1092 text "(use -v to see a list of the files searched for)"
1094 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1096 warnDeprec :: GlobalRdrElt -> TcRn m ()
1097 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1098 = ifOptM Opt_WarnDeprecations $
1099 addWarn (sep [ text (occNameFlavour (nameOccName name)) <+>
1100 quotes (ppr name) <+> text "is deprecated:",