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, getSrcLoc, nameIsLocalOrFrom, isWiredInName,
33 mkInternalName, mkExternalName, mkIPName, nameSrcLoc,
34 nameOccName, setNameSrcLoc, nameModule )
36 import OccName ( OccName, tcName, isDataOcc, occNameUserString, occNameFlavour )
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,
43 bindIOName, returnIOName, failIOName, thenIOName
46 import DsMeta ( templateHaskellNames, qTyConName )
48 import TysWiredIn ( unitTyCon ) -- A little odd
49 import Finder ( findModule )
52 import SrcLoc ( SrcLoc, noSrcLoc, importedSrcLoc )
54 import ListSetOps ( removeDups, equivClasses )
55 import BasicTypes ( mapIPName, FixitySig(..) )
58 import FastString ( FastString )
61 %*********************************************************
63 \subsection{Making new names}
65 %*********************************************************
68 newTopBinder :: Module -> RdrName -> SrcLoc -> TcRn m Name
69 newTopBinder mod rdr_name loc
70 | Just name <- isExact_maybe rdr_name
74 = ASSERT( not (isOrig rdr_name) || rdrNameModule rdr_name == moduleName mod )
75 -- When reading External Core we get Orig names as binders,
76 -- but they should agree with the module gotten from the monad
77 newGlobalName mod (rdrNameOcc rdr_name) loc
79 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
80 newGlobalName mod occ loc
81 = -- First check the cache
82 getNameCache `thenM` \ name_supply ->
83 case lookupOrigNameCache (nsNames name_supply) mod occ of
85 -- A hit in the cache! We are at the binding site of the name.
86 -- This is the moment when we know the defining SrcLoc
87 -- of the Name, so we set the SrcLoc of the name we return.
89 -- Main reason: then (bogus) multiple bindings of the same Name
90 -- get different SrcLocs can can be reported as such.
92 -- Possible other reason: it might be in the cache because we
93 -- encountered an occurrence before the binding site for an
94 -- implicitly-imported Name. Perhaps the current SrcLoc is
95 -- better... but not really: it'll still just say 'imported'
97 -- IMPORTANT: Don't mess with wired-in names.
98 -- Their wired-in-ness is in the SrcLoc
100 Just name | isWiredInName name -> returnM name
101 | otherwise -> returnM (setNameSrcLoc name loc)
103 -- Miss in the cache!
104 -- Build a completely new Name, and put it in the cache
105 Nothing -> addNewName name_supply mod occ loc
107 -- Look up a "system name" in the name cache.
108 -- This is done by the type checker...
109 lookupSysName :: Name -- Base name
110 -> (OccName -> OccName) -- Occurrence name modifier
111 -> TcRn m Name -- System name
112 lookupSysName base_name mk_sys_occ
113 = newGlobalName (nameModule base_name)
114 (mk_sys_occ (nameOccName base_name))
115 (nameSrcLoc base_name)
118 newGlobalNameFromRdrName rdr_name -- Qualified original name
119 = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
121 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
122 -- This one starts with a ModuleName, not a Module, because
123 -- we may be simply looking at an occurrence M.x in an interface file.
125 -- Used for *occurrences*. Even if we get a miss in the
126 -- original-name cache, we make a new External Name.
127 -- We get its Module either from the OrigNameCache, or (if this
128 -- is the first Name from that module) from the Finder
130 -- In the case of a miss, we have to make up the SrcLoc, but that's
131 -- OK: it must be an implicitly-imported Name, and that never occurs
132 -- in an error message.
134 newGlobalName2 mod_name occ
135 = getNameCache `thenM` \ name_supply ->
137 new_name mod = addNewName name_supply mod occ importedSrcLoc
139 case lookupModuleEnvByName (nsNames name_supply) mod_name of
140 Just (mod, occ_env) ->
141 -- There are some names from this module already
142 -- Next, look up in the OccNameEnv
143 case lookupFM occ_env occ of
144 Just name -> returnM name
145 Nothing -> new_name mod
147 Nothing -> -- No names from this module yet
148 ioToTcRn (findModule mod_name) `thenM` \ mb_loc ->
150 Just (mod, _) -> new_name mod
151 Nothing -> addErr (noModule mod_name) `thenM_`
152 -- Things have really gone wrong at this point,
153 -- so having the wrong package info in the
154 -- Module is the least of our worries.
155 new_name (mkHomeModule mod_name)
157 noModule mod_name = ptext SLIT("Can't find interface for module") <+> ppr mod_name
160 newIPName rdr_name_ip
161 = getNameCache `thenM` \ name_supply ->
163 ipcache = nsIPs name_supply
165 case lookupFM ipcache key of
166 Just name_ip -> returnM name_ip
167 Nothing -> setNameCache new_ns `thenM_`
170 (us', us1) = splitUniqSupply (nsUniqs name_supply)
171 uniq = uniqFromSupply us1
172 name_ip = mapIPName mk_name rdr_name_ip
173 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
174 new_ipcache = addToFM ipcache key name_ip
175 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
177 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
179 -- A local helper function
180 addNewName name_supply mod occ loc
181 = setNameCache new_name_supply `thenM_`
184 (new_name_supply, name) = newExternalName name_supply mod occ loc
187 newExternalName :: NameCache -> Module -> OccName -> SrcLoc
189 -- Allocate a new unique, manufacture a new External Name,
190 -- put it in the cache, and return the two
191 newExternalName name_supply mod occ loc
192 = (new_name_supply, name)
194 (us', us1) = splitUniqSupply (nsUniqs name_supply)
195 uniq = uniqFromSupply us1
196 name = mkExternalName uniq mod occ loc
197 new_cache = extend_name_cache (nsNames name_supply) mod occ name
198 new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
200 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
201 lookupOrigNameCache nc mod occ
202 = case lookupModuleEnv nc mod of
204 Just (_, occ_env) -> lookupFM occ_env occ
206 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
207 extendOrigNameCache nc name
208 = extend_name_cache nc (nameModule name) (nameOccName name) name
210 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
211 extend_name_cache nc mod occ name
212 = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
214 combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
217 %*********************************************************
219 \subsection{Looking up names}
221 %*********************************************************
223 Looking up a name in the RnEnv.
226 lookupBndrRn rdr_name
227 = getLocalRdrEnv `thenM` \ local_env ->
228 case lookupRdrEnv local_env rdr_name of
229 Just name -> returnM name
230 Nothing -> lookupTopBndrRn rdr_name
232 lookupTopBndrRn rdr_name
233 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
234 -- and there may be several imported 'f's too, which must not confuse us.
235 -- So we have to filter out the non-local ones.
236 -- A separate function (importsFromLocalDecls) reports duplicate top level
237 -- decls, so here it's safe just to choose an arbitrary one.
239 -- There should never be a qualified name in a binding position in Haskell,
240 -- but there can be if we have read in an external-Core file.
241 -- The Haskell parser checks for the illegal qualified name in Haskell
242 -- source files, so we don't need to do so here.
244 = getModeRn `thenM` \ mode ->
247 getSrcLocM `thenM` \ loc ->
248 newTopBinder mod rdr_name loc
250 other -> lookupTopSrcBndr rdr_name
252 lookupTopSrcBndr :: RdrName -> TcRn m Name
253 lookupTopSrcBndr rdr_name
254 = lookupTopSrcBndr_maybe rdr_name `thenM` \ maybe_name ->
256 Just name -> returnM name
257 Nothing -> unboundName rdr_name
260 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
261 -- Look up a source-code binder
263 -- Ignores imported names; for example, this is OK:
265 -- infix 9 f -- The 'f' here does not need to be qualified
266 -- f x = x -- Nor here, of course
268 lookupTopSrcBndr_maybe rdr_name
269 | Just name <- isExact_maybe rdr_name
270 -- This is here just to catch the PrelBase defn of (say) [] and similar
271 -- The parser reads the special syntax and returns an Exact RdrName
272 -- But the global_env contains only Qual RdrNames, so we won't
273 -- find it there; instead just get the name via the Orig route
275 -- We are at a binding site for the name, so check first that it
276 -- the current module is the correct one; otherwise GHC can get
277 -- very confused indeed. This test rejects code like
278 -- data T = (,) Int Int
279 -- unless we are in GHC.Tup
280 = getModule `thenM` \ mod ->
281 checkErr (moduleName mod == moduleName (nameModule name))
282 (badOrigBinding rdr_name) `thenM_`
286 = getGlobalRdrEnv `thenM` \ global_env ->
287 case lookupRdrEnv global_env rdr_name of
288 Nothing -> returnM Nothing
289 Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
290 [] -> returnM Nothing
291 (n:ns) -> returnM (Just n)
294 -- lookupSigOccRn is used for type signatures and pragmas
300 -- It's clear that the 'f' in the signature must refer to A.f
301 -- The Haskell98 report does not stipulate this, but it will!
302 -- So we must treat the 'f' in the signature in the same way
303 -- as the binding occurrence of 'f', using lookupBndrRn
304 lookupSigOccRn :: RdrName -> RnM Name
305 lookupSigOccRn = lookupBndrRn
307 -- lookupInstDeclBndr is used for the binders in an
308 -- instance declaration. Here we use the class name to
311 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
312 -- We use the selector name as the binder
313 lookupInstDeclBndr cls_name rdr_name
315 = -- Find all the things the class op name maps to
316 -- and pick the one with the right parent name
317 getGblEnv `thenM` \ gbl_env ->
319 avail_env = imp_env (tcg_imports gbl_env)
321 case lookupAvailEnv avail_env cls_name of
323 -- If the class itself isn't in scope, then cls_name will
324 -- be unboundName, and there'll already be an error for
325 -- that in the error list. Example:
326 -- e.g. import Prelude hiding( Ord )
327 -- instance Ord T where ...
328 -- The program is wrong, but that should not cause a crash.
329 returnM (mkUnboundName rdr_name)
331 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
332 (n:ns)-> ASSERT( null ns ) returnM n
333 [] -> unboundName rdr_name
335 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
338 | otherwise -- Occurs in derived instances, where we just
339 -- refer directly to the right method, and avail_env
341 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
342 -- NB: qualified names are rejected by the parser
343 lookupOrigName rdr_name
346 occ = rdrNameOcc rdr_name
348 lookupSysBndr :: RdrName -> RnM Name
349 -- Used for the 'system binders' in a data type or class declaration
350 -- Do *not* look up in the RdrEnv; these system binders are never in scope
351 -- Instead, get the module from the monad... but remember that
352 -- where the module is depends on whether we are renaming source or
353 -- interface file stuff
354 lookupSysBndr rdr_name
355 = getSrcLocM `thenM` \ loc ->
356 getModeRn `thenM` \ mode ->
358 InterfaceMode mod -> newTopBinder mod rdr_name loc
359 other -> getModule `thenM` \ mod ->
360 newTopBinder mod rdr_name loc
362 -- lookupOccRn looks up an occurrence of a RdrName
363 lookupOccRn :: RdrName -> RnM Name
365 = getLocalRdrEnv `thenM` \ local_env ->
366 case lookupRdrEnv local_env rdr_name of
367 Just name -> returnM name
368 Nothing -> lookupGlobalOccRn rdr_name
370 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
371 -- environment. It's used only for
372 -- record field names
373 -- class op names in class and instance decls
375 lookupGlobalOccRn rdr_name
376 = getModeRn `thenM` \ mode ->
378 InterfaceMode mod -> lookupIfaceName mod rdr_name
379 SourceMode -> lookupSrcName rdr_name
382 | not (isQual rdr_name) ->
383 lookupSrcName rdr_name
385 -- We allow qualified names on the command line to refer to
386 -- *any* name exported by any module in scope, just as if
387 -- there was an "import qualified M" declaration for every
390 -- First look up the name in the normal environment. If
391 -- it isn't there, we manufacture a new occurrence of an
394 lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
396 Just name -> returnM name
397 Nothing -> lookupQualifiedName rdr_name
399 -- A qualified name on the command line can refer to any module at all: we
400 -- try to load the interface if we don't already have it.
401 lookupQualifiedName :: RdrName -> TcRn m Name
402 lookupQualifiedName rdr_name
404 mod = rdrNameModule rdr_name
405 occ = rdrNameOcc rdr_name
407 loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
408 case [ name | (_,avails) <- mi_exports iface,
410 name <- availNames avail,
411 nameOccName name == occ ] of
412 (n:ns) -> ASSERT (null ns) returnM n
413 _ -> unboundName rdr_name
415 lookupSrcName :: RdrName -> TcRn m Name
416 lookupSrcName rdr_name
417 = lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
419 Nothing -> unboundName rdr_name
420 Just name -> returnM name
422 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
423 lookupSrcName_maybe rdr_name
424 | Just name <- isExact_maybe rdr_name -- Can occur in source code too
425 = returnM (Just name)
427 | isOrig rdr_name -- An original name
428 = newGlobalNameFromRdrName rdr_name `thenM` \ name ->
432 = lookupGRE rdr_name `thenM` \ mb_gre ->
434 Nothing -> returnM Nothing
435 Just gre -> returnM (Just (gre_name gre))
437 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
439 = getGlobalRdrEnv `thenM` \ global_env ->
440 case lookupRdrEnv global_env rdr_name of
441 Just [gre] -> case gre_deprec gre of
442 Nothing -> returnM (Just gre)
443 Just _ -> warnDeprec gre `thenM_`
445 Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff `thenM_`
447 Nothing -> return Nothing
449 lookupIfaceName :: Module -> RdrName -> TcRn m Name
450 -- An Unqual is allowed; interface files contain
451 -- unqualified names for locally-defined things, such as
452 -- constructors of a data type.
453 lookupIfaceName mod rdr_name
454 | isUnqual rdr_name = newGlobalName mod (rdrNameOcc rdr_name) importedSrcLoc
455 | otherwise = lookupOrigName rdr_name
457 lookupOrigName :: RdrName -> TcRn m Name
458 -- Just for original or exact names
459 lookupOrigName rdr_name
460 | Just n <- isExact_maybe rdr_name
461 -- This happens in derived code, which we
462 -- rename in InterfaceMode
465 | otherwise -- Usually Orig, but can be a Qual when
466 -- we are reading a .hi-boot file
467 = newGlobalNameFromRdrName rdr_name
470 dataTcOccs :: RdrName -> [RdrName]
471 -- If the input is a data constructor, return both it and a type
472 -- constructor. This is useful when we aren't sure which we are
475 | isDataOcc occ = [rdr_name, rdr_name_tc]
476 | otherwise = [rdr_name]
478 occ = rdrNameOcc rdr_name
479 rdr_name_tc = setRdrNameSpace rdr_name tcName
483 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
484 returnM (mkUnboundName rdr_name)
487 %*********************************************************
491 %*********************************************************
494 --------------------------------
495 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
496 -- Used for nested fixity decls
497 -- No need to worry about type constructors here,
498 -- Should check for duplicates but we don't
499 bindLocalFixities fixes thing_inside
500 | null fixes = thing_inside
501 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
502 extendFixityEnv new_bit thing_inside
504 rn_sig (FixitySig v fix src_loc)
505 = addSrcLoc src_loc $
506 lookupSigOccRn v `thenM` \ new_v ->
507 returnM (new_v, FixitySig new_v fix src_loc)
510 --------------------------------
511 lookupFixity is a bit strange.
513 * Nested local fixity decls are put in the local fixity env, which we
514 find with getFixtyEnv
516 * Imported fixities are found in the HIT or PIT
518 * Top-level fixity decls in this module may be for Names that are
519 either Global (constructors, class operations)
520 or Local/Exported (everything else)
521 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
522 We put them all in the local fixity environment
525 lookupFixityRn :: Name -> RnM Fixity
527 = getModule `thenM` \ this_mod ->
528 if nameIsLocalOrFrom this_mod name
529 then -- It's defined in this module
530 getFixityEnv `thenM` \ local_fix_env ->
531 returnM (lookupFixity local_fix_env name)
533 else -- It's imported
534 -- For imported names, we have to get their fixities by doing a
535 -- loadHomeInterface, and consulting the Ifaces that comes back
536 -- from that, because the interface file for the Name might not
537 -- have been loaded yet. Why not? Suppose you import module A,
538 -- which exports a function 'f', thus;
539 -- module CurrentModule where
541 -- module A( f ) where
543 -- Then B isn't loaded right away (after all, it's possible that
544 -- nothing from B will be used). When we come across a use of
545 -- 'f', we need to know its fixity, and it's then, and only
546 -- then, that we load B.hi. That is what's happening here.
547 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
548 returnM (lookupFixity (mi_fixities iface) name)
550 doc = ptext SLIT("Checking fixity for") <+> ppr name
551 name_mod = moduleName (nameModule name)
555 %*********************************************************
557 \subsection{Implicit free vars and sugar names}
559 %*********************************************************
561 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
562 mentioned explicitly, but which might be needed by the type checker.
565 implicitStmtFVs source_fvs -- Compiling a statement
566 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
568 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName]
569 -- These are all needed implicitly when compiling a statement
570 -- See TcModule.tc_stmts
572 implicitModuleFVs source_fvs
573 = mkTemplateHaskellFVs source_fvs `plusFV`
574 namesNeededForFlattening `plusFV`
578 thProxyName :: NameSet
579 mkTemplateHaskellFVs :: NameSet -> NameSet
580 -- This is a bit of a hack. When we see the Template-Haskell construct
582 -- we are going to need lots of the ``smart constructors'' defined in
583 -- the main Template Haskell data type module. Rather than treat them
584 -- all as free vars at every occurrence site, we just make the Q type
585 -- consructor a free var.... and then use that here to haul in the others
588 --------------- Template Haskell enabled --------------
589 thProxyName = unitFV qTyConName
591 mkTemplateHaskellFVs source_fvs
592 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
593 | otherwise = emptyFVs
596 --------------- Template Haskell disabled --------------
598 thProxyName = emptyFVs
599 mkTemplateHaskellFVs source_fvs = emptyFVs
601 --------------------------------------------------------
603 -- ubiquitous_names are loaded regardless, because
604 -- they are needed in virtually every program
606 = mkFVs [unpackCStringName, unpackCStringFoldrName,
607 unpackCStringUtf8Name, eqStringName,
608 -- Virtually every program has error messages in it somewhere
609 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
610 -- Add occurrences for very frequently used types.
611 -- (e.g. we don't want to be bothered with making
612 -- funTyCon a free var at every function application!)
615 %************************************************************************
617 \subsection{Re-bindable desugaring names}
619 %************************************************************************
621 Haskell 98 says that when you say "3" you get the "fromInteger" from the
622 Standard Prelude, regardless of what is in scope. However, to experiment
623 with having a language that is less coupled to the standard prelude, we're
624 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
625 happens to be in scope. Then you can
627 import MyPrelude as Prelude
628 to get the desired effect.
630 At the moment this just happens for
631 * fromInteger, fromRational on literals (in expressions and patterns)
632 * negate (in expressions)
633 * minus (arising from n+k patterns)
636 We store the relevant Name in the HsSyn tree, in
637 * HsIntegral/HsFractional
641 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
642 fromRationalName etc), but the renamer changes this to the appropriate user
643 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
645 We treat the orignal (standard) names as free-vars too, because the type checker
646 checks the type of the user thing against the type of the standard thing.
649 lookupSyntaxName :: Name -- The standard name
650 -> RnM (Name, FreeVars) -- Possibly a non-standard name
651 lookupSyntaxName std_name
652 = getModeRn `thenM` \ mode ->
653 if isInterfaceMode mode then
654 returnM (std_name, unitFV std_name)
655 -- Happens for 'derived' code
656 -- where we don't want to rebind
659 doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
660 if not no_prelude then
661 returnM (std_name, unitFV std_name) -- Normal case
664 -- Get the similarly named thing from the local environment
665 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
666 returnM (usr_name, mkFVs [usr_name, std_name])
670 %*********************************************************
674 %*********************************************************
677 newLocalsRn :: [(RdrName,SrcLoc)]
679 newLocalsRn rdr_names_w_loc
680 = newUniqueSupply `thenM` \ us ->
682 uniqs = uniqsFromSupply us
683 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
684 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
690 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
691 -> [(RdrName,SrcLoc)]
694 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
695 = getModeRn `thenM` \ mode ->
696 getLocalRdrEnv `thenM` \ local_env ->
697 getGlobalRdrEnv `thenM` \ global_env ->
699 -- Check for duplicate names
700 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
702 -- Warn about shadowing, but only in source modules
704 check_shadow (rdr_name,loc)
705 | rdr_name `elemRdrEnv` local_env
706 || rdr_name `elemRdrEnv` global_env
707 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
713 SourceMode -> ifOptM Opt_WarnNameShadowing $
714 mappM_ check_shadow rdr_names_w_loc
718 newLocalsRn rdr_names_w_loc `thenM` \ names ->
720 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
722 setLocalRdrEnv new_local_env (enclosed_scope names)
724 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
725 -- A specialised variant when renaming stuff from interface
726 -- files (of which there is a lot)
728 -- * no checks for shadowing
730 -- * deal with free vars
731 bindCoreLocalRn rdr_name enclosed_scope
732 = getSrcLocM `thenM` \ loc ->
733 getLocalRdrEnv `thenM` \ name_env ->
734 newUnique `thenM` \ uniq ->
736 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
737 new_name_env = extendRdrEnv name_env rdr_name name
739 setLocalRdrEnv new_name_env (enclosed_scope name)
741 bindCoreLocalsRn [] thing_inside = thing_inside []
742 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
743 bindCoreLocalsRn bs $ \ names' ->
744 thing_inside (name':names')
746 bindLocalNames names enclosed_scope
747 = getLocalRdrEnv `thenM` \ name_env ->
748 setLocalRdrEnv (extendLocalRdrEnv name_env names)
751 bindLocalNamesFV names enclosed_scope
752 = bindLocalNames names $
753 enclosed_scope `thenM` \ (thing, fvs) ->
754 returnM (thing, delListFromNameSet fvs names)
757 -------------------------------------
758 bindLocalRn doc rdr_name enclosed_scope
759 = getSrcLocM `thenM` \ loc ->
760 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
764 bindLocalsRn doc rdr_names enclosed_scope
765 = getSrcLocM `thenM` \ loc ->
766 bindLocatedLocalsRn doc
767 (rdr_names `zip` repeat loc)
770 -- binLocalsFVRn is the same as bindLocalsRn
771 -- except that it deals with free vars
772 bindLocalsFVRn doc rdr_names enclosed_scope
773 = bindLocalsRn doc rdr_names $ \ names ->
774 enclosed_scope names `thenM` \ (thing, fvs) ->
775 returnM (thing, delListFromNameSet fvs names)
777 -------------------------------------
778 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
779 -- This tiresome function is used only in rnSourceDecl on InstDecl
780 extendTyVarEnvFVRn tyvars enclosed_scope
781 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
782 returnM (thing, delListFromNameSet fvs tyvars)
784 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
785 -> ([HsTyVarBndr Name] -> RnM a)
787 bindTyVarsRn doc_str tyvar_names enclosed_scope
788 = getSrcLocM `thenM` \ loc ->
790 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
792 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
793 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
795 bindPatSigTyVars :: [RdrNameHsType]
798 -- Find the type variables in the pattern type
799 -- signatures that must be brought into scope
801 bindPatSigTyVars tys enclosed_scope
802 = getLocalRdrEnv `thenM` \ name_env ->
803 getSrcLocM `thenM` \ loc ->
805 forall_tyvars = nub [ tv | ty <- tys,
806 tv <- extractHsTyRdrTyVars ty,
807 not (tv `elemFM` name_env)
809 -- The 'nub' is important. For example:
810 -- f (x :: t) (y :: t) = ....
811 -- We don't want to complain about binding t twice!
813 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
814 doc_sig = text "In a pattern type-signature"
816 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
817 enclosed_scope `thenM` \ (thing, fvs) ->
818 returnM (thing, delListFromNameSet fvs names)
821 -------------------------------------
822 checkDupOrQualNames, checkDupNames :: SDoc
823 -> [(RdrName, SrcLoc)]
825 -- Works in any variant of the renamer monad
827 checkDupOrQualNames doc_str rdr_names_w_loc
828 = -- Qualified names in patterns are now rejected by the parser
829 -- but I'm not 100% certain that it finds all cases, so I've left
830 -- this check in for now. Should go eventually.
831 -- Hmm. Sooner rather than later.. data type decls
832 -- mappM_ (qualNameErr doc_str) quals `thenM_`
833 checkDupNames doc_str rdr_names_w_loc
835 quals = filter (isQual . fst) rdr_names_w_loc
837 checkDupNames doc_str rdr_names_w_loc
838 = -- Check for duplicated names in a binding group
839 mappM_ (dupNamesErr doc_str) dups
841 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
845 %************************************************************************
847 \subsection{GlobalRdrEnv}
849 %************************************************************************
852 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
853 -> Bool -- True <=> want unqualified import
854 -> (Name -> Provenance)
855 -> Avails -- Whats imported
859 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
862 -- Make the name environment. We're talking about a
863 -- single module here, so there must be no name clashes.
864 -- In practice there only ever will be if it's the module
867 -- Add qualified names for the things that are available
868 -- (Qualified names are always imported)
869 gbl_env1 = foldl add_avail emptyRdrEnv avails
871 -- Add unqualified names
872 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
873 | otherwise = gbl_env1
875 add_unqual env (qual_name, elts)
876 = foldl add_one env elts
878 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
879 unqual_name = unqualifyRdrName qual_name
880 -- The qualified import should only have added one
881 -- binding for each qualified name! But if there's an error in
882 -- the module (multiple bindings for the same name) we may get
883 -- duplicates. So the simple thing is to do the fold.
885 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
886 add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
888 add_name parent env name -- Add qualified name only
889 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
891 occ = nameOccName name
892 elt = GRE {gre_name = name,
894 gre_prov = mk_provenance name,
895 gre_deprec = lookupDeprec deprecs name}
900 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
901 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
903 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
904 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
906 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
907 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
909 combine_globals :: [GlobalRdrElt] -- Old
910 -> [GlobalRdrElt] -- New
912 combine_globals ns_old ns_new -- ns_new is often short
913 = foldr add ns_old ns_new
915 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
918 choose n m | n `beats` m = n
921 g1 `beats` g2 = gre_name g1 == gre_name g2 &&
922 gre_prov g1 `hasBetterProv` gre_prov g2
924 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
925 is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
926 is_duplicate g1 g2 = gre_name g1 == gre_name g2
929 We treat two bindings of a locally-defined name as a duplicate,
930 because they might be two separate, local defns and we want to report
931 and error for that, {\em not} eliminate a duplicate.
933 On the other hand, if you import the same name from two different
934 import statements, we {\em do} want to eliminate the duplicate, not report
937 If a module imports itself then there might be a local defn and an imported
938 defn of the same name; in this case the names will compare as equal, but
939 will still have different provenances.
942 %************************************************************************
944 \subsection{Free variable manipulation}
946 %************************************************************************
950 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
952 (ys, fvs_s) = unzip stuff
954 returnM (ys, plusFVs fvs_s)
958 %************************************************************************
960 \subsection{Envt utility functions}
962 %************************************************************************
965 warnUnusedModules :: [ModuleName] -> TcRn m ()
966 warnUnusedModules mods
967 = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
969 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
970 text "is imported, but nothing from it is used",
971 parens (ptext SLIT("except perhaps instances visible in") <+>
974 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
975 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
976 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
978 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
979 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
980 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
982 -------------------------
984 warnUnusedGREs gres = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
985 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
987 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
988 warnUnusedBinds names
989 = mappM_ warnUnusedGroup groups
991 -- Group by provenance
992 groups = equivClasses cmp names
993 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
996 -------------------------
998 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
999 warnUnusedGroup names
1000 | null filtered_names = returnM ()
1001 | not is_local = returnM ()
1003 = addSrcLoc def_loc $
1005 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
1007 filtered_names = filter reportable names
1008 (name1, prov1) = head filtered_names
1009 (is_local, def_loc, msg)
1011 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
1013 NonLocalDef (UserImport mod loc _)
1014 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
1016 reportable (name,_) = case occNameUserString (nameOccName name) of
1019 -- Haskell 98 encourages compilers to suppress warnings about
1020 -- unused names in a pattern if they start with "_".
1024 addNameClashErrRn rdr_name (np1:nps)
1025 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1026 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1028 msg1 = ptext SLIT("either") <+> mk_ref np1
1029 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1030 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1032 shadowedNameWarn shadow
1033 = hsep [ptext SLIT("This binding for"),
1034 quotes (ppr shadow),
1035 ptext SLIT("shadows an existing binding")]
1038 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1040 flavour = occNameFlavour (rdrNameOcc name)
1043 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1044 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1046 qualNameErr descriptor (name,loc)
1048 addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1051 dupNamesErr descriptor ((name,loc) : dup_things)
1053 addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1057 warnDeprec :: GlobalRdrElt -> TcRn m ()
1058 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1059 = ifOptM Opt_WarnDeprecations $
1060 addWarn (sep [ text (occNameFlavour (nameOccName name)) <+>
1061 quotes (ppr name) <+> text "is deprecated:",