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
14 import RdrHsSyn ( RdrNameIE )
15 import RnHsSyn ( RenamedTyClDecl )
16 import RdrName ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
17 mkRdrUnqual, mkRdrQual, lookupRdrEnv, foldRdrEnv
19 import HsTypes ( hsTyVarName, replaceTyVarName )
20 import HscTypes ( Provenance(..), pprNameProvenance, hasBetterProv,
21 ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), AvailEnv,
22 AvailInfo, Avails, GenAvailInfo(..), NameSupply(..),
24 Deprecations(..), lookupDeprec,
29 getSrcLoc, nameIsLocalOrFrom,
30 mkLocalName, mkGlobalName,
31 mkIPName, nameOccName, nameModule_maybe,
36 import OccName ( OccName, occNameUserString, occNameFlavour )
37 import Module ( ModuleName, moduleName, mkVanillaModule,
38 mkSysModuleNameFS, moduleNameFS, WhereFrom(..) )
39 import PrelNames ( mkUnboundName, syntaxList, SyntaxMap, vanillaSyntaxMap,
41 mAIN_Name, pREL_MAIN_Name,
42 ioTyConName, integerTyConName, doubleTyConName, intTyConName,
43 boolTyConName, funTyConName,
44 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
45 eqStringName, printName,
46 hasKey, fractionalClassKey, numClassKey,
47 bindIOName, returnIOName, failIOName
49 import TysWiredIn ( unitTyCon ) -- A little odd
52 import SrcLoc ( SrcLoc, noSrcLoc )
54 import ListSetOps ( removeDups, equivClasses )
55 import Util ( sortLt )
57 import UniqFM ( lookupWithDefaultUFM )
58 import Maybes ( orElse )
60 import FastString ( FastString )
63 %*********************************************************
65 \subsection{Making new names}
67 %*********************************************************
70 newTopBinder :: Module -> RdrName -> SrcLoc -> RnM d Name
71 -- newTopBinder puts into the cache the binder with the
72 -- module information set correctly. When the decl is later renamed,
73 -- the binding site will thereby get the correct module.
74 -- There maybe occurrences that don't have the correct Module, but
75 -- by the typechecker will propagate the binding definition to all
76 -- the occurrences, so that doesn't matter
78 newTopBinder mod rdr_name loc
79 = -- First check the cache
81 -- There should never be a qualified name in a binding position (except in instance decls)
82 -- The parser doesn't check this because the same parser parses instance decls
83 (if isQual rdr_name then
84 qualNameErr (text "its declaration") (rdr_name,loc)
89 getNameSupplyRn `thenRn` \ name_supply ->
91 occ = rdrNameOcc rdr_name
92 key = (moduleName mod, occ)
93 cache = nsNames name_supply
95 case lookupFM cache key of
97 -- A hit in the cache! We are at the binding site of the name, and
98 -- this is the moment when we know all about
99 -- a) the Name's host Module (in particular, which
100 -- package it comes from)
101 -- b) its defining SrcLoc
102 -- So we update this info
105 new_name = setNameModuleAndLoc name mod loc
106 new_cache = addToFM cache key new_name
108 setNameSupplyRn (name_supply {nsNames = new_cache}) `thenRn_`
109 -- traceRn (text "newTopBinder: overwrite" <+> ppr new_name) `thenRn_`
112 -- Miss in the cache!
113 -- Build a completely new Name, and put it in the cache
114 -- Even for locally-defined names we use implicitImportProvenance;
115 -- updateProvenances will set it to rights
117 (us', us1) = splitUniqSupply (nsUniqs name_supply)
118 uniq = uniqFromSupply us1
119 new_name = mkGlobalName uniq mod occ loc
120 new_cache = addToFM cache key new_name
122 setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
123 -- traceRn (text "newTopBinder: new" <+> ppr new_name) `thenRn_`
127 newGlobalName :: ModuleName -> OccName -> RnM d Name
128 -- Used for *occurrences*. We make a place-holder Name, really just
129 -- to agree on its unique, which gets overwritten when we read in
130 -- the binding occurence later (newTopBinder)
131 -- The place-holder Name doesn't have the right SrcLoc, and its
132 -- Module won't have the right Package either.
134 -- (We have to pass a ModuleName, not a Module, because we may be
135 -- simply looking at an occurrence M.x in an interface file.)
137 -- This means that a renamed program may have incorrect info
138 -- on implicitly-imported occurrences, but the correct info on the
139 -- *binding* declaration. It's the type checker that propagates the
140 -- correct information to all the occurrences.
141 -- Since implicitly-imported names never occur in error messages,
142 -- it doesn't matter that we get the correct info in place till later,
143 -- (but since it affects DLL-ery it does matter that we get it right
145 newGlobalName mod_name occ
146 = getNameSupplyRn `thenRn` \ name_supply ->
148 key = (mod_name, occ)
149 cache = nsNames name_supply
151 case lookupFM cache key of
152 Just name -> -- traceRn (text "newGlobalName: hit" <+> ppr name) `thenRn_`
155 Nothing -> setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
156 -- traceRn (text "newGlobalName: new" <+> ppr name) `thenRn_`
159 (us', us1) = splitUniqSupply (nsUniqs name_supply)
160 uniq = uniqFromSupply us1
161 mod = mkVanillaModule mod_name
162 name = mkGlobalName uniq mod occ noSrcLoc
163 new_cache = addToFM cache key name
166 = getNameSupplyRn `thenRn` \ name_supply ->
168 ipcache = nsIPs name_supply
170 case lookupFM ipcache key of
171 Just name -> returnRn name
172 Nothing -> setNameSupplyRn (name_supply {nsUniqs = us', nsIPs = new_ipcache}) `thenRn_`
175 (us', us1) = splitUniqSupply (nsUniqs name_supply)
176 uniq = uniqFromSupply us1
177 name = mkIPName uniq key
178 new_ipcache = addToFM ipcache key name
179 where key = (rdrNameOcc rdr_name)
182 %*********************************************************
184 \subsection{Looking up names}
186 %*********************************************************
188 Looking up a name in the RnEnv.
191 lookupBndrRn rdr_name
192 = getLocalNameEnv `thenRn` \ local_env ->
193 case lookupRdrEnv local_env rdr_name of
194 Just name -> returnRn name
195 Nothing -> lookupTopBndrRn rdr_name
197 lookupTopBndrRn rdr_name
198 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
199 -- and there may be several imported 'f's too, which must not confuse us.
200 -- So we have to filter out the non-local ones.
201 -- A separate function (importsFromLocalDecls) reports duplicate top level
202 -- decls, so here it's safe just to choose an arbitrary one.
205 -- This is here just to catch the PrelBase defn of (say) [] and similar
206 -- The parser reads the special syntax and returns an Orig RdrName
207 -- But the global_env contains only Qual RdrNames, so we won't
208 -- find it there; instead just get the name via the Orig route
209 = lookupOrigName rdr_name
212 = getModeRn `thenRn` \ mode ->
213 if isInterfaceMode mode
214 then lookupIfaceName rdr_name
216 getModuleRn `thenRn` \ mod ->
217 getGlobalNameEnv `thenRn` \ global_env ->
218 case lookup_local mod global_env rdr_name of
219 Just name -> returnRn name
220 Nothing -> failWithRn (mkUnboundName rdr_name)
221 (unknownNameErr rdr_name)
223 lookup_local mod global_env rdr_name
224 = case lookupRdrEnv global_env rdr_name of
226 Just gres -> case [n | GRE n _ _ <- gres, nameIsLocalOrFrom mod n] of
231 -- lookupSigOccRn is used for type signatures and pragmas
237 -- It's clear that the 'f' in the signature must refer to A.f
238 -- The Haskell98 report does not stipulate this, but it will!
239 -- So we must treat the 'f' in the signature in the same way
240 -- as the binding occurrence of 'f', using lookupBndrRn
241 lookupSigOccRn :: RdrName -> RnMS Name
242 lookupSigOccRn = lookupBndrRn
244 -- lookupOccRn looks up an occurrence of a RdrName
245 lookupOccRn :: RdrName -> RnMS Name
247 = getLocalNameEnv `thenRn` \ local_env ->
248 case lookupRdrEnv local_env rdr_name of
249 Just name -> returnRn name
250 Nothing -> lookupGlobalOccRn rdr_name
252 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
253 -- environment. It's used only for
254 -- record field names
255 -- class op names in class and instance decls
257 lookupGlobalOccRn rdr_name
258 = getModeRn `thenRn` \ mode ->
259 if (isInterfaceMode mode)
260 then lookupIfaceName rdr_name
263 getGlobalNameEnv `thenRn` \ global_env ->
265 SourceMode -> lookupSrcName global_env rdr_name
268 | not (isQual rdr_name) ->
269 lookupSrcName global_env rdr_name
271 -- We allow qualified names on the command line to refer to
272 -- *any* name exported by any module in scope, just as if
273 -- there was an "import qualified M" declaration for every
276 -- First look up the name in the normal environment. If
277 -- it isn't there, we manufacture a new occurrence of an
280 case lookupRdrEnv global_env rdr_name of
281 Just _ -> lookupSrcName global_env rdr_name
282 Nothing -> lookupQualifiedName rdr_name
284 -- a qualified name on the command line can refer to any module at all: we
285 -- try to load the interface if we don't already have it.
286 lookupQualifiedName :: RdrName -> RnM d Name
287 lookupQualifiedName rdr_name
289 mod = rdrNameModule rdr_name
290 occ = rdrNameOcc rdr_name
292 loadInterface (ppr rdr_name) mod ImportBySystem `thenRn` \ iface ->
293 case [ name | (_,avails) <- mi_exports iface,
295 name <- availNames avail,
296 nameOccName name == occ ] of
297 (n:ns) -> ASSERT (null ns) returnRn n
298 _ -> failWithRn (mkUnboundName rdr_name) (unknownNameErr rdr_name)
300 lookupSrcName :: GlobalRdrEnv -> RdrName -> RnM d Name
301 -- NB: passed GlobalEnv explicitly, not necessarily in RnMS monad
302 lookupSrcName global_env rdr_name
303 | isOrig rdr_name -- Can occur in source code too
304 = lookupOrigName rdr_name
307 = case lookupRdrEnv global_env rdr_name of
308 Just [GRE name _ Nothing] -> returnRn name
309 Just [GRE name _ (Just deprec)] -> warnDeprec name deprec `thenRn_`
311 Just stuff@(GRE name _ _ : _) -> addNameClashErrRn rdr_name stuff `thenRn_`
313 Nothing -> failWithRn (mkUnboundName rdr_name)
314 (unknownNameErr rdr_name)
316 lookupOrigName :: RdrName -> RnM d Name
317 lookupOrigName rdr_name
318 = ASSERT( isOrig rdr_name )
319 newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
321 lookupIfaceUnqual :: RdrName -> RnM d Name
322 lookupIfaceUnqual rdr_name
323 = ASSERT( isUnqual rdr_name )
324 -- An Unqual is allowed; interface files contain
325 -- unqualified names for locally-defined things, such as
326 -- constructors of a data type.
327 getModuleRn `thenRn ` \ mod ->
328 newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
330 lookupIfaceName :: RdrName -> RnM d Name
331 lookupIfaceName rdr_name
332 | isUnqual rdr_name = lookupIfaceUnqual rdr_name
333 | otherwise = lookupOrigName rdr_name
336 @lookupOrigName@ takes an RdrName representing an {\em original}
337 name, and adds it to the occurrence pool so that it'll be loaded
338 later. This is used when language constructs (such as monad
339 comprehensions, overloaded literals, or deriving clauses) require some
340 stuff to be loaded that isn't explicitly mentioned in the code.
342 This doesn't apply in interface mode, where everything is explicit,
343 but we don't check for this case: it does no harm to record an
344 ``extra'' occurrence and @lookupOrigNames@ isn't used much in
345 interface mode (it's only the @Nothing@ clause of @rnDerivs@ that
346 calls it at all I think).
348 \fbox{{\em Jan 98: this comment is wrong: @rnHsType@ uses it quite a bit.}}
351 lookupOrigNames :: [RdrName] -> RnM d NameSet
352 lookupOrigNames rdr_names
353 = mapRn lookupOrigName rdr_names `thenRn` \ names ->
354 returnRn (mkNameSet names)
357 lookupSysBinder is used for the "system binders" of a type, class, or
358 instance decl. It ensures that the module is set correctly in the
359 name cache, and sets the provenance on the returned name too. The
360 returned name will end up actually in the type, class, or instance.
363 lookupSysBinder rdr_name
364 = ASSERT( isUnqual rdr_name )
365 getModuleRn `thenRn` \ mod ->
366 getSrcLocRn `thenRn` \ loc ->
367 newTopBinder mod rdr_name loc
371 %*********************************************************
373 \subsection{Implicit free vars and sugar names}
375 %*********************************************************
377 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
378 mentioned explicitly, but which might be needed by the type checker.
381 getImplicitStmtFVs -- Compiling a statement
382 = returnRn (mkFVs [printName, bindIOName, returnIOName, failIOName]
383 `plusFV` ubiquitousNames)
384 -- These are all needed implicitly when compiling a statement
385 -- See TcModule.tc_stmts
387 getImplicitModuleFVs mod_name decls -- Compiling a module
388 = lookupOrigNames deriv_occs `thenRn` \ deriving_names ->
389 returnRn (deriving_names `plusFV` implicit_main `plusFV` ubiquitousNames)
391 -- Add occurrences for IO or PrimIO
392 implicit_main | mod_name == mAIN_Name
393 || mod_name == pREL_MAIN_Name = unitFV ioTyConName
394 | otherwise = emptyFVs
396 deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
397 cls <- deriv_classes,
398 occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
400 -- ubiquitous_names are loaded regardless, because
401 -- they are needed in virtually every program
403 = mkFVs [unpackCStringName, unpackCStringFoldrName,
404 unpackCStringUtf8Name, eqStringName]
405 -- Virtually every program has error messages in it somewhere
408 mkFVs [getName unitTyCon, funTyConName, boolTyConName, intTyConName]
409 -- Add occurrences for very frequently used types.
410 -- (e.g. we don't want to be bothered with making funTyCon a
411 -- free var at every function application!)
415 rnSyntaxNames :: GlobalRdrEnv -> FreeVars -> RnMG (FreeVars, SyntaxMap)
416 -- Look up the re-bindable syntactic sugar names
417 -- Any errors arising from these lookups may surprise the
418 -- programmer, since they aren't explicitly mentioned, and
419 -- the src line will be unhelpful (ToDo)
421 rnSyntaxNames gbl_env source_fvs
422 = doptRn Opt_NoImplicitPrelude `thenRn` \ no_prelude ->
423 if not no_prelude then
424 returnRn (source_fvs, vanillaSyntaxMap)
427 -- There's a -fno-implicit-prelude flag,
428 -- so build the re-mapping function
430 reqd_syntax_list = filter is_reqd syntaxList
431 is_reqd (n,_) = n `elemNameSet` source_fvs
432 lookup (n,rn) = lookupSrcName gbl_env rn `thenRn` \ rn' ->
435 mapRn lookup reqd_syntax_list `thenRn` \ rn_syntax_list ->
437 -- Delete the proxies and add the actuals
438 proxies = map fst rn_syntax_list
439 actuals = map snd rn_syntax_list
440 new_source_fvs = (proxies `delFVs` source_fvs) `plusFV` mkFVs actuals
442 syntax_env = mkNameEnv rn_syntax_list
443 syntax_map n = lookupNameEnv syntax_env n `orElse` n
445 returnRn (new_source_fvs, syntax_map)
449 %*********************************************************
453 %*********************************************************
456 newLocalsRn :: [(RdrName,SrcLoc)]
458 newLocalsRn rdr_names_w_loc
459 = getNameSupplyRn `thenRn` \ name_supply ->
461 n = length rdr_names_w_loc
462 (us', us1) = splitUniqSupply (nsUniqs name_supply)
463 uniqs = uniqsFromSupply n us1
464 names = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
465 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
468 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
472 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
473 -> [(RdrName,SrcLoc)]
474 -> ([Name] -> RnMS a)
476 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
477 = getModeRn `thenRn` \ mode ->
478 getLocalNameEnv `thenRn` \ name_env ->
480 -- Check for duplicate names
481 checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
483 -- Warn about shadowing, but only in source modules
485 SourceMode -> ifOptRn Opt_WarnNameShadowing $
486 mapRn_ (check_shadow name_env) rdr_names_w_loc
490 newLocalsRn rdr_names_w_loc `thenRn` \ names ->
492 new_local_env = addListToRdrEnv name_env (map fst rdr_names_w_loc `zip` names)
494 setLocalNameEnv new_local_env (enclosed_scope names)
497 check_shadow name_env (rdr_name,loc)
498 = case lookupRdrEnv name_env rdr_name of
499 Nothing -> returnRn ()
500 Just name -> pushSrcLocRn loc $
501 addWarnRn (shadowedNameWarn rdr_name)
503 bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
504 -- A specialised variant when renaming stuff from interface
505 -- files (of which there is a lot)
507 -- * no checks for shadowing
509 -- * deal with free vars
510 bindCoreLocalRn rdr_name enclosed_scope
511 = getSrcLocRn `thenRn` \ loc ->
512 getLocalNameEnv `thenRn` \ name_env ->
513 getNameSupplyRn `thenRn` \ name_supply ->
515 (us', us1) = splitUniqSupply (nsUniqs name_supply)
516 uniq = uniqFromSupply us1
517 name = mkLocalName uniq (rdrNameOcc rdr_name) loc
519 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
521 new_name_env = extendRdrEnv name_env rdr_name name
523 setLocalNameEnv new_name_env (enclosed_scope name)
525 bindCoreLocalsRn [] thing_inside = thing_inside []
526 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
527 bindCoreLocalsRn bs $ \ names' ->
528 thing_inside (name':names')
530 bindLocalNames names enclosed_scope
531 = getLocalNameEnv `thenRn` \ name_env ->
532 setLocalNameEnv (extendLocalRdrEnv name_env names)
535 bindLocalNamesFV names enclosed_scope
536 = bindLocalNames names $
537 enclosed_scope `thenRn` \ (thing, fvs) ->
538 returnRn (thing, delListFromNameSet fvs names)
541 -------------------------------------
542 bindLocalRn doc rdr_name enclosed_scope
543 = getSrcLocRn `thenRn` \ loc ->
544 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
548 bindLocalsRn doc rdr_names enclosed_scope
549 = getSrcLocRn `thenRn` \ loc ->
550 bindLocatedLocalsRn doc
551 (rdr_names `zip` repeat loc)
554 -- binLocalsFVRn is the same as bindLocalsRn
555 -- except that it deals with free vars
556 bindLocalsFVRn doc rdr_names enclosed_scope
557 = bindLocalsRn doc rdr_names $ \ names ->
558 enclosed_scope names `thenRn` \ (thing, fvs) ->
559 returnRn (thing, delListFromNameSet fvs names)
561 -------------------------------------
562 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
563 -- This tiresome function is used only in rnSourceDecl on InstDecl
564 extendTyVarEnvFVRn tyvars enclosed_scope
565 = bindLocalNames tyvars enclosed_scope `thenRn` \ (thing, fvs) ->
566 returnRn (thing, delListFromNameSet fvs tyvars)
568 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
569 -> ([HsTyVarBndr Name] -> RnMS a)
571 bindTyVarsRn doc_str tyvar_names enclosed_scope
572 = bindTyVars2Rn doc_str tyvar_names $ \ names tyvars ->
573 enclosed_scope tyvars
575 -- Gruesome name: return Names as well as HsTyVars
576 bindTyVars2Rn :: SDoc -> [HsTyVarBndr RdrName]
577 -> ([Name] -> [HsTyVarBndr Name] -> RnMS a)
579 bindTyVars2Rn doc_str tyvar_names enclosed_scope
580 = getSrcLocRn `thenRn` \ loc ->
582 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
584 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
585 enclosed_scope names (zipWith replaceTyVarName tyvar_names names)
587 bindTyVarsFVRn :: SDoc -> [HsTyVarBndr RdrName]
588 -> ([HsTyVarBndr Name] -> RnMS (a, FreeVars))
589 -> RnMS (a, FreeVars)
590 bindTyVarsFVRn doc_str rdr_names enclosed_scope
591 = bindTyVars2Rn doc_str rdr_names $ \ names tyvars ->
592 enclosed_scope tyvars `thenRn` \ (thing, fvs) ->
593 returnRn (thing, delListFromNameSet fvs names)
595 bindTyVarsFV2Rn :: SDoc -> [HsTyVarBndr RdrName]
596 -> ([Name] -> [HsTyVarBndr Name] -> RnMS (a, FreeVars))
597 -> RnMS (a, FreeVars)
598 bindTyVarsFV2Rn doc_str rdr_names enclosed_scope
599 = bindTyVars2Rn doc_str rdr_names $ \ names tyvars ->
600 enclosed_scope names tyvars `thenRn` \ (thing, fvs) ->
601 returnRn (thing, delListFromNameSet fvs names)
603 bindNakedTyVarsFVRn :: SDoc -> [RdrName]
604 -> ([Name] -> RnMS (a, FreeVars))
605 -> RnMS (a, FreeVars)
606 bindNakedTyVarsFVRn doc_str tyvar_names enclosed_scope
607 = getSrcLocRn `thenRn` \ loc ->
609 located_tyvars = [(tv, loc) | tv <- tyvar_names]
611 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
612 enclosed_scope names `thenRn` \ (thing, fvs) ->
613 returnRn (thing, delListFromNameSet fvs names)
616 -------------------------------------
617 checkDupOrQualNames, checkDupNames :: SDoc
618 -> [(RdrName, SrcLoc)]
620 -- Works in any variant of the renamer monad
622 checkDupOrQualNames doc_str rdr_names_w_loc
623 = -- Check for use of qualified names
624 mapRn_ (qualNameErr doc_str) quals `thenRn_`
625 checkDupNames doc_str rdr_names_w_loc
627 quals = filter (isQual . fst) rdr_names_w_loc
629 checkDupNames doc_str rdr_names_w_loc
630 = -- Check for duplicated names in a binding group
631 mapRn_ (dupNamesErr doc_str) dups
633 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
637 %************************************************************************
639 \subsection{GlobalRdrEnv}
641 %************************************************************************
644 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
645 -> Bool -- True <=> want unqualified import
646 -> Bool -- True <=> want qualified import
647 -> [AvailInfo] -- What's to be hidden (but only the unqualified
648 -- version is hidden)
649 -> (Name -> Provenance)
650 -> Avails -- Whats imported and how
654 mkGlobalRdrEnv this_mod unqual_imp qual_imp hides
655 mk_provenance avails deprecs
658 -- Make the name environment. We're talking about a
659 -- single module here, so there must be no name clashes.
660 -- In practice there only ever will be if it's the module
663 -- Add the things that are available
664 gbl_env1 = foldl add_avail emptyRdrEnv avails
666 -- Delete things that are hidden
667 gbl_env2 = foldl del_avail gbl_env1 hides
669 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
670 add_avail env avail = foldl add_name env (availNames avail)
673 | qual_imp && unqual_imp = env3
678 env1 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
679 env2 = addOneToGlobalRdrEnv env (mkRdrUnqual occ) elt
680 env3 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) elt
681 occ = nameOccName name
682 elt = GRE name (mk_provenance name) (lookupDeprec deprecs name)
684 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
686 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
688 mkIfaceGlobalRdrEnv :: [(ModuleName,Avails)] -> GlobalRdrEnv
689 -- Used to construct a GlobalRdrEnv for an interface that we've
690 -- read from a .hi file. We can't construct the original top-level
691 -- environment because we don't have enough info, but we compromise
692 -- by making an environment from its exports
693 mkIfaceGlobalRdrEnv m_avails
694 = foldl add emptyRdrEnv m_avails
696 add env (mod,avails) = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True False []
697 (\n -> LocalDef) avails NoDeprecs)
698 -- The NoDeprecs is a bit of a hack I suppose
702 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
703 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
705 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
706 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
708 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
709 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
711 combine_globals :: [GlobalRdrElt] -- Old
712 -> [GlobalRdrElt] -- New
714 combine_globals ns_old ns_new -- ns_new is often short
715 = foldr add ns_old ns_new
717 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
720 choose n m | n `beats` m = n
723 (GRE n pn _) `beats` (GRE m pm _) = n==m && pn `hasBetterProv` pm
725 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
726 is_duplicate (GRE n1 LocalDef _) (GRE n2 LocalDef _) = False
727 is_duplicate (GRE n1 _ _) (GRE n2 _ _) = n1 == n2
730 We treat two bindings of a locally-defined name as a duplicate,
731 because they might be two separate, local defns and we want to report
732 and error for that, {\em not} eliminate a duplicate.
734 On the other hand, if you import the same name from two different
735 import statements, we {\em do} want to eliminate the duplicate, not report
738 If a module imports itself then there might be a local defn and an imported
739 defn of the same name; in this case the names will compare as equal, but
740 will still have different provenances.
743 @unQualInScope@ returns a function that takes a @Name@ and tells whether
744 its unqualified name is in scope. This is put as a boolean flag in
745 the @Name@'s provenance to guide whether or not to print the name qualified
749 unQualInScope :: GlobalRdrEnv -> Name -> Bool
750 -- True if 'f' is in scope, and has only one binding
751 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
753 = (`elemNameSet` unqual_names)
755 unqual_names :: NameSet
756 unqual_names = foldRdrEnv add emptyNameSet env
757 add rdr_name [GRE name _ _] unquals | isUnqual rdr_name = addOneToNameSet unquals name
758 add _ _ unquals = unquals
762 %************************************************************************
766 %************************************************************************
769 plusAvail (Avail n1) (Avail n2) = Avail n1
770 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
773 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
776 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
777 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
779 emptyAvailEnv = emptyNameEnv
780 unitAvailEnv :: AvailInfo -> AvailEnv
781 unitAvailEnv a = unitNameEnv (availName a) a
783 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
784 plusAvailEnv = plusNameEnv_C plusAvail
786 availEnvElts = nameEnvElts
788 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
789 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
791 availsToNameSet :: [AvailInfo] -> NameSet
792 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
794 availName :: GenAvailInfo name -> name
795 availName (Avail n) = n
796 availName (AvailTC n _) = n
798 availNames :: GenAvailInfo name -> [name]
799 availNames (Avail n) = [n]
800 availNames (AvailTC n ns) = ns
802 -------------------------------------
803 filterAvail :: RdrNameIE -- Wanted
804 -> AvailInfo -- Available
805 -> Maybe AvailInfo -- Resulting available;
806 -- Nothing if (any of the) wanted stuff isn't there
808 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
809 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
810 | otherwise = Nothing
812 is_wanted name = nameOccName name `elem` wanted_occs
813 sub_names_ok = all (`elem` avail_occs) wanted_occs
814 avail_occs = map nameOccName ns
815 wanted_occs = map rdrNameOcc (want:wants)
817 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
820 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
822 filterAvail (IEVar _) avail@(Avail n) = Just avail
823 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
825 wanted n = nameOccName n == occ
827 -- The second equation happens if we import a class op, thus
829 -- where op is a class operation
831 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
832 -- We don't complain even if the IE says T(..), but
833 -- no constrs/class ops of T are available
834 -- Instead that's caught with a warning by the caller
836 filterAvail ie avail = Nothing
838 -------------------------------------
839 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
840 -- Group by module and sort by occurrence
841 -- This keeps the list in canonical order
842 groupAvails this_mod avails
843 = [ (mkSysModuleNameFS fs, sortLt lt avails)
844 | (fs,avails) <- fmToList groupFM
847 groupFM :: FiniteMap FastString Avails
848 -- Deliberately use the FastString so we
849 -- get a canonical ordering
850 groupFM = foldl add emptyFM avails
852 add env avail = addToFM_C combine env mod_fs [avail']
854 mod_fs = moduleNameFS (moduleName avail_mod)
855 avail_mod = case nameModule_maybe (availName avail) of
858 combine old _ = avail':old
859 avail' = sortAvail avail
861 a1 `lt` a2 = occ1 < occ2
863 occ1 = nameOccName (availName a1)
864 occ2 = nameOccName (availName a2)
866 sortAvail :: AvailInfo -> AvailInfo
867 -- Sort the sub-names into canonical order.
868 -- The canonical order has the "main name" at the beginning
869 -- (if it's there at all)
870 sortAvail (Avail n) = Avail n
871 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
872 | otherwise = AvailTC n ( sortLt lt ns)
874 n1 `lt` n2 = nameOccName n1 < nameOccName n2
878 %************************************************************************
880 \subsection{Free variable manipulation}
882 %************************************************************************
886 mapFvRn f xs = mapRn f xs `thenRn` \ stuff ->
888 (ys, fvs_s) = unzip stuff
890 returnRn (ys, plusFVs fvs_s)
894 %************************************************************************
896 \subsection{Envt utility functions}
898 %************************************************************************
901 warnUnusedModules :: [ModuleName] -> RnM d ()
902 warnUnusedModules mods
903 = ifOptRn Opt_WarnUnusedImports (mapRn_ (addWarnRn . unused_mod) mods)
905 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
906 text "is imported, but nothing from it is used",
907 parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
910 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
911 warnUnusedImports names
912 = ifOptRn Opt_WarnUnusedImports (warnUnusedBinds names)
914 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
915 warnUnusedLocalBinds names
916 = ifOptRn Opt_WarnUnusedBinds (warnUnusedBinds [(n,LocalDef) | n<-names])
918 warnUnusedMatches names
919 = ifOptRn Opt_WarnUnusedMatches (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 = ifOptRn Opt_WarnDeprecations $
994 addWarnRn (sep [ text (occNameFlavour (nameOccName name)) <+>
995 quotes (ppr name) <+> text "is deprecated:",