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
13 import HscTypes ( ModIface(..) )
15 import RdrHsSyn ( RdrNameIE )
16 import RdrName ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
17 mkRdrUnqual, mkRdrQual, qualifyRdrName, lookupRdrEnv, foldRdrEnv
19 import HsTypes ( hsTyVarName, replaceTyVarName )
20 import HscTypes ( Provenance(..), pprNameProvenance, hasBetterProv,
21 ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), AvailEnv,
22 AvailInfo, Avails, GenAvailInfo(..), NameSupply(..),
23 Deprecations(..), lookupDeprec,
29 mkLocalName, mkGlobalName,
30 mkIPName, nameOccName, nameModule_maybe,
35 import OccName ( OccName, occNameUserString, occNameFlavour )
36 import Module ( ModuleName, moduleName, mkVanillaModule,
37 mkSysModuleNameFS, moduleNameFS, WhereFrom(..) )
38 import PrelNames ( mkUnboundName, syntaxList, SyntaxMap, vanillaSyntaxMap,
40 mAIN_Name, pREL_MAIN_Name,
41 ioTyConName, integerTyConName, doubleTyConName, intTyConName,
42 boolTyConName, funTyConName,
43 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
44 eqStringName, printName,
45 hasKey, fractionalClassKey, numClassKey,
46 bindIOName, returnIOName, failIOName
48 import TysWiredIn ( unitTyCon ) -- A little odd
51 import SrcLoc ( SrcLoc, noSrcLoc )
53 import ListSetOps ( removeDups, equivClasses )
54 import Util ( sortLt )
56 import UniqFM ( lookupWithDefaultUFM )
57 import Maybes ( orElse )
59 import FastString ( FastString )
62 %*********************************************************
64 \subsection{Making new names}
66 %*********************************************************
69 newTopBinder :: Module -> RdrName -> SrcLoc -> RnM d Name
70 -- newTopBinder puts into the cache the binder with the
71 -- module information set correctly. When the decl is later renamed,
72 -- the binding site will thereby get the correct module.
73 -- There maybe occurrences that don't have the correct Module, but
74 -- by the typechecker will propagate the binding definition to all
75 -- the occurrences, so that doesn't matter
77 newTopBinder mod rdr_name loc
78 = -- First check the cache
80 -- There should never be a qualified name in a binding position (except in instance decls)
81 -- The parser doesn't check this because the same parser parses instance decls
82 (if isQual rdr_name then
83 qualNameErr (text "its declaration") (rdr_name,loc)
88 getNameSupplyRn `thenRn` \ name_supply ->
90 occ = rdrNameOcc rdr_name
91 key = (moduleName mod, occ)
92 cache = nsNames name_supply
94 case lookupFM cache key of
96 -- A hit in the cache! We are at the binding site of the name, and
97 -- this is the moment when we know all about
98 -- a) the Name's host Module (in particular, which
99 -- package it comes from)
100 -- b) its defining SrcLoc
101 -- So we update this info
104 new_name = setNameModuleAndLoc name mod loc
105 new_cache = addToFM cache key new_name
107 setNameSupplyRn (name_supply {nsNames = new_cache}) `thenRn_`
108 -- traceRn (text "newTopBinder: overwrite" <+> ppr new_name) `thenRn_`
111 -- Miss in the cache!
112 -- Build a completely new Name, and put it in the cache
113 -- Even for locally-defined names we use implicitImportProvenance;
114 -- updateProvenances will set it to rights
116 (us', us1) = splitUniqSupply (nsUniqs name_supply)
117 uniq = uniqFromSupply us1
118 new_name = mkGlobalName uniq mod occ loc
119 new_cache = addToFM cache key new_name
121 setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
122 -- traceRn (text "newTopBinder: new" <+> ppr new_name) `thenRn_`
126 newGlobalName :: ModuleName -> OccName -> RnM d Name
127 -- Used for *occurrences*. We make a place-holder Name, really just
128 -- to agree on its unique, which gets overwritten when we read in
129 -- the binding occurence later (newTopBinder)
130 -- The place-holder Name doesn't have the right SrcLoc, and its
131 -- Module won't have the right Package either.
133 -- (We have to pass a ModuleName, not a Module, because we may be
134 -- simply looking at an occurrence M.x in an interface file.)
136 -- This means that a renamed program may have incorrect info
137 -- on implicitly-imported occurrences, but the correct info on the
138 -- *binding* declaration. It's the type checker that propagates the
139 -- correct information to all the occurrences.
140 -- Since implicitly-imported names never occur in error messages,
141 -- it doesn't matter that we get the correct info in place till later,
142 -- (but since it affects DLL-ery it does matter that we get it right
144 newGlobalName mod_name occ
145 = getNameSupplyRn `thenRn` \ name_supply ->
147 key = (mod_name, occ)
148 cache = nsNames name_supply
150 case lookupFM cache key of
151 Just name -> -- traceRn (text "newGlobalName: hit" <+> ppr name) `thenRn_`
154 Nothing -> setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
155 -- traceRn (text "newGlobalName: new" <+> ppr name) `thenRn_`
158 (us', us1) = splitUniqSupply (nsUniqs name_supply)
159 uniq = uniqFromSupply us1
160 mod = mkVanillaModule mod_name
161 name = mkGlobalName uniq mod occ noSrcLoc
162 new_cache = addToFM cache key name
165 = getNameSupplyRn `thenRn` \ name_supply ->
167 ipcache = nsIPs name_supply
169 case lookupFM ipcache key of
170 Just name -> returnRn name
171 Nothing -> setNameSupplyRn (name_supply {nsUniqs = us', nsIPs = new_ipcache}) `thenRn_`
174 (us', us1) = splitUniqSupply (nsUniqs name_supply)
175 uniq = uniqFromSupply us1
176 name = mkIPName uniq key
177 new_ipcache = addToFM ipcache key name
178 where key = (rdrNameOcc rdr_name)
181 %*********************************************************
183 \subsection{Looking up names}
185 %*********************************************************
187 Looking up a name in the RnEnv.
190 lookupBndrRn rdr_name
191 = getLocalNameEnv `thenRn` \ local_env ->
192 case lookupRdrEnv local_env rdr_name of
193 Just name -> returnRn name
194 Nothing -> lookupTopBndrRn rdr_name
196 lookupTopBndrRn rdr_name
197 = getModeRn `thenRn` \ mode ->
198 if isInterfaceMode mode
199 then lookupIfaceName rdr_name
200 else -- Source mode, so look up a *qualified* version
201 -- of the name, so that we get the right one even
202 -- if there are many with the same occ name
203 -- There must *be* a binding
204 getModuleRn `thenRn` \ mod ->
205 getGlobalNameEnv `thenRn` \ global_env ->
206 lookupSrcName global_env (qualifyRdrName (moduleName mod) rdr_name)
208 -- lookupSigOccRn is used for type signatures and pragmas
214 -- It's clear that the 'f' in the signature must refer to A.f
215 -- The Haskell98 report does not stipulate this, but it will!
216 -- So we must treat the 'f' in the signature in the same way
217 -- as the binding occurrence of 'f', using lookupBndrRn
218 lookupSigOccRn :: RdrName -> RnMS Name
219 lookupSigOccRn = lookupBndrRn
221 -- lookupOccRn looks up an occurrence of a RdrName
222 lookupOccRn :: RdrName -> RnMS Name
224 = getLocalNameEnv `thenRn` \ local_env ->
225 case lookupRdrEnv local_env rdr_name of
226 Just name -> returnRn name
227 Nothing -> lookupGlobalOccRn rdr_name
229 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
230 -- environment. It's used only for
231 -- record field names
232 -- class op names in class and instance decls
234 lookupGlobalOccRn rdr_name
235 = getModeRn `thenRn` \ mode ->
236 if (isInterfaceMode mode)
237 then lookupIfaceName rdr_name
240 getGlobalNameEnv `thenRn` \ global_env ->
242 SourceMode -> lookupSrcName global_env rdr_name
245 | not (isQual rdr_name) ->
246 lookupSrcName global_env rdr_name
248 -- We allow qualified names on the command line to refer to
249 -- *any* name exported by any module in scope, just as if
250 -- there was an "import qualified M" declaration for every
253 -- First look up the name in the normal environment. If
254 -- it isn't there, we manufacture a new occurrence of an
257 case lookupRdrEnv global_env rdr_name of
258 Just _ -> lookupSrcName global_env rdr_name
259 Nothing -> lookupQualifiedName rdr_name
261 -- a qualified name on the command line can refer to any module at all: we
262 -- try to load the interface if we don't already have it.
263 lookupQualifiedName :: RdrName -> RnM d Name
264 lookupQualifiedName rdr_name
266 mod = rdrNameModule rdr_name
267 occ = rdrNameOcc rdr_name
269 loadInterface (ppr rdr_name) mod ImportBySystem `thenRn` \ iface ->
270 case [ name | (_,avails) <- mi_exports iface,
272 name <- availNames avail,
273 nameOccName name == occ ] of
274 (n:ns) -> ASSERT (null ns) returnRn n
275 _ -> failWithRn (mkUnboundName rdr_name) (unknownNameErr rdr_name)
277 lookupSrcName :: GlobalRdrEnv -> RdrName -> RnM d Name
278 -- NB: passed GlobalEnv explicitly, not necessarily in RnMS monad
279 lookupSrcName global_env rdr_name
280 | isOrig rdr_name -- Can occur in source code too
281 = lookupOrigName rdr_name
284 = case lookupRdrEnv global_env rdr_name of
285 Just [GRE name _ Nothing] -> returnRn name
286 Just [GRE name _ (Just deprec)] -> warnDeprec name deprec `thenRn_`
288 Just stuff@(GRE name _ _ : _) -> addNameClashErrRn rdr_name stuff `thenRn_`
290 Nothing -> failWithRn (mkUnboundName rdr_name)
291 (unknownNameErr rdr_name)
293 lookupOrigName :: RdrName -> RnM d Name
294 lookupOrigName rdr_name
295 = ASSERT( isOrig rdr_name )
296 newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
298 lookupIfaceUnqual :: RdrName -> RnM d Name
299 lookupIfaceUnqual rdr_name
300 = ASSERT( isUnqual rdr_name )
301 -- An Unqual is allowed; interface files contain
302 -- unqualified names for locally-defined things, such as
303 -- constructors of a data type.
304 getModuleRn `thenRn ` \ mod ->
305 newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
307 lookupIfaceName :: RdrName -> RnM d Name
308 lookupIfaceName rdr_name
309 | isUnqual rdr_name = lookupIfaceUnqual rdr_name
310 | otherwise = lookupOrigName rdr_name
313 @lookupOrigName@ takes an RdrName representing an {\em original}
314 name, and adds it to the occurrence pool so that it'll be loaded
315 later. This is used when language constructs (such as monad
316 comprehensions, overloaded literals, or deriving clauses) require some
317 stuff to be loaded that isn't explicitly mentioned in the code.
319 This doesn't apply in interface mode, where everything is explicit,
320 but we don't check for this case: it does no harm to record an
321 ``extra'' occurrence and @lookupOrigNames@ isn't used much in
322 interface mode (it's only the @Nothing@ clause of @rnDerivs@ that
323 calls it at all I think).
325 \fbox{{\em Jan 98: this comment is wrong: @rnHsType@ uses it quite a bit.}}
328 lookupOrigNames :: [RdrName] -> RnM d NameSet
329 lookupOrigNames rdr_names
330 = mapRn lookupOrigName rdr_names `thenRn` \ names ->
331 returnRn (mkNameSet names)
334 lookupSysBinder is used for the "system binders" of a type, class, or
335 instance decl. It ensures that the module is set correctly in the
336 name cache, and sets the provenance on the returned name too. The
337 returned name will end up actually in the type, class, or instance.
340 lookupSysBinder rdr_name
341 = ASSERT( isUnqual rdr_name )
342 getModuleRn `thenRn` \ mod ->
343 getSrcLocRn `thenRn` \ loc ->
344 newTopBinder mod rdr_name loc
348 %*********************************************************
350 \subsection{Implicit free vars and sugar names}
352 %*********************************************************
354 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
355 mentioned explicitly, but which might be needed by the type checker.
358 getImplicitStmtFVs -- Compiling a statement
359 = returnRn (mkFVs [printName, bindIOName, returnIOName, failIOName]
360 `plusFV` ubiquitousNames)
361 -- These are all needed implicitly when compiling a statement
362 -- See TcModule.tc_stmts
364 getImplicitModuleFVs mod_name decls -- Compiling a module
365 = lookupOrigNames deriv_occs `thenRn` \ deriving_names ->
366 returnRn (deriving_names `plusFV` implicit_main `plusFV` ubiquitousNames)
368 -- Add occurrences for IO or PrimIO
369 implicit_main | mod_name == mAIN_Name
370 || mod_name == pREL_MAIN_Name = unitFV ioTyConName
371 | otherwise = emptyFVs
373 deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
374 cls <- deriv_classes,
375 occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
377 -- ubiquitous_names are loaded regardless, because
378 -- they are needed in virtually every program
380 = mkFVs [unpackCStringName, unpackCStringFoldrName,
381 unpackCStringUtf8Name, eqStringName]
382 -- Virtually every program has error messages in it somewhere
385 mkFVs [getName unitTyCon, funTyConName, boolTyConName, intTyConName]
386 -- Add occurrences for very frequently used types.
387 -- (e.g. we don't want to be bothered with making funTyCon a
388 -- free var at every function application!)
392 implicitGates :: Name -> FreeVars
393 -- If we load class Num, add Integer to the gates
394 -- This takes account of the fact that Integer might be needed for
395 -- defaulting, but we don't want to load Integer (and all its baggage)
396 -- if there's no numeric stuff needed.
397 -- Similarly for class Fractional and Double
399 -- NB: If we load (say) Floating, we'll end up loading Fractional too,
400 -- since Fractional is a superclass of Floating
401 implicitGates cls | cls `hasKey` numClassKey = unitFV integerTyConName
402 | cls `hasKey` fractionalClassKey = unitFV doubleTyConName
403 | otherwise = emptyFVs
407 rnSyntaxNames :: GlobalRdrEnv -> FreeVars -> RnMG (FreeVars, SyntaxMap)
408 -- Look up the re-bindable syntactic sugar names
409 -- Any errors arising from these lookups may surprise the
410 -- programmer, since they aren't explicitly mentioned, and
411 -- the src line will be unhelpful (ToDo)
413 rnSyntaxNames gbl_env source_fvs
414 = doptRn Opt_NoImplicitPrelude `thenRn` \ no_prelude ->
415 if not no_prelude then
416 returnRn (source_fvs, vanillaSyntaxMap)
419 -- There's a -fno-implicit-prelude flag,
420 -- so build the re-mapping function
422 reqd_syntax_list = filter is_reqd syntaxList
423 is_reqd (n,_) = n `elemNameSet` source_fvs
424 lookup (n,rn) = lookupSrcName gbl_env rn `thenRn` \ rn' ->
427 mapRn lookup reqd_syntax_list `thenRn` \ rn_syntax_list ->
429 -- Delete the proxies and add the actuals
430 proxies = map fst rn_syntax_list
431 actuals = map snd rn_syntax_list
432 new_source_fvs = (proxies `delFVs` source_fvs) `plusFV` mkFVs actuals
434 syntax_env = mkNameEnv rn_syntax_list
435 syntax_map n = lookupNameEnv syntax_env n `orElse` n
437 returnRn (new_source_fvs, syntax_map)
441 %*********************************************************
445 %*********************************************************
448 newLocalsRn :: [(RdrName,SrcLoc)]
450 newLocalsRn rdr_names_w_loc
451 = getNameSupplyRn `thenRn` \ name_supply ->
453 n = length rdr_names_w_loc
454 (us', us1) = splitUniqSupply (nsUniqs name_supply)
455 uniqs = uniqsFromSupply n us1
456 names = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
457 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
460 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
464 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
465 -> [(RdrName,SrcLoc)]
466 -> ([Name] -> RnMS a)
468 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
469 = getModeRn `thenRn` \ mode ->
470 getLocalNameEnv `thenRn` \ name_env ->
472 -- Check for duplicate names
473 checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
475 doptRn Opt_WarnNameShadowing `thenRn` \ warn_shadow ->
477 -- Warn about shadowing, but only in source modules
479 SourceMode | warn_shadow -> mapRn_ (check_shadow name_env) rdr_names_w_loc
483 newLocalsRn rdr_names_w_loc `thenRn` \ names ->
485 new_local_env = addListToRdrEnv name_env (map fst rdr_names_w_loc `zip` names)
487 setLocalNameEnv new_local_env (enclosed_scope names)
490 check_shadow name_env (rdr_name,loc)
491 = case lookupRdrEnv name_env rdr_name of
492 Nothing -> returnRn ()
493 Just name -> pushSrcLocRn loc $
494 addWarnRn (shadowedNameWarn rdr_name)
496 bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
497 -- A specialised variant when renaming stuff from interface
498 -- files (of which there is a lot)
500 -- * no checks for shadowing
502 -- * deal with free vars
503 bindCoreLocalRn rdr_name enclosed_scope
504 = getSrcLocRn `thenRn` \ loc ->
505 getLocalNameEnv `thenRn` \ name_env ->
506 getNameSupplyRn `thenRn` \ name_supply ->
508 (us', us1) = splitUniqSupply (nsUniqs name_supply)
509 uniq = uniqFromSupply us1
510 name = mkLocalName uniq (rdrNameOcc rdr_name) loc
512 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
514 new_name_env = extendRdrEnv name_env rdr_name name
516 setLocalNameEnv new_name_env (enclosed_scope name)
518 bindCoreLocalsRn [] thing_inside = thing_inside []
519 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
520 bindCoreLocalsRn bs $ \ names' ->
521 thing_inside (name':names')
523 bindLocalNames names enclosed_scope
524 = getLocalNameEnv `thenRn` \ name_env ->
525 setLocalNameEnv (extendLocalRdrEnv name_env names)
528 bindLocalNamesFV names enclosed_scope
529 = bindLocalNames names $
530 enclosed_scope `thenRn` \ (thing, fvs) ->
531 returnRn (thing, delListFromNameSet fvs names)
534 -------------------------------------
535 bindLocalRn doc rdr_name enclosed_scope
536 = getSrcLocRn `thenRn` \ loc ->
537 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
541 bindLocalsRn doc rdr_names enclosed_scope
542 = getSrcLocRn `thenRn` \ loc ->
543 bindLocatedLocalsRn doc
544 (rdr_names `zip` repeat loc)
547 -- binLocalsFVRn is the same as bindLocalsRn
548 -- except that it deals with free vars
549 bindLocalsFVRn doc rdr_names enclosed_scope
550 = bindLocalsRn doc rdr_names $ \ names ->
551 enclosed_scope names `thenRn` \ (thing, fvs) ->
552 returnRn (thing, delListFromNameSet fvs names)
554 -------------------------------------
555 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
556 -- This tiresome function is used only in rnSourceDecl on InstDecl
557 extendTyVarEnvFVRn tyvars enclosed_scope
558 = bindLocalNames tyvars enclosed_scope `thenRn` \ (thing, fvs) ->
559 returnRn (thing, delListFromNameSet fvs tyvars)
561 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
562 -> ([HsTyVarBndr Name] -> RnMS a)
564 bindTyVarsRn doc_str tyvar_names enclosed_scope
565 = bindTyVars2Rn doc_str tyvar_names $ \ names tyvars ->
566 enclosed_scope tyvars
568 -- Gruesome name: return Names as well as HsTyVars
569 bindTyVars2Rn :: SDoc -> [HsTyVarBndr RdrName]
570 -> ([Name] -> [HsTyVarBndr Name] -> RnMS a)
572 bindTyVars2Rn doc_str tyvar_names enclosed_scope
573 = getSrcLocRn `thenRn` \ loc ->
575 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
577 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
578 enclosed_scope names (zipWith replaceTyVarName tyvar_names names)
580 bindTyVarsFVRn :: SDoc -> [HsTyVarBndr RdrName]
581 -> ([HsTyVarBndr Name] -> RnMS (a, FreeVars))
582 -> RnMS (a, FreeVars)
583 bindTyVarsFVRn doc_str rdr_names enclosed_scope
584 = bindTyVars2Rn doc_str rdr_names $ \ names tyvars ->
585 enclosed_scope tyvars `thenRn` \ (thing, fvs) ->
586 returnRn (thing, delListFromNameSet fvs names)
588 bindTyVarsFV2Rn :: SDoc -> [HsTyVarBndr RdrName]
589 -> ([Name] -> [HsTyVarBndr Name] -> RnMS (a, FreeVars))
590 -> RnMS (a, FreeVars)
591 bindTyVarsFV2Rn doc_str rdr_names enclosed_scope
592 = bindTyVars2Rn doc_str rdr_names $ \ names tyvars ->
593 enclosed_scope names tyvars `thenRn` \ (thing, fvs) ->
594 returnRn (thing, delListFromNameSet fvs names)
596 bindNakedTyVarsFVRn :: SDoc -> [RdrName]
597 -> ([Name] -> RnMS (a, FreeVars))
598 -> RnMS (a, FreeVars)
599 bindNakedTyVarsFVRn doc_str tyvar_names enclosed_scope
600 = getSrcLocRn `thenRn` \ loc ->
602 located_tyvars = [(tv, loc) | tv <- tyvar_names]
604 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
605 enclosed_scope names `thenRn` \ (thing, fvs) ->
606 returnRn (thing, delListFromNameSet fvs names)
609 -------------------------------------
610 checkDupOrQualNames, checkDupNames :: SDoc
611 -> [(RdrName, SrcLoc)]
613 -- Works in any variant of the renamer monad
615 checkDupOrQualNames doc_str rdr_names_w_loc
616 = -- Check for use of qualified names
617 mapRn_ (qualNameErr doc_str) quals `thenRn_`
618 checkDupNames doc_str rdr_names_w_loc
620 quals = filter (isQual . fst) rdr_names_w_loc
622 checkDupNames doc_str rdr_names_w_loc
623 = -- Check for duplicated names in a binding group
624 mapRn_ (dupNamesErr doc_str) dups
626 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
630 %************************************************************************
632 \subsection{GlobalRdrEnv}
634 %************************************************************************
637 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
638 -> Bool -- True <=> want unqualified import
639 -> Bool -- True <=> want qualified import
640 -> [AvailInfo] -- What's to be hidden (but only the unqualified
641 -- version is hidden)
642 -> (Name -> Provenance)
643 -> Avails -- Whats imported and how
647 mkGlobalRdrEnv this_mod unqual_imp qual_imp hides
648 mk_provenance avails deprecs
651 -- Make the name environment. We're talking about a
652 -- single module here, so there must be no name clashes.
653 -- In practice there only ever will be if it's the module
656 -- Add the things that are available
657 gbl_env1 = foldl add_avail emptyRdrEnv avails
659 -- Delete things that are hidden
660 gbl_env2 = foldl del_avail gbl_env1 hides
662 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
663 add_avail env avail = foldl add_name env (availNames avail)
666 | qual_imp && unqual_imp = env3
671 env1 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
672 env2 = addOneToGlobalRdrEnv env (mkRdrUnqual occ) elt
673 env3 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) elt
674 occ = nameOccName name
675 elt = GRE name (mk_provenance name) (lookupDeprec deprecs name)
677 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
679 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
681 mkIfaceGlobalRdrEnv :: [(ModuleName,Avails)] -> GlobalRdrEnv
682 -- Used to construct a GlobalRdrEnv for an interface that we've
683 -- read from a .hi file. We can't construct the original top-level
684 -- environment because we don't have enough info, but we compromise
685 -- by making an environment from its exports
686 mkIfaceGlobalRdrEnv m_avails
687 = foldl add emptyRdrEnv m_avails
689 add env (mod,avails) = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True False []
690 (\n -> LocalDef) avails NoDeprecs)
691 -- The NoDeprecs is a bit of a hack I suppose
695 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
696 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
698 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
699 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
701 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
702 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
704 combine_globals :: [GlobalRdrElt] -- Old
705 -> [GlobalRdrElt] -- New
707 combine_globals ns_old ns_new -- ns_new is often short
708 = foldr add ns_old ns_new
710 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
713 choose n m | n `beats` m = n
716 (GRE n pn _) `beats` (GRE m pm _) = n==m && pn `hasBetterProv` pm
718 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
719 is_duplicate (GRE n1 LocalDef _) (GRE n2 LocalDef _) = False
720 is_duplicate (GRE n1 _ _) (GRE n2 _ _) = n1 == n2
723 We treat two bindings of a locally-defined name as a duplicate,
724 because they might be two separate, local defns and we want to report
725 and error for that, {\em not} eliminate a duplicate.
727 On the other hand, if you import the same name from two different
728 import statements, we {\em do} want to eliminate the duplicate, not report
731 If a module imports itself then there might be a local defn and an imported
732 defn of the same name; in this case the names will compare as equal, but
733 will still have different provenances.
736 @unQualInScope@ returns a function that takes a @Name@ and tells whether
737 its unqualified name is in scope. This is put as a boolean flag in
738 the @Name@'s provenance to guide whether or not to print the name qualified
742 unQualInScope :: GlobalRdrEnv -> Name -> Bool
743 -- True if 'f' is in scope, and has only one binding
744 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
746 = (`elemNameSet` unqual_names)
748 unqual_names :: NameSet
749 unqual_names = foldRdrEnv add emptyNameSet env
750 add rdr_name [GRE name _ _] unquals | isUnqual rdr_name = addOneToNameSet unquals name
751 add _ _ unquals = unquals
755 %************************************************************************
759 %************************************************************************
762 plusAvail (Avail n1) (Avail n2) = Avail n1
763 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
766 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
769 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
770 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
772 emptyAvailEnv = emptyNameEnv
773 unitAvailEnv :: AvailInfo -> AvailEnv
774 unitAvailEnv a = unitNameEnv (availName a) a
776 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
777 plusAvailEnv = plusNameEnv_C plusAvail
779 availEnvElts = nameEnvElts
781 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
782 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
784 availsToNameSet :: [AvailInfo] -> NameSet
785 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
787 availName :: GenAvailInfo name -> name
788 availName (Avail n) = n
789 availName (AvailTC n _) = n
791 availNames :: GenAvailInfo name -> [name]
792 availNames (Avail n) = [n]
793 availNames (AvailTC n ns) = ns
795 -------------------------------------
796 filterAvail :: RdrNameIE -- Wanted
797 -> AvailInfo -- Available
798 -> Maybe AvailInfo -- Resulting available;
799 -- Nothing if (any of the) wanted stuff isn't there
801 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
802 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
803 | otherwise = Nothing
805 is_wanted name = nameOccName name `elem` wanted_occs
806 sub_names_ok = all (`elem` avail_occs) wanted_occs
807 avail_occs = map nameOccName ns
808 wanted_occs = map rdrNameOcc (want:wants)
810 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
813 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
815 filterAvail (IEVar _) avail@(Avail n) = Just avail
816 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
818 wanted n = nameOccName n == occ
820 -- The second equation happens if we import a class op, thus
822 -- where op is a class operation
824 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
825 -- We don't complain even if the IE says T(..), but
826 -- no constrs/class ops of T are available
827 -- Instead that's caught with a warning by the caller
829 filterAvail ie avail = Nothing
831 -------------------------------------
832 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
833 -- Group by module and sort by occurrence
834 -- This keeps the list in canonical order
835 groupAvails this_mod avails
836 = [ (mkSysModuleNameFS fs, sortLt lt avails)
837 | (fs,avails) <- fmToList groupFM
840 groupFM :: FiniteMap FastString Avails
841 -- Deliberately use the FastString so we
842 -- get a canonical ordering
843 groupFM = foldl add emptyFM avails
845 add env avail = addToFM_C combine env mod_fs [avail']
847 mod_fs = moduleNameFS (moduleName avail_mod)
848 avail_mod = case nameModule_maybe (availName avail) of
851 combine old _ = avail':old
852 avail' = sortAvail avail
854 a1 `lt` a2 = occ1 < occ2
856 occ1 = nameOccName (availName a1)
857 occ2 = nameOccName (availName a2)
859 sortAvail :: AvailInfo -> AvailInfo
860 -- Sort the sub-names into canonical order.
861 -- The canonical order has the "main name" at the beginning
862 -- (if it's there at all)
863 sortAvail (Avail n) = Avail n
864 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
865 | otherwise = AvailTC n ( sortLt lt ns)
867 n1 `lt` n2 = nameOccName n1 < nameOccName n2
871 %************************************************************************
873 \subsection{Free variable manipulation}
875 %************************************************************************
879 mapFvRn f xs = mapRn f xs `thenRn` \ stuff ->
881 (ys, fvs_s) = unzip stuff
883 returnRn (ys, plusFVs fvs_s)
887 %************************************************************************
889 \subsection{Envt utility functions}
891 %************************************************************************
894 warnUnusedModules :: [ModuleName] -> RnM d ()
895 warnUnusedModules mods
896 = doptRn Opt_WarnUnusedImports `thenRn` \ warn ->
897 if warn then mapRn_ (addWarnRn . unused_mod) mods
900 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
901 text "is imported, but nothing from it is used",
902 parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
905 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
906 warnUnusedImports names
907 = doptRn Opt_WarnUnusedImports `thenRn` \ warn ->
908 if warn then warnUnusedBinds names else returnRn ()
910 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
911 warnUnusedLocalBinds names
912 = doptRn Opt_WarnUnusedBinds `thenRn` \ warn ->
913 if warn then warnUnusedBinds [(n,LocalDef) | n<-names]
916 warnUnusedMatches names
917 = doptRn Opt_WarnUnusedMatches `thenRn` \ warn ->
918 if warn then warnUnusedGroup [(n,LocalDef) | n<-names]
921 -------------------------
923 warnUnusedBinds :: [(Name,Provenance)] -> RnM d ()
924 warnUnusedBinds names
925 = mapRn_ warnUnusedGroup groups
927 -- Group by provenance
928 groups = equivClasses cmp names
929 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
932 -------------------------
934 warnUnusedGroup :: [(Name,Provenance)] -> RnM d ()
935 warnUnusedGroup names
936 | null filtered_names = returnRn ()
937 | not is_local = returnRn ()
939 = pushSrcLocRn def_loc $
941 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
943 filtered_names = filter reportable names
944 (name1, prov1) = head filtered_names
945 (is_local, def_loc, msg)
947 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
949 NonLocalDef (UserImport mod loc _)
950 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
952 reportable (name,_) = case occNameUserString (nameOccName name) of
955 -- Haskell 98 encourages compilers to suppress warnings about
956 -- unused names in a pattern if they start with "_".
960 addNameClashErrRn rdr_name (np1:nps)
961 = addErrRn (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
962 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
964 msg1 = ptext SLIT("either") <+> mk_ref np1
965 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
966 mk_ref (GRE name prov _) = quotes (ppr name) <> comma <+> pprNameProvenance name prov
968 shadowedNameWarn shadow
969 = hsep [ptext SLIT("This binding for"),
971 ptext SLIT("shadows an existing binding")]
974 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
976 flavour = occNameFlavour (rdrNameOcc name)
978 qualNameErr descriptor (name,loc)
980 addErrRn (hsep [ ptext SLIT("Invalid use of qualified name"),
985 dupNamesErr descriptor ((name,loc) : dup_things)
987 addErrRn ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
989 (ptext SLIT("in") <+> descriptor))
991 warnDeprec :: Name -> DeprecTxt -> RnM d ()
993 = doptRn Opt_WarnDeprecations `thenRn` \ warn_drs ->
994 if not warn_drs then returnRn () else
995 addWarnRn (sep [ text (occNameFlavour (nameOccName name)) <+>
996 quotes (ppr name) <+> text "is deprecated:",