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 = newGlobalName mod (rdrNameOcc rdr_name) loc
76 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
77 newGlobalName mod occ loc
78 = -- First check the cache
79 getNameCache `thenM` \ name_supply ->
80 case lookupOrigNameCache (nsNames name_supply) mod occ of
82 -- A hit in the cache! We are at the binding site of the name.
83 -- This is the moment when we know the defining SrcLoc
84 -- of the Name, so we set the SrcLoc of the name we return.
86 -- Main reason: then (bogus) multiple bindings of the same Name
87 -- get different SrcLocs can can be reported as such.
89 -- Possible other reason: it might be in the cache because we
90 -- encountered an occurrence before the binding site for an
91 -- implicitly-imported Name. Perhaps the current SrcLoc is
92 -- better... but not really: it'll still just say 'imported'
94 -- IMPORTANT: Don't mess with wired-in names.
95 -- Their wired-in-ness is in the SrcLoc
97 Just name | isWiredInName name -> returnM name
98 | otherwise -> returnM (setNameSrcLoc name loc)
100 -- Miss in the cache!
101 -- Build a completely new Name, and put it in the cache
102 Nothing -> addNewName name_supply mod occ loc
104 -- Look up a "system name" in the name cache.
105 -- This is done by the type checker...
106 lookupSysName :: Name -- Base name
107 -> (OccName -> OccName) -- Occurrence name modifier
108 -> TcRn m Name -- System name
109 lookupSysName base_name mk_sys_occ
110 = newGlobalName (nameModule base_name)
111 (mk_sys_occ (nameOccName base_name))
112 (nameSrcLoc base_name)
115 newGlobalNameFromRdrName rdr_name -- Qualified original name
116 = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
118 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
119 -- This one starts with a ModuleName, not a Module, because
120 -- we may be simply looking at an occurrence M.x in an interface file.
122 -- Used for *occurrences*. Even if we get a miss in the
123 -- original-name cache, we make a new External Name.
124 -- We get its Module either from the OrigNameCache, or (if this
125 -- is the first Name from that module) from the Finder
127 -- In the case of a miss, we have to make up the SrcLoc, but that's
128 -- OK: it must be an implicitly-imported Name, and that never occurs
129 -- in an error message.
131 newGlobalName2 mod_name occ
132 = getNameCache `thenM` \ name_supply ->
134 new_name mod = addNewName name_supply mod occ importedSrcLoc
136 case lookupModuleEnvByName (nsNames name_supply) mod_name of
137 Just (mod, occ_env) ->
138 -- There are some names from this module already
139 -- Next, look up in the OccNameEnv
140 case lookupFM occ_env occ of
141 Just name -> returnM name
142 Nothing -> new_name mod
144 Nothing -> -- No names from this module yet
145 ioToTcRn (findModule mod_name) `thenM` \ mb_loc ->
147 Just (mod, _) -> new_name mod
148 Nothing -> addErr (noModule mod_name) `thenM_`
149 -- Things have really gone wrong at this point,
150 -- so having the wrong package info in the
151 -- Module is the least of our worries.
152 new_name (mkHomeModule mod_name)
154 noModule mod_name = ptext SLIT("Can't find interface for module") <+> ppr mod_name
157 newIPName rdr_name_ip
158 = getNameCache `thenM` \ name_supply ->
160 ipcache = nsIPs name_supply
162 case lookupFM ipcache key of
163 Just name_ip -> returnM name_ip
164 Nothing -> setNameCache new_ns `thenM_`
167 (us', us1) = splitUniqSupply (nsUniqs name_supply)
168 uniq = uniqFromSupply us1
169 name_ip = mapIPName mk_name rdr_name_ip
170 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
171 new_ipcache = addToFM ipcache key name_ip
172 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
174 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
176 -- A local helper function
177 addNewName name_supply mod occ loc
178 = setNameCache new_name_supply `thenM_`
181 (new_name_supply, name) = newExternalName name_supply mod occ loc
184 newExternalName :: NameCache -> Module -> OccName -> SrcLoc
186 -- Allocate a new unique, manufacture a new External Name,
187 -- put it in the cache, and return the two
188 newExternalName name_supply mod occ loc
189 = (new_name_supply, name)
191 (us', us1) = splitUniqSupply (nsUniqs name_supply)
192 uniq = uniqFromSupply us1
193 name = mkExternalName uniq mod occ loc
194 new_cache = extend_name_cache (nsNames name_supply) mod occ name
195 new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
197 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
198 lookupOrigNameCache nc mod occ
199 = case lookupModuleEnv nc mod of
201 Just (_, occ_env) -> lookupFM occ_env occ
203 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
204 extendOrigNameCache nc name
205 = extend_name_cache nc (nameModule name) (nameOccName name) name
207 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
208 extend_name_cache nc mod occ name
209 = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
211 combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
214 %*********************************************************
216 \subsection{Looking up names}
218 %*********************************************************
220 Looking up a name in the RnEnv.
223 lookupBndrRn rdr_name
224 = getLocalRdrEnv `thenM` \ local_env ->
225 case lookupRdrEnv local_env rdr_name of
226 Just name -> returnM name
227 Nothing -> lookupTopBndrRn rdr_name
229 lookupTopBndrRn rdr_name
230 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
231 -- and there may be several imported 'f's too, which must not confuse us.
232 -- So we have to filter out the non-local ones.
233 -- A separate function (importsFromLocalDecls) reports duplicate top level
234 -- decls, so here it's safe just to choose an arbitrary one.
236 -- There should never be a qualified name in a binding position in Haskell,
237 -- but there can be if we have read in an external-Core file.
238 -- The Haskell parser checks for the illegal qualified name, so we
239 -- don't need to do so here.
241 = ASSERT( not (isOrig rdr_name) )
242 -- Original names are used only for occurrences,
245 getModeRn `thenM` \ mode ->
248 getSrcLocM `thenM` \ loc ->
249 newTopBinder mod rdr_name loc
251 other -> lookupTopSrcBndr rdr_name
253 lookupTopSrcBndr :: RdrName -> TcRn m Name
254 lookupTopSrcBndr rdr_name
255 = lookupTopSrcBndr_maybe rdr_name `thenM` \ maybe_name ->
257 Just name -> returnM name
258 Nothing -> unboundName rdr_name
261 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
262 -- Look up a source-code binder
264 -- Ignores imported names; for example, this is OK:
266 -- infix 9 f -- The 'f' here does not need to be qualified
267 -- f x = x -- Nor here, of course
269 lookupTopSrcBndr_maybe rdr_name
270 | Just name <- isExact_maybe rdr_name
271 -- This is here just to catch the PrelBase defn of (say) [] and similar
272 -- The parser reads the special syntax and returns an Exact RdrName
273 -- But the global_env contains only Qual RdrNames, so we won't
274 -- find it there; instead just get the name via the Orig route
276 -- We are at a binding site for the name, so check first that it
277 -- the current module is the correct one; otherwise GHC can get
278 -- very confused indeed. This test rejects code like
279 -- data T = (,) Int Int
280 -- unless we are in GHC.Tup
281 = getModule `thenM` \ mod ->
282 checkErr (moduleName mod == moduleName (nameModule name))
283 (badOrigBinding rdr_name) `thenM_`
287 = getGlobalRdrEnv `thenM` \ global_env ->
288 case lookupRdrEnv global_env rdr_name of
289 Nothing -> returnM Nothing
290 Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
291 [] -> returnM Nothing
292 (n:ns) -> returnM (Just n)
295 -- lookupSigOccRn is used for type signatures and pragmas
301 -- It's clear that the 'f' in the signature must refer to A.f
302 -- The Haskell98 report does not stipulate this, but it will!
303 -- So we must treat the 'f' in the signature in the same way
304 -- as the binding occurrence of 'f', using lookupBndrRn
305 lookupSigOccRn :: RdrName -> RnM Name
306 lookupSigOccRn = lookupBndrRn
308 -- lookupInstDeclBndr is used for the binders in an
309 -- instance declaration. Here we use the class name to
312 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
313 -- We use the selector name as the binder
314 lookupInstDeclBndr cls_name rdr_name
316 = -- Find all the things the class op name maps to
317 -- and pick the one with the right parent name
318 getGblEnv `thenM` \ gbl_env ->
320 avail_env = imp_env (tcg_imports gbl_env)
322 case lookupAvailEnv avail_env cls_name of
324 -- If the class itself isn't in scope, then cls_name will
325 -- be unboundName, and there'll already be an error for
326 -- that in the error list. Example:
327 -- e.g. import Prelude hiding( Ord )
328 -- instance Ord T where ...
329 -- The program is wrong, but that should not cause a crash.
330 returnM (mkUnboundName rdr_name)
332 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
333 (n:ns)-> ASSERT( null ns ) returnM n
334 [] -> unboundName rdr_name
336 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
339 | otherwise -- Occurs in derived instances, where we just
340 -- refer directly to the right method, and avail_env
342 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
343 -- NB: qualified names are rejected by the parser
344 lookupOrigName rdr_name
347 occ = rdrNameOcc rdr_name
349 lookupSysBndr :: RdrName -> RnM Name
350 -- Used for the 'system binders' in a data type or class declaration
351 -- Do *not* look up in the RdrEnv; these system binders are never in scope
352 -- Instead, get the module from the monad... but remember that
353 -- where the module is depends on whether we are renaming source or
354 -- interface file stuff
355 lookupSysBndr rdr_name
356 = getSrcLocM `thenM` \ loc ->
357 getModeRn `thenM` \ mode ->
359 InterfaceMode mod -> newTopBinder mod rdr_name loc
360 other -> getModule `thenM` \ mod ->
361 newTopBinder mod rdr_name loc
363 -- lookupOccRn looks up an occurrence of a RdrName
364 lookupOccRn :: RdrName -> RnM Name
366 = getLocalRdrEnv `thenM` \ local_env ->
367 case lookupRdrEnv local_env rdr_name of
368 Just name -> returnM name
369 Nothing -> lookupGlobalOccRn rdr_name
371 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
372 -- environment. It's used only for
373 -- record field names
374 -- class op names in class and instance decls
376 lookupGlobalOccRn rdr_name
377 = getModeRn `thenM` \ mode ->
379 InterfaceMode mod -> lookupIfaceName mod rdr_name
380 SourceMode -> lookupSrcName rdr_name
383 | not (isQual rdr_name) ->
384 lookupSrcName rdr_name
386 -- We allow qualified names on the command line to refer to
387 -- *any* name exported by any module in scope, just as if
388 -- there was an "import qualified M" declaration for every
391 -- First look up the name in the normal environment. If
392 -- it isn't there, we manufacture a new occurrence of an
395 lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
397 Just name -> returnM name
398 Nothing -> lookupQualifiedName rdr_name
400 -- A qualified name on the command line can refer to any module at all: we
401 -- try to load the interface if we don't already have it.
402 lookupQualifiedName :: RdrName -> TcRn m Name
403 lookupQualifiedName rdr_name
405 mod = rdrNameModule rdr_name
406 occ = rdrNameOcc rdr_name
408 loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
409 case [ name | (_,avails) <- mi_exports iface,
411 name <- availNames avail,
412 nameOccName name == occ ] of
413 (n:ns) -> ASSERT (null ns) returnM n
414 _ -> unboundName rdr_name
416 lookupSrcName :: RdrName -> TcRn m Name
417 lookupSrcName rdr_name
418 = lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
420 Nothing -> unboundName rdr_name
421 Just name -> returnM name
423 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
424 lookupSrcName_maybe rdr_name
425 | Just name <- isExact_maybe rdr_name -- Can occur in source code too
426 = returnM (Just name)
428 | isOrig rdr_name -- An original name
429 = newGlobalNameFromRdrName rdr_name `thenM` \ name ->
433 = lookupGRE rdr_name `thenM` \ mb_gre ->
435 Nothing -> returnM Nothing
436 Just gre -> returnM (Just (gre_name gre))
438 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
440 = getGlobalRdrEnv `thenM` \ global_env ->
441 case lookupRdrEnv global_env rdr_name of
442 Just [gre] -> case gre_deprec gre of
443 Nothing -> returnM (Just gre)
444 Just _ -> warnDeprec gre `thenM_`
446 Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff `thenM_`
448 Nothing -> return Nothing
450 lookupIfaceName :: Module -> RdrName -> TcRn m Name
451 -- An Unqual is allowed; interface files contain
452 -- unqualified names for locally-defined things, such as
453 -- constructors of a data type.
454 lookupIfaceName mod rdr_name
455 | isUnqual rdr_name = newGlobalName mod (rdrNameOcc rdr_name) importedSrcLoc
456 | otherwise = lookupOrigName rdr_name
458 lookupOrigName :: RdrName -> TcRn m Name
459 -- Just for original or exact names
460 lookupOrigName rdr_name
461 | Just n <- isExact_maybe rdr_name
462 -- This happens in derived code, which we
463 -- rename in InterfaceMode
466 | otherwise -- Usually Orig, but can be a Qual when
467 -- we are reading a .hi-boot file
468 = newGlobalNameFromRdrName rdr_name
471 dataTcOccs :: RdrName -> [RdrName]
472 -- If the input is a data constructor, return both it and a type
473 -- constructor. This is useful when we aren't sure which we are
476 | isDataOcc occ = [rdr_name, rdr_name_tc]
477 | otherwise = [rdr_name]
479 occ = rdrNameOcc rdr_name
480 rdr_name_tc = setRdrNameSpace rdr_name tcName
484 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
485 returnM (mkUnboundName rdr_name)
488 %*********************************************************
492 %*********************************************************
495 --------------------------------
496 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
497 -- Used for nested fixity decls
498 -- No need to worry about type constructors here,
499 -- Should check for duplicates but we don't
500 bindLocalFixities fixes thing_inside
501 | null fixes = thing_inside
502 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
503 extendFixityEnv new_bit thing_inside
505 rn_sig (FixitySig v fix src_loc)
506 = addSrcLoc src_loc $
507 lookupSigOccRn v `thenM` \ new_v ->
508 returnM (new_v, FixitySig new_v fix src_loc)
511 --------------------------------
512 lookupFixity is a bit strange.
514 * Nested local fixity decls are put in the local fixity env, which we
515 find with getFixtyEnv
517 * Imported fixities are found in the HIT or PIT
519 * Top-level fixity decls in this module may be for Names that are
520 either Global (constructors, class operations)
521 or Local/Exported (everything else)
522 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
523 We put them all in the local fixity environment
526 lookupFixityRn :: Name -> RnM Fixity
528 = getModule `thenM` \ this_mod ->
529 if nameIsLocalOrFrom this_mod name
530 then -- It's defined in this module
531 getFixityEnv `thenM` \ local_fix_env ->
532 returnM (lookupFixity local_fix_env name)
534 else -- It's imported
535 -- For imported names, we have to get their fixities by doing a
536 -- loadHomeInterface, and consulting the Ifaces that comes back
537 -- from that, because the interface file for the Name might not
538 -- have been loaded yet. Why not? Suppose you import module A,
539 -- which exports a function 'f', thus;
540 -- module CurrentModule where
542 -- module A( f ) where
544 -- Then B isn't loaded right away (after all, it's possible that
545 -- nothing from B will be used). When we come across a use of
546 -- 'f', we need to know its fixity, and it's then, and only
547 -- then, that we load B.hi. That is what's happening here.
548 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
549 returnM (lookupFixity (mi_fixities iface) name)
551 doc = ptext SLIT("Checking fixity for") <+> ppr name
552 name_mod = moduleName (nameModule name)
556 %*********************************************************
558 \subsection{Implicit free vars and sugar names}
560 %*********************************************************
562 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
563 mentioned explicitly, but which might be needed by the type checker.
566 implicitStmtFVs source_fvs -- Compiling a statement
567 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
569 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName]
570 -- These are all needed implicitly when compiling a statement
571 -- See TcModule.tc_stmts
573 implicitModuleFVs source_fvs
574 = mkTemplateHaskellFVs source_fvs `plusFV`
575 namesNeededForFlattening `plusFV`
579 thProxyName :: NameSet
580 mkTemplateHaskellFVs :: NameSet -> NameSet
581 -- This is a bit of a hack. When we see the Template-Haskell construct
583 -- we are going to need lots of the ``smart constructors'' defined in
584 -- the main Template Haskell data type module. Rather than treat them
585 -- all as free vars at every occurrence site, we just make the Q type
586 -- consructor a free var.... and then use that here to haul in the others
589 --------------- Template Haskell enabled --------------
590 thProxyName = unitFV qTyConName
592 mkTemplateHaskellFVs source_fvs
593 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
594 | otherwise = emptyFVs
597 --------------- Template Haskell disabled --------------
599 thProxyName = emptyFVs
600 mkTemplateHaskellFVs source_fvs = emptyFVs
602 --------------------------------------------------------
604 -- ubiquitous_names are loaded regardless, because
605 -- they are needed in virtually every program
607 = mkFVs [unpackCStringName, unpackCStringFoldrName,
608 unpackCStringUtf8Name, eqStringName,
609 -- Virtually every program has error messages in it somewhere
610 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
611 -- Add occurrences for very frequently used types.
612 -- (e.g. we don't want to be bothered with making
613 -- funTyCon a free var at every function application!)
616 %************************************************************************
618 \subsection{Re-bindable desugaring names}
620 %************************************************************************
622 Haskell 98 says that when you say "3" you get the "fromInteger" from the
623 Standard Prelude, regardless of what is in scope. However, to experiment
624 with having a language that is less coupled to the standard prelude, we're
625 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
626 happens to be in scope. Then you can
628 import MyPrelude as Prelude
629 to get the desired effect.
631 At the moment this just happens for
632 * fromInteger, fromRational on literals (in expressions and patterns)
633 * negate (in expressions)
634 * minus (arising from n+k patterns)
637 We store the relevant Name in the HsSyn tree, in
638 * HsIntegral/HsFractional
642 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
643 fromRationalName etc), but the renamer changes this to the appropriate user
644 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
646 We treat the orignal (standard) names as free-vars too, because the type checker
647 checks the type of the user thing against the type of the standard thing.
650 lookupSyntaxName :: Name -- The standard name
651 -> RnM (Name, FreeVars) -- Possibly a non-standard name
652 lookupSyntaxName std_name
653 = getModeRn `thenM` \ mode ->
654 if isInterfaceMode mode then
655 returnM (std_name, unitFV std_name)
656 -- Happens for 'derived' code
657 -- where we don't want to rebind
660 doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
661 if not no_prelude then
662 returnM (std_name, unitFV std_name) -- Normal case
665 -- Get the similarly named thing from the local environment
666 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
667 returnM (usr_name, mkFVs [usr_name, std_name])
671 %*********************************************************
675 %*********************************************************
678 newLocalsRn :: [(RdrName,SrcLoc)]
680 newLocalsRn rdr_names_w_loc
681 = newUniqueSupply `thenM` \ us ->
683 uniqs = uniqsFromSupply us
684 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
685 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
691 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
692 -> [(RdrName,SrcLoc)]
695 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
696 = getModeRn `thenM` \ mode ->
697 getLocalRdrEnv `thenM` \ local_env ->
698 getGlobalRdrEnv `thenM` \ global_env ->
700 -- Check for duplicate names
701 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
703 -- Warn about shadowing, but only in source modules
705 check_shadow (rdr_name,loc)
706 | rdr_name `elemRdrEnv` local_env
707 || rdr_name `elemRdrEnv` global_env
708 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
714 SourceMode -> ifOptM Opt_WarnNameShadowing $
715 mappM_ check_shadow rdr_names_w_loc
719 newLocalsRn rdr_names_w_loc `thenM` \ names ->
721 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
723 setLocalRdrEnv new_local_env (enclosed_scope names)
725 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
726 -- A specialised variant when renaming stuff from interface
727 -- files (of which there is a lot)
729 -- * no checks for shadowing
731 -- * deal with free vars
732 bindCoreLocalRn rdr_name enclosed_scope
733 = getSrcLocM `thenM` \ loc ->
734 getLocalRdrEnv `thenM` \ name_env ->
735 newUnique `thenM` \ uniq ->
737 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
738 new_name_env = extendRdrEnv name_env rdr_name name
740 setLocalRdrEnv new_name_env (enclosed_scope name)
742 bindCoreLocalsRn [] thing_inside = thing_inside []
743 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
744 bindCoreLocalsRn bs $ \ names' ->
745 thing_inside (name':names')
747 bindLocalNames names enclosed_scope
748 = getLocalRdrEnv `thenM` \ name_env ->
749 setLocalRdrEnv (extendLocalRdrEnv name_env names)
752 bindLocalNamesFV names enclosed_scope
753 = bindLocalNames names $
754 enclosed_scope `thenM` \ (thing, fvs) ->
755 returnM (thing, delListFromNameSet fvs names)
758 -------------------------------------
759 bindLocalRn doc rdr_name enclosed_scope
760 = getSrcLocM `thenM` \ loc ->
761 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
765 bindLocalsRn doc rdr_names enclosed_scope
766 = getSrcLocM `thenM` \ loc ->
767 bindLocatedLocalsRn doc
768 (rdr_names `zip` repeat loc)
771 -- binLocalsFVRn is the same as bindLocalsRn
772 -- except that it deals with free vars
773 bindLocalsFVRn doc rdr_names enclosed_scope
774 = bindLocalsRn doc rdr_names $ \ names ->
775 enclosed_scope names `thenM` \ (thing, fvs) ->
776 returnM (thing, delListFromNameSet fvs names)
778 -------------------------------------
779 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
780 -- This tiresome function is used only in rnSourceDecl on InstDecl
781 extendTyVarEnvFVRn tyvars enclosed_scope
782 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
783 returnM (thing, delListFromNameSet fvs tyvars)
785 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
786 -> ([HsTyVarBndr Name] -> RnM a)
788 bindTyVarsRn doc_str tyvar_names enclosed_scope
789 = getSrcLocM `thenM` \ loc ->
791 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
793 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
794 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
796 bindPatSigTyVars :: [RdrNameHsType]
799 -- Find the type variables in the pattern type
800 -- signatures that must be brought into scope
802 bindPatSigTyVars tys enclosed_scope
803 = getLocalRdrEnv `thenM` \ name_env ->
804 getSrcLocM `thenM` \ loc ->
806 forall_tyvars = nub [ tv | ty <- tys,
807 tv <- extractHsTyRdrTyVars ty,
808 not (tv `elemFM` name_env)
810 -- The 'nub' is important. For example:
811 -- f (x :: t) (y :: t) = ....
812 -- We don't want to complain about binding t twice!
814 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
815 doc_sig = text "In a pattern type-signature"
817 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
818 enclosed_scope `thenM` \ (thing, fvs) ->
819 returnM (thing, delListFromNameSet fvs names)
822 -------------------------------------
823 checkDupOrQualNames, checkDupNames :: SDoc
824 -> [(RdrName, SrcLoc)]
826 -- Works in any variant of the renamer monad
828 checkDupOrQualNames doc_str rdr_names_w_loc
829 = -- Qualified names in patterns are now rejected by the parser
830 -- but I'm not 100% certain that it finds all cases, so I've left
831 -- this check in for now. Should go eventually.
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:",