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(..),
27 Deprecations(..), lookupDeprec, isLocalGRE,
28 extendLocalRdrEnv, availName, availNames,
32 import Name ( Name, getName, getSrcLoc, nameIsLocalOrFrom, isWiredInName,
33 mkInternalName, mkExternalName, mkIPName,
34 nameOccName, setNameModuleAndLoc, nameModule )
36 import OccName ( OccName, tcName, isDataOcc, occNameUserString, occNameFlavour )
37 import Module ( Module, ModuleName, moduleName, mkVanillaModule )
38 import PrelNames ( mkUnboundName, intTyConName,
39 boolTyConName, funTyConName,
40 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
41 eqStringName, printName,
42 bindIOName, returnIOName, failIOName, thenIOName
44 , templateHaskellNames, qTyConName
47 import TysWiredIn ( unitTyCon ) -- A little odd
50 import SrcLoc ( SrcLoc, noSrcLoc )
52 import ListSetOps ( removeDups, equivClasses )
53 import BasicTypes ( mapIPName, FixitySig(..) )
56 import FastString ( FastString )
59 %*********************************************************
61 \subsection{Making new names}
63 %*********************************************************
66 newTopBinder :: Module -> RdrName -> SrcLoc -> TcRn m Name
67 -- newTopBinder puts into the cache the binder with the
68 -- module information set correctly. When the decl is later renamed,
69 -- the binding site will thereby get the correct module.
70 -- There maybe occurrences that don't have the correct Module, but
71 -- by the typechecker will propagate the binding definition to all
72 -- the occurrences, so that doesn't matter
74 newTopBinder mod rdr_name loc
75 | Just name <- isExact_maybe rdr_name
79 = -- First check the cache
80 getNameCache `thenM` \ name_supply ->
82 occ = rdrNameOcc rdr_name
83 key = (moduleName mod, occ)
84 cache = nsNames name_supply
86 case lookupFM cache key of
88 -- A hit in the cache! We are at the binding site of the name, and
89 -- this is the moment when we know all about
90 -- a) the Name's host Module (in particular, which
91 -- package it comes from)
92 -- b) its defining SrcLoc
93 -- So we update this info
96 | isWiredInName name -> returnM name
97 -- Don't mess with wired-in names. Apart from anything
98 -- else, their wired-in-ness is in the SrcLoca
101 new_name = setNameModuleAndLoc name mod loc
102 new_cache = addToFM cache key new_name
104 setNameCache (name_supply {nsNames = new_cache}) `thenM_`
107 -- Miss in the cache!
108 -- Build a completely new Name, and put it in the cache
109 -- Even for locally-defined names we use implicitImportProvenance;
110 -- updateProvenances will set it to rights
111 Nothing -> addNewName name_supply key mod occ loc
113 newGlobalName :: ModuleName -> OccName -> TcRn m Name
114 -- Used for *occurrences*. We make a place-holder Name, really just
115 -- to agree on its unique, which gets overwritten when we read in
116 -- the binding occurence later (newTopBinder)
117 -- The place-holder Name doesn't have the right SrcLoc, and its
118 -- Module won't have the right Package either.
120 -- (We have to pass a ModuleName, not a Module, because we may be
121 -- simply looking at an occurrence M.x in an interface file.)
123 -- This means that a renamed program may have incorrect info
124 -- on implicitly-imported occurrences, but the correct info on the
125 -- *binding* declaration. It's the type checker that propagates the
126 -- correct information to all the occurrences.
127 -- Since implicitly-imported names never occur in error messages,
128 -- it doesn't matter that we get the correct info in place till later,
129 -- (but since it affects DLL-ery it does matter that we get it right
131 newGlobalName mod_name occ
132 = getNameCache `thenM` \ name_supply ->
134 key = (mod_name, occ)
135 cache = nsNames name_supply
137 case lookupFM cache key of
138 Just name -> -- traceRn (text "newGlobalName: hit" <+> ppr name) `thenM_`
141 Nothing -> -- traceRn (text "newGlobalName: new" <+> ppr name) `thenM_`
142 addNewName name_supply key (mkVanillaModule mod_name) occ noSrcLoc
144 -- Look up a "system name" in the name cache.
145 -- This is done by the type checker...
146 -- For *source* declarations, this will put the thing into the name cache
147 -- For *interface* declarations, RnHiFiles.getSysBinders will already have
148 -- put it into the cache.
149 lookupSysName :: Name -- Base name
150 -> (OccName -> OccName) -- Occurrence name modifier
151 -> TcRn m Name -- System name
152 lookupSysName base_name mk_sys_occ
153 = getNameCache `thenM` \ name_supply ->
155 mod = nameModule base_name
156 occ = mk_sys_occ (nameOccName base_name)
157 key = (moduleName mod, occ)
159 case lookupFM (nsNames name_supply) key of
160 Just name -> returnM name
161 Nothing -> addNewName name_supply key mod occ noSrcLoc
163 newIPName rdr_name_ip
164 = getNameCache `thenM` \ name_supply ->
166 ipcache = nsIPs name_supply
168 case lookupFM ipcache key of
169 Just name_ip -> returnM name_ip
170 Nothing -> setNameCache new_ns `thenM_`
173 (us', us1) = splitUniqSupply (nsUniqs name_supply)
174 uniq = uniqFromSupply us1
175 name_ip = mapIPName mk_name rdr_name_ip
176 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
177 new_ipcache = addToFM ipcache key name_ip
178 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
180 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
182 addNewName :: NameCache -> (ModuleName,OccName)
183 -> Module -> OccName -> SrcLoc -> TcRn m Name
184 -- Internal function: extend the name cache, dump it back into
185 -- the monad, and return the new name
186 -- (internal, hence the rather redundant interface)
187 addNewName name_supply key mod occ loc
188 = setNameCache new_name_supply `thenM_`
191 (us', us1) = splitUniqSupply (nsUniqs name_supply)
192 uniq = uniqFromSupply us1
193 name = mkExternalName uniq mod occ loc
194 new_cache = addToFM (nsNames name_supply) key name
195 new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
198 %*********************************************************
200 \subsection{Looking up names}
202 %*********************************************************
204 Looking up a name in the RnEnv.
207 lookupBndrRn rdr_name
208 = getLocalRdrEnv `thenM` \ local_env ->
209 case lookupRdrEnv local_env rdr_name of
210 Just name -> returnM name
211 Nothing -> lookupTopBndrRn rdr_name
213 lookupTopBndrRn rdr_name
214 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
215 -- and there may be several imported 'f's too, which must not confuse us.
216 -- So we have to filter out the non-local ones.
217 -- A separate function (importsFromLocalDecls) reports duplicate top level
218 -- decls, so here it's safe just to choose an arbitrary one.
220 -- There should never be a qualified name in a binding position
221 -- The parser could check this, but doesn't (yet)
223 = getSrcLocM `thenM` \ loc ->
224 qualNameErr (text "In its declaration") (rdr_name,loc) `thenM_`
225 returnM (mkUnboundName rdr_name)
228 = ASSERT( not (isOrig rdr_name) )
229 -- Original names are used only for occurrences,
232 getModeRn `thenM` \ mode ->
235 getSrcLocM `thenM` \ loc ->
236 newTopBinder mod rdr_name loc
238 other -> lookupTopSrcBndr rdr_name
240 lookupTopSrcBndr :: RdrName -> TcRn m Name
241 lookupTopSrcBndr rdr_name
242 = lookupTopSrcBndr_maybe rdr_name `thenM` \ maybe_name ->
244 Just name -> returnM name
245 Nothing -> unboundName rdr_name
248 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
249 -- Look up a source-code binder
251 -- Ignores imported names; for example, this is OK:
253 -- infix 9 f -- The 'f' here does not need to be qualified
254 -- f x = x -- Nor here, of course
256 lookupTopSrcBndr_maybe rdr_name
257 | Just name <- isExact_maybe rdr_name
258 -- This is here just to catch the PrelBase defn of (say) [] and similar
259 -- The parser reads the special syntax and returns an Exact RdrName
260 -- But the global_env contains only Qual RdrNames, so we won't
261 -- find it there; instead just get the name via the Orig route
263 -- We are at a binding site for the name, so check first that it
264 -- the current module is the correct one; otherwise GHC can get
265 -- very confused indeed. This test rejects code like
266 -- data T = (,) Int Int
267 -- unless we are in GHC.Tup
268 = getModule `thenM` \ mod ->
269 checkErr (moduleName mod == moduleName (nameModule name))
270 (badOrigBinding rdr_name) `thenM_`
274 = getGlobalRdrEnv `thenM` \ global_env ->
275 case lookupRdrEnv global_env rdr_name of
276 Nothing -> returnM Nothing
277 Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
278 [] -> returnM Nothing
279 (n:ns) -> returnM (Just n)
282 -- lookupSigOccRn is used for type signatures and pragmas
288 -- It's clear that the 'f' in the signature must refer to A.f
289 -- The Haskell98 report does not stipulate this, but it will!
290 -- So we must treat the 'f' in the signature in the same way
291 -- as the binding occurrence of 'f', using lookupBndrRn
292 lookupSigOccRn :: RdrName -> RnM Name
293 lookupSigOccRn = lookupBndrRn
295 -- lookupInstDeclBndr is used for the binders in an
296 -- instance declaration. Here we use the class name to
299 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
300 -- We use the selector name as the binder
301 lookupInstDeclBndr cls_name rdr_name
303 = -- Find all the things the class op name maps to
304 -- and pick the one with the right parent name
305 getGblEnv `thenM` \ gbl_env ->
307 avail_env = imp_env (tcg_imports gbl_env)
309 case lookupAvailEnv avail_env cls_name of
311 -- If the class itself isn't in scope, then cls_name will
312 -- be unboundName, and there'll already be an error for
313 -- that in the error list. Example:
314 -- e.g. import Prelude hiding( Ord )
315 -- instance Ord T where ...
316 -- The program is wrong, but that should not cause a crash.
317 returnM (mkUnboundName rdr_name)
319 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
320 (n:ns)-> ASSERT( null ns ) returnM n
321 [] -> unboundName rdr_name
323 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
325 | isQual rdr_name -- Should never have a qualified name in a binding position
326 = getSrcLocM `thenM` \ loc ->
327 qualNameErr (text "In an instance method") (rdr_name,loc) `thenM_`
328 returnM (mkUnboundName rdr_name)
330 | otherwise -- Occurs in derived instances, where we just
331 -- refer directly to the right method, and avail_env
333 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
334 lookupOrigName rdr_name
337 occ = rdrNameOcc rdr_name
339 lookupSysBndr :: RdrName -> RnM Name
340 -- Used for the 'system binders' in a data type or class declaration
341 -- Do *not* look up in the RdrEnv; these system binders are never in scope
342 -- Instead, get the module from the monad... but remember that
343 -- where the module is depends on whether we are renaming source or
344 -- interface file stuff
345 lookupSysBndr rdr_name
346 = getSrcLocM `thenM` \ loc ->
347 getModeRn `thenM` \ mode ->
349 InterfaceMode mod -> newTopBinder mod rdr_name loc
350 other -> getModule `thenM` \ mod ->
351 newTopBinder mod rdr_name loc
353 -- lookupOccRn looks up an occurrence of a RdrName
354 lookupOccRn :: RdrName -> RnM Name
356 = getLocalRdrEnv `thenM` \ local_env ->
357 case lookupRdrEnv local_env rdr_name of
358 Just name -> returnM name
359 Nothing -> lookupGlobalOccRn rdr_name
361 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
362 -- environment. It's used only for
363 -- record field names
364 -- class op names in class and instance decls
366 lookupGlobalOccRn rdr_name
367 = getModeRn `thenM` \ mode ->
369 InterfaceMode mod -> lookupIfaceName mod rdr_name
370 SourceMode -> lookupSrcName rdr_name
373 | not (isQual rdr_name) ->
374 lookupSrcName rdr_name
376 -- We allow qualified names on the command line to refer to
377 -- *any* name exported by any module in scope, just as if
378 -- there was an "import qualified M" declaration for every
381 -- First look up the name in the normal environment. If
382 -- it isn't there, we manufacture a new occurrence of an
385 lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
387 Just name -> returnM name
388 Nothing -> lookupQualifiedName rdr_name
390 -- A qualified name on the command line can refer to any module at all: we
391 -- try to load the interface if we don't already have it.
392 lookupQualifiedName :: RdrName -> TcRn m Name
393 lookupQualifiedName rdr_name
395 mod = rdrNameModule rdr_name
396 occ = rdrNameOcc rdr_name
398 loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
399 case [ name | (_,avails) <- mi_exports iface,
401 name <- availNames avail,
402 nameOccName name == occ ] of
403 (n:ns) -> ASSERT (null ns) returnM n
404 _ -> unboundName rdr_name
406 lookupSrcName :: RdrName -> TcRn m Name
407 lookupSrcName rdr_name
408 = lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
410 Nothing -> unboundName rdr_name
411 Just name -> returnM name
413 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
414 lookupSrcName_maybe rdr_name
415 | Just name <- isExact_maybe rdr_name -- Can occur in source code too
416 = returnM (Just name)
418 | isOrig rdr_name -- An original name
419 = newGlobalName (rdrNameModule rdr_name)
420 (rdrNameOcc rdr_name) `thenM` \ name ->
424 = lookupGRE rdr_name `thenM` \ mb_gre ->
426 Nothing -> returnM Nothing
427 Just gre -> returnM (Just (gre_name gre))
429 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
431 = getGlobalRdrEnv `thenM` \ global_env ->
432 case lookupRdrEnv global_env rdr_name of
433 Just [gre] -> case gre_deprec gre of
434 Nothing -> returnM (Just gre)
435 Just _ -> warnDeprec gre `thenM_`
437 Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff `thenM_`
439 Nothing -> return Nothing
441 lookupIfaceName :: Module -> RdrName -> TcRn m Name
442 -- An Unqual is allowed; interface files contain
443 -- unqualified names for locally-defined things, such as
444 -- constructors of a data type.
445 lookupIfaceName mod rdr_name
446 | isUnqual rdr_name = newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
447 | otherwise = lookupOrigName rdr_name
449 lookupOrigName :: RdrName -> TcRn m Name
450 -- Just for original or exact names
451 lookupOrigName rdr_name
452 | Just n <- isExact_maybe rdr_name
453 -- This happens in derived code, which we
454 -- rename in InterfaceMode
457 | otherwise -- Usually Orig, but can be a Qual when
458 -- we are reading a .hi-boot file
459 = newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
462 dataTcOccs :: RdrName -> [RdrName]
463 -- If the input is a data constructor, return both it and a type
464 -- constructor. This is useful when we aren't sure which we are
467 | isDataOcc occ = [rdr_name, rdr_name_tc]
468 | otherwise = [rdr_name]
470 occ = rdrNameOcc rdr_name
471 rdr_name_tc = setRdrNameSpace rdr_name tcName
475 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
476 returnM (mkUnboundName rdr_name)
479 %*********************************************************
483 %*********************************************************
486 --------------------------------
487 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
488 -- Used for nested fixity decls
489 -- No need to worry about type constructors here,
490 -- Should check for duplicates but we don't
491 bindLocalFixities fixes thing_inside
492 | null fixes = thing_inside
493 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
494 extendFixityEnv new_bit thing_inside
496 rn_sig (FixitySig v fix src_loc)
497 = addSrcLoc src_loc $
498 lookupSigOccRn v `thenM` \ new_v ->
499 returnM (new_v, FixitySig new_v fix src_loc)
502 --------------------------------
503 lookupFixity is a bit strange.
505 * Nested local fixity decls are put in the local fixity env, which we
506 find with getFixtyEnv
508 * Imported fixities are found in the HIT or PIT
510 * Top-level fixity decls in this module may be for Names that are
511 either Global (constructors, class operations)
512 or Local/Exported (everything else)
513 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
514 We put them all in the local fixity environment
517 lookupFixityRn :: Name -> RnM Fixity
519 = getModule `thenM` \ this_mod ->
520 if nameIsLocalOrFrom this_mod name
521 then -- It's defined in this module
522 getFixityEnv `thenM` \ local_fix_env ->
523 returnM (lookupFixity local_fix_env name)
525 else -- It's imported
526 -- For imported names, we have to get their fixities by doing a
527 -- loadHomeInterface, and consulting the Ifaces that comes back
528 -- from that, because the interface file for the Name might not
529 -- have been loaded yet. Why not? Suppose you import module A,
530 -- which exports a function 'f', thus;
531 -- module CurrentModule where
533 -- module A( f ) where
535 -- Then B isn't loaded right away (after all, it's possible that
536 -- nothing from B will be used). When we come across a use of
537 -- 'f', we need to know its fixity, and it's then, and only
538 -- then, that we load B.hi. That is what's happening here.
539 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
540 returnM (lookupFixity (mi_fixities iface) name)
542 doc = ptext SLIT("Checking fixity for") <+> ppr name
543 name_mod = moduleName (nameModule name)
547 %*********************************************************
549 \subsection{Implicit free vars and sugar names}
551 %*********************************************************
553 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
554 mentioned explicitly, but which might be needed by the type checker.
557 implicitStmtFVs source_fvs -- Compiling a statement
558 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
560 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName]
561 -- These are all needed implicitly when compiling a statement
562 -- See TcModule.tc_stmts
564 implicitModuleFVs source_fvs
565 = mkTemplateHaskellFVs source_fvs `plusFV`
566 namesNeededForFlattening `plusFV`
569 -- This is a bit of a hack. When we see the Template-Haskell construct
571 -- we are going to need lots of the ``smart constructors'' defined in
572 -- the main Template Haskell data type module. Rather than treat them
573 -- all as free vars at every occurrence site, we just make the Q type
574 -- consructor a free var.... and then use that here to haul in the others
575 mkTemplateHaskellFVs source_fvs
577 -- Only if Template Haskell is enabled
578 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
580 | otherwise = emptyFVs
582 -- ubiquitous_names are loaded regardless, because
583 -- they are needed in virtually every program
585 = mkFVs [unpackCStringName, unpackCStringFoldrName,
586 unpackCStringUtf8Name, eqStringName,
587 -- Virtually every program has error messages in it somewhere
588 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
589 -- Add occurrences for very frequently used types.
590 -- (e.g. we don't want to be bothered with making
591 -- funTyCon a free var at every function application!)
594 %************************************************************************
596 \subsection{Re-bindable desugaring names}
598 %************************************************************************
600 Haskell 98 says that when you say "3" you get the "fromInteger" from the
601 Standard Prelude, regardless of what is in scope. However, to experiment
602 with having a language that is less coupled to the standard prelude, we're
603 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
604 happens to be in scope. Then you can
606 import MyPrelude as Prelude
607 to get the desired effect.
609 At the moment this just happens for
610 * fromInteger, fromRational on literals (in expressions and patterns)
611 * negate (in expressions)
612 * minus (arising from n+k patterns)
615 We store the relevant Name in the HsSyn tree, in
616 * HsIntegral/HsFractional
620 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
621 fromRationalName etc), but the renamer changes this to the appropriate user
622 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
624 We treat the orignal (standard) names as free-vars too, because the type checker
625 checks the type of the user thing against the type of the standard thing.
628 lookupSyntaxName :: Name -- The standard name
629 -> RnM (Name, FreeVars) -- Possibly a non-standard name
630 lookupSyntaxName std_name
631 = getModeRn `thenM` \ mode ->
632 if isInterfaceMode mode then
633 returnM (std_name, unitFV std_name)
634 -- Happens for 'derived' code
635 -- where we don't want to rebind
638 doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
639 if not no_prelude then
640 returnM (std_name, unitFV std_name) -- Normal case
643 -- Get the similarly named thing from the local environment
644 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
645 returnM (usr_name, mkFVs [usr_name, std_name])
649 %*********************************************************
653 %*********************************************************
656 newLocalsRn :: [(RdrName,SrcLoc)]
658 newLocalsRn rdr_names_w_loc
659 = newUniqueSupply `thenM` \ us ->
661 uniqs = uniqsFromSupply us
662 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
663 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
669 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
670 -> [(RdrName,SrcLoc)]
673 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
674 = getModeRn `thenM` \ mode ->
675 getLocalRdrEnv `thenM` \ local_env ->
676 getGlobalRdrEnv `thenM` \ global_env ->
678 -- Check for duplicate names
679 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
681 -- Warn about shadowing, but only in source modules
683 check_shadow (rdr_name,loc)
684 | rdr_name `elemRdrEnv` local_env
685 || rdr_name `elemRdrEnv` global_env
686 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
692 SourceMode -> ifOptM Opt_WarnNameShadowing $
693 mappM_ check_shadow rdr_names_w_loc
697 newLocalsRn rdr_names_w_loc `thenM` \ names ->
699 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
701 setLocalRdrEnv new_local_env (enclosed_scope names)
703 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
704 -- A specialised variant when renaming stuff from interface
705 -- files (of which there is a lot)
707 -- * no checks for shadowing
709 -- * deal with free vars
710 bindCoreLocalRn rdr_name enclosed_scope
711 = getSrcLocM `thenM` \ loc ->
712 getLocalRdrEnv `thenM` \ name_env ->
713 newUnique `thenM` \ uniq ->
715 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
716 new_name_env = extendRdrEnv name_env rdr_name name
718 setLocalRdrEnv new_name_env (enclosed_scope name)
720 bindCoreLocalsRn [] thing_inside = thing_inside []
721 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
722 bindCoreLocalsRn bs $ \ names' ->
723 thing_inside (name':names')
725 bindLocalNames names enclosed_scope
726 = getLocalRdrEnv `thenM` \ name_env ->
727 setLocalRdrEnv (extendLocalRdrEnv name_env names)
730 bindLocalNamesFV names enclosed_scope
731 = bindLocalNames names $
732 enclosed_scope `thenM` \ (thing, fvs) ->
733 returnM (thing, delListFromNameSet fvs names)
736 -------------------------------------
737 bindLocalRn doc rdr_name enclosed_scope
738 = getSrcLocM `thenM` \ loc ->
739 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
743 bindLocalsRn doc rdr_names enclosed_scope
744 = getSrcLocM `thenM` \ loc ->
745 bindLocatedLocalsRn doc
746 (rdr_names `zip` repeat loc)
749 -- binLocalsFVRn is the same as bindLocalsRn
750 -- except that it deals with free vars
751 bindLocalsFVRn doc rdr_names enclosed_scope
752 = bindLocalsRn doc rdr_names $ \ names ->
753 enclosed_scope names `thenM` \ (thing, fvs) ->
754 returnM (thing, delListFromNameSet fvs names)
756 -------------------------------------
757 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
758 -- This tiresome function is used only in rnSourceDecl on InstDecl
759 extendTyVarEnvFVRn tyvars enclosed_scope
760 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
761 returnM (thing, delListFromNameSet fvs tyvars)
763 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
764 -> ([HsTyVarBndr Name] -> RnM a)
766 bindTyVarsRn doc_str tyvar_names enclosed_scope
767 = getSrcLocM `thenM` \ loc ->
769 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
771 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
772 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
774 bindPatSigTyVars :: [RdrNameHsType]
777 -- Find the type variables in the pattern type
778 -- signatures that must be brought into scope
780 bindPatSigTyVars tys enclosed_scope
781 = getLocalRdrEnv `thenM` \ name_env ->
782 getSrcLocM `thenM` \ loc ->
784 forall_tyvars = nub [ tv | ty <- tys,
785 tv <- extractHsTyRdrTyVars ty,
786 not (tv `elemFM` name_env)
788 -- The 'nub' is important. For example:
789 -- f (x :: t) (y :: t) = ....
790 -- We don't want to complain about binding t twice!
792 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
793 doc_sig = text "In a pattern type-signature"
795 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
796 enclosed_scope `thenM` \ (thing, fvs) ->
797 returnM (thing, delListFromNameSet fvs names)
800 -------------------------------------
801 checkDupOrQualNames, checkDupNames :: SDoc
802 -> [(RdrName, SrcLoc)]
804 -- Works in any variant of the renamer monad
806 checkDupOrQualNames doc_str rdr_names_w_loc
807 = -- Check for use of qualified names
808 mappM_ (qualNameErr doc_str) quals `thenM_`
809 checkDupNames doc_str rdr_names_w_loc
811 quals = filter (isQual . fst) rdr_names_w_loc
813 checkDupNames doc_str rdr_names_w_loc
814 = -- Check for duplicated names in a binding group
815 mappM_ (dupNamesErr doc_str) dups
817 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
821 %************************************************************************
823 \subsection{GlobalRdrEnv}
825 %************************************************************************
828 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
829 -> Bool -- True <=> want unqualified import
830 -> (Name -> Provenance)
831 -> Avails -- Whats imported
835 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
838 -- Make the name environment. We're talking about a
839 -- single module here, so there must be no name clashes.
840 -- In practice there only ever will be if it's the module
843 -- Add qualified names for the things that are available
844 -- (Qualified names are always imported)
845 gbl_env1 = foldl add_avail emptyRdrEnv avails
847 -- Add unqualified names
848 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
849 | otherwise = gbl_env1
851 add_unqual env (qual_name, elts)
852 = foldl add_one env elts
854 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
855 unqual_name = unqualifyRdrName qual_name
856 -- The qualified import should only have added one
857 -- binding for each qualified name! But if there's an error in
858 -- the module (multiple bindings for the same name) we may get
859 -- duplicates. So the simple thing is to do the fold.
861 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
862 add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
864 add_name parent env name -- Add qualified name only
865 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
867 occ = nameOccName name
868 elt = GRE {gre_name = name,
870 gre_prov = mk_provenance name,
871 gre_deprec = lookupDeprec deprecs name}
876 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
877 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
879 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
880 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
882 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
883 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
885 combine_globals :: [GlobalRdrElt] -- Old
886 -> [GlobalRdrElt] -- New
888 combine_globals ns_old ns_new -- ns_new is often short
889 = foldr add ns_old ns_new
891 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
894 choose n m | n `beats` m = n
897 g1 `beats` g2 = gre_name g1 == gre_name g2 &&
898 gre_prov g1 `hasBetterProv` gre_prov g2
900 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
901 is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
902 is_duplicate g1 g2 = gre_name g1 == gre_name g2
905 We treat two bindings of a locally-defined name as a duplicate,
906 because they might be two separate, local defns and we want to report
907 and error for that, {\em not} eliminate a duplicate.
909 On the other hand, if you import the same name from two different
910 import statements, we {\em do} want to eliminate the duplicate, not report
913 If a module imports itself then there might be a local defn and an imported
914 defn of the same name; in this case the names will compare as equal, but
915 will still have different provenances.
918 %************************************************************************
920 \subsection{Free variable manipulation}
922 %************************************************************************
926 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
928 (ys, fvs_s) = unzip stuff
930 returnM (ys, plusFVs fvs_s)
934 %************************************************************************
936 \subsection{Envt utility functions}
938 %************************************************************************
941 warnUnusedModules :: [ModuleName] -> TcRn m ()
942 warnUnusedModules mods
943 = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
945 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
946 text "is imported, but nothing from it is used",
947 parens (ptext SLIT("except perhaps instances visible in") <+>
950 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
951 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
952 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
954 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
955 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
956 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
958 -------------------------
960 warnUnusedGREs gres = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
961 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
963 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
964 warnUnusedBinds names
965 = mappM_ warnUnusedGroup groups
967 -- Group by provenance
968 groups = equivClasses cmp names
969 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
972 -------------------------
974 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
975 warnUnusedGroup names
976 | null filtered_names = returnM ()
977 | not is_local = returnM ()
979 = addSrcLoc def_loc $
981 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
983 filtered_names = filter reportable names
984 (name1, prov1) = head filtered_names
985 (is_local, def_loc, msg)
987 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
989 NonLocalDef (UserImport mod loc _)
990 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
992 reportable (name,_) = case occNameUserString (nameOccName name) of
995 -- Haskell 98 encourages compilers to suppress warnings about
996 -- unused names in a pattern if they start with "_".
1000 addNameClashErrRn rdr_name (np1:nps)
1001 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1002 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1004 msg1 = ptext SLIT("either") <+> mk_ref np1
1005 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1006 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1008 shadowedNameWarn shadow
1009 = hsep [ptext SLIT("This binding for"),
1010 quotes (ppr shadow),
1011 ptext SLIT("shadows an existing binding")]
1014 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1016 flavour = occNameFlavour (rdrNameOcc name)
1019 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1020 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1022 qualNameErr descriptor (name,loc)
1024 addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1027 dupNamesErr descriptor ((name,loc) : dup_things)
1029 addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1033 warnDeprec :: GlobalRdrElt -> TcRn m ()
1034 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1035 = ifOptM Opt_WarnDeprecations $
1036 addWarn (sep [ text (occNameFlavour (nameOccName name)) <+>
1037 quotes (ppr name) <+> text "is deprecated:",