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, RdrNameHsType, extractHsTyRdrTyVars )
15 import RdrName ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
16 mkRdrUnqual, mkRdrQual,
17 lookupRdrEnv, foldRdrEnv, rdrEnvToList, elemRdrEnv,
20 import HsTypes ( hsTyVarName, replaceTyVarName )
21 import HscTypes ( Provenance(..), pprNameProvenance, hasBetterProv,
22 ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), AvailEnv,
23 AvailInfo, Avails, GenAvailInfo(..), NameSupply(..),
25 Deprecations(..), lookupDeprec,
28 import Type ( mapIPName )
31 getSrcLoc, nameIsLocalOrFrom,
32 mkLocalName, mkGlobalName,
33 mkIPName, nameOccName, nameModule_maybe,
38 import OccName ( OccName, occNameUserString, occNameFlavour )
39 import Module ( ModuleName, moduleName, mkVanillaModule,
40 mkSysModuleNameFS, moduleNameFS, WhereFrom(..) )
41 import PrelNames ( mkUnboundName,
43 mAIN_Name, pREL_MAIN_Name,
44 ioTyConName, intTyConName,
45 boolTyConName, funTyConName,
46 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
47 eqStringName, printName,
48 bindIOName, returnIOName, failIOName
50 import TysWiredIn ( unitTyCon ) -- A little odd
53 import SrcLoc ( SrcLoc, noSrcLoc )
55 import ListSetOps ( removeDups, equivClasses )
56 import Util ( sortLt )
58 import UniqFM ( lookupWithDefaultUFM )
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 "In 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
165 newIPName rdr_name_ip
166 = getNameSupplyRn `thenRn` \ name_supply ->
168 ipcache = nsIPs name_supply
170 case lookupFM ipcache key of
171 Just name_ip -> returnRn name_ip
172 Nothing -> setNameSupplyRn new_ns `thenRn_`
175 (us', us1) = splitUniqSupply (nsUniqs name_supply)
176 uniq = uniqFromSupply us1
177 name_ip = mapIPName mk_name rdr_name_ip
178 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
179 new_ipcache = addToFM ipcache key name_ip
180 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
182 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
185 %*********************************************************
187 \subsection{Looking up names}
189 %*********************************************************
191 Looking up a name in the RnEnv.
194 lookupBndrRn rdr_name
195 = getLocalNameEnv `thenRn` \ local_env ->
196 case lookupRdrEnv local_env rdr_name of
197 Just name -> returnRn name
198 Nothing -> lookupTopBndrRn rdr_name
200 lookupTopBndrRn rdr_name
201 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
202 -- and there may be several imported 'f's too, which must not confuse us.
203 -- So we have to filter out the non-local ones.
204 -- A separate function (importsFromLocalDecls) reports duplicate top level
205 -- decls, so here it's safe just to choose an arbitrary one.
208 -- This is here just to catch the PrelBase defn of (say) [] and similar
209 -- The parser reads the special syntax and returns an Orig RdrName
210 -- But the global_env contains only Qual RdrNames, so we won't
211 -- find it there; instead just get the name via the Orig route
212 = lookupOrigName rdr_name
215 = getModeRn `thenRn` \ mode ->
216 if isInterfaceMode mode
217 then lookupIfaceName rdr_name
219 getModuleRn `thenRn` \ mod ->
220 getGlobalNameEnv `thenRn` \ global_env ->
221 case lookup_local mod global_env rdr_name of
222 Just name -> returnRn name
223 Nothing -> failWithRn (mkUnboundName rdr_name)
224 (unknownNameErr rdr_name)
226 lookup_local mod global_env rdr_name
227 = case lookupRdrEnv global_env rdr_name of
229 Just gres -> case [n | GRE n _ _ <- gres, nameIsLocalOrFrom mod n] of
234 -- lookupSigOccRn is used for type signatures and pragmas
240 -- It's clear that the 'f' in the signature must refer to A.f
241 -- The Haskell98 report does not stipulate this, but it will!
242 -- So we must treat the 'f' in the signature in the same way
243 -- as the binding occurrence of 'f', using lookupBndrRn
244 lookupSigOccRn :: RdrName -> RnMS Name
245 lookupSigOccRn = lookupBndrRn
247 -- lookupOccRn looks up an occurrence of a RdrName
248 lookupOccRn :: RdrName -> RnMS Name
250 = getLocalNameEnv `thenRn` \ local_env ->
251 case lookupRdrEnv local_env rdr_name of
252 Just name -> returnRn name
253 Nothing -> lookupGlobalOccRn rdr_name
255 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
256 -- environment. It's used only for
257 -- record field names
258 -- class op names in class and instance decls
260 lookupGlobalOccRn rdr_name
261 = getModeRn `thenRn` \ mode ->
262 if (isInterfaceMode mode)
263 then lookupIfaceName rdr_name
266 getGlobalNameEnv `thenRn` \ global_env ->
268 SourceMode -> lookupSrcName global_env rdr_name
271 | not (isQual rdr_name) ->
272 lookupSrcName global_env rdr_name
274 -- We allow qualified names on the command line to refer to
275 -- *any* name exported by any module in scope, just as if
276 -- there was an "import qualified M" declaration for every
279 -- First look up the name in the normal environment. If
280 -- it isn't there, we manufacture a new occurrence of an
283 case lookupRdrEnv global_env rdr_name of
284 Just _ -> lookupSrcName global_env rdr_name
285 Nothing -> lookupQualifiedName rdr_name
287 -- a qualified name on the command line can refer to any module at all: we
288 -- try to load the interface if we don't already have it.
289 lookupQualifiedName :: RdrName -> RnM d Name
290 lookupQualifiedName rdr_name
292 mod = rdrNameModule rdr_name
293 occ = rdrNameOcc rdr_name
295 loadInterface (ppr rdr_name) mod ImportByUser `thenRn` \ iface ->
296 case [ name | (_,avails) <- mi_exports iface,
298 name <- availNames avail,
299 nameOccName name == occ ] of
300 (n:ns) -> ASSERT (null ns) returnRn n
301 _ -> failWithRn (mkUnboundName rdr_name) (unknownNameErr rdr_name)
303 lookupSrcName :: GlobalRdrEnv -> RdrName -> RnM d Name
304 -- NB: passed GlobalEnv explicitly, not necessarily in RnMS monad
305 lookupSrcName global_env rdr_name
306 | isOrig rdr_name -- Can occur in source code too
307 = lookupOrigName rdr_name
310 = case lookupRdrEnv global_env rdr_name of
311 Just [GRE name _ Nothing] -> returnRn name
312 Just [GRE name _ (Just deprec)] -> warnDeprec name deprec `thenRn_`
314 Just stuff@(GRE name _ _ : _) -> addNameClashErrRn rdr_name stuff `thenRn_`
316 Nothing -> failWithRn (mkUnboundName rdr_name)
317 (unknownNameErr rdr_name)
319 lookupOrigName :: RdrName -> RnM d Name
320 lookupOrigName rdr_name
321 = ASSERT( isOrig rdr_name )
322 newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
324 lookupIfaceUnqual :: RdrName -> RnM d Name
325 lookupIfaceUnqual rdr_name
326 = ASSERT( isUnqual rdr_name )
327 -- An Unqual is allowed; interface files contain
328 -- unqualified names for locally-defined things, such as
329 -- constructors of a data type.
330 getModuleRn `thenRn ` \ mod ->
331 newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
333 lookupIfaceName :: RdrName -> RnM d Name
334 lookupIfaceName rdr_name
335 | isUnqual rdr_name = lookupIfaceUnqual rdr_name
336 | otherwise = lookupOrigName rdr_name
339 @lookupOrigName@ takes an RdrName representing an {\em original}
340 name, and adds it to the occurrence pool so that it'll be loaded
341 later. This is used when language constructs (such as monad
342 comprehensions, overloaded literals, or deriving clauses) require some
343 stuff to be loaded that isn't explicitly mentioned in the code.
345 This doesn't apply in interface mode, where everything is explicit,
346 but we don't check for this case: it does no harm to record an
347 ``extra'' occurrence and @lookupOrigNames@ isn't used much in
348 interface mode (it's only the @Nothing@ clause of @rnDerivs@ that
349 calls it at all I think).
351 \fbox{{\em Jan 98: this comment is wrong: @rnHsType@ uses it quite a bit.}}
354 lookupOrigNames :: [RdrName] -> RnM d NameSet
355 lookupOrigNames rdr_names
356 = mapRn lookupOrigName rdr_names `thenRn` \ names ->
357 returnRn (mkNameSet names)
360 lookupSysBinder is used for the "system binders" of a type, class, or
361 instance decl. It ensures that the module is set correctly in the
362 name cache, and sets the provenance on the returned name too. The
363 returned name will end up actually in the type, class, or instance.
366 lookupSysBinder rdr_name
367 = ASSERT( isUnqual rdr_name )
368 getModuleRn `thenRn` \ mod ->
369 getSrcLocRn `thenRn` \ loc ->
370 newTopBinder mod rdr_name loc
374 %*********************************************************
376 \subsection{Implicit free vars and sugar names}
378 %*********************************************************
380 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
381 mentioned explicitly, but which might be needed by the type checker.
384 getImplicitStmtFVs -- Compiling a statement
385 = returnRn (mkFVs [printName, bindIOName, returnIOName, failIOName]
386 `plusFV` ubiquitousNames)
387 -- These are all needed implicitly when compiling a statement
388 -- See TcModule.tc_stmts
390 getImplicitModuleFVs mod_name decls -- Compiling a module
391 = lookupOrigNames deriv_occs `thenRn` \ deriving_names ->
392 returnRn (deriving_names `plusFV` implicit_main `plusFV` ubiquitousNames)
394 -- Add occurrences for IO or PrimIO
395 implicit_main | mod_name == mAIN_Name
396 || mod_name == pREL_MAIN_Name = unitFV ioTyConName
397 | otherwise = emptyFVs
399 deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
400 cls <- deriv_classes,
401 occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
403 -- ubiquitous_names are loaded regardless, because
404 -- they are needed in virtually every program
406 = mkFVs [unpackCStringName, unpackCStringFoldrName,
407 unpackCStringUtf8Name, eqStringName]
408 -- Virtually every program has error messages in it somewhere
411 mkFVs [getName unitTyCon, funTyConName, boolTyConName, intTyConName]
412 -- Add occurrences for very frequently used types.
413 -- (e.g. we don't want to be bothered with making funTyCon a
414 -- free var at every function application!)
417 %************************************************************************
419 \subsection{Re-bindable desugaring names}
421 %************************************************************************
423 Haskell 98 says that when you say "3" you get the "fromInteger" from the
424 Standard Prelude, regardless of what is in scope. However, to experiment
425 with having a language that is less coupled to the standard prelude, we're
426 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
427 happens to be in scope. Then you can
429 import MyPrelude as Prelude
430 to get the desired effect.
432 At the moment this just happens for
433 * fromInteger, fromRational on literals (in expressions and patterns)
434 * negate (in expressions)
435 * minus (arising from n+k patterns)
437 We store the relevant Name in the HsSyn tree, in
438 * HsIntegral/HsFractional
441 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
442 fromRationalName etc), but the renamer changes this to the appropriate user
443 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
446 lookupSyntaxName :: Name -- The standard name
447 -> RnMS Name -- Possibly a non-standard name
448 lookupSyntaxName std_name
449 = doptRn Opt_NoImplicitPrelude `thenRn` \ no_prelude ->
450 if not no_prelude then
451 returnRn std_name -- Normal case
454 rdr_name = mkRdrUnqual (nameOccName std_name)
455 -- Get the similarly named thing from the local environment
461 %*********************************************************
465 %*********************************************************
468 newLocalsRn :: [(RdrName,SrcLoc)]
470 newLocalsRn rdr_names_w_loc
471 = getNameSupplyRn `thenRn` \ name_supply ->
473 (us', us1) = splitUniqSupply (nsUniqs name_supply)
474 uniqs = uniqsFromSupply us1
475 names = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
476 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
479 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
483 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
484 -> [(RdrName,SrcLoc)]
485 -> ([Name] -> RnMS a)
487 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
488 = getModeRn `thenRn` \ mode ->
489 getLocalNameEnv `thenRn` \ local_env ->
490 getGlobalNameEnv `thenRn` \ global_env ->
492 -- Check for duplicate names
493 checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
495 -- Warn about shadowing, but only in source modules
497 check_shadow (rdr_name,loc)
498 | rdr_name `elemRdrEnv` local_env
499 || rdr_name `elemRdrEnv` global_env
500 = pushSrcLocRn loc $ addWarnRn (shadowedNameWarn rdr_name)
506 SourceMode -> ifOptRn Opt_WarnNameShadowing $
507 mapRn_ check_shadow rdr_names_w_loc
511 newLocalsRn rdr_names_w_loc `thenRn` \ names ->
513 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
515 setLocalNameEnv new_local_env (enclosed_scope names)
517 bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
518 -- A specialised variant when renaming stuff from interface
519 -- files (of which there is a lot)
521 -- * no checks for shadowing
523 -- * deal with free vars
524 bindCoreLocalRn rdr_name enclosed_scope
525 = getSrcLocRn `thenRn` \ loc ->
526 getLocalNameEnv `thenRn` \ name_env ->
527 getNameSupplyRn `thenRn` \ name_supply ->
529 (us', us1) = splitUniqSupply (nsUniqs name_supply)
530 uniq = uniqFromSupply us1
531 name = mkLocalName uniq (rdrNameOcc rdr_name) loc
533 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
535 new_name_env = extendRdrEnv name_env rdr_name name
537 setLocalNameEnv new_name_env (enclosed_scope name)
539 bindCoreLocalsRn [] thing_inside = thing_inside []
540 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
541 bindCoreLocalsRn bs $ \ names' ->
542 thing_inside (name':names')
544 bindLocalNames names enclosed_scope
545 = getLocalNameEnv `thenRn` \ name_env ->
546 setLocalNameEnv (extendLocalRdrEnv name_env names)
549 bindLocalNamesFV names enclosed_scope
550 = bindLocalNames names $
551 enclosed_scope `thenRn` \ (thing, fvs) ->
552 returnRn (thing, delListFromNameSet fvs names)
555 -------------------------------------
556 bindLocalRn doc rdr_name enclosed_scope
557 = getSrcLocRn `thenRn` \ loc ->
558 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
562 bindLocalsRn doc rdr_names enclosed_scope
563 = getSrcLocRn `thenRn` \ loc ->
564 bindLocatedLocalsRn doc
565 (rdr_names `zip` repeat loc)
568 -- binLocalsFVRn is the same as bindLocalsRn
569 -- except that it deals with free vars
570 bindLocalsFVRn doc rdr_names enclosed_scope
571 = bindLocalsRn doc rdr_names $ \ names ->
572 enclosed_scope names `thenRn` \ (thing, fvs) ->
573 returnRn (thing, delListFromNameSet fvs names)
575 -------------------------------------
576 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
577 -- This tiresome function is used only in rnSourceDecl on InstDecl
578 extendTyVarEnvFVRn tyvars enclosed_scope
579 = bindLocalNames tyvars enclosed_scope `thenRn` \ (thing, fvs) ->
580 returnRn (thing, delListFromNameSet fvs tyvars)
582 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
583 -> ([HsTyVarBndr Name] -> RnMS a)
585 bindTyVarsRn doc_str tyvar_names enclosed_scope
586 = bindTyVars2Rn doc_str tyvar_names $ \ names tyvars ->
587 enclosed_scope tyvars
589 -- Gruesome name: return Names as well as HsTyVars
590 bindTyVars2Rn :: SDoc -> [HsTyVarBndr RdrName]
591 -> ([Name] -> [HsTyVarBndr Name] -> RnMS a)
593 bindTyVars2Rn doc_str tyvar_names enclosed_scope
594 = getSrcLocRn `thenRn` \ loc ->
596 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
598 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
599 enclosed_scope names (zipWith replaceTyVarName tyvar_names names)
601 bindPatSigTyVars :: [RdrNameHsType]
602 -> RnMS (a, FreeVars)
603 -> RnMS (a, FreeVars)
604 -- Find the type variables in the pattern type
605 -- signatures that must be brought into scope
607 bindPatSigTyVars tys enclosed_scope
608 = getLocalNameEnv `thenRn` \ name_env ->
609 getSrcLocRn `thenRn` \ loc ->
611 forall_tyvars = nub [ tv | ty <- tys,
612 tv <- extractHsTyRdrTyVars ty,
613 not (tv `elemFM` name_env)
615 -- The 'nub' is important. For example:
616 -- f (x :: t) (y :: t) = ....
617 -- We don't want to complain about binding t twice!
619 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
620 doc_sig = text "In a pattern type-signature"
622 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
623 enclosed_scope `thenRn` \ (thing, fvs) ->
624 returnRn (thing, delListFromNameSet fvs names)
627 -------------------------------------
628 checkDupOrQualNames, checkDupNames :: SDoc
629 -> [(RdrName, SrcLoc)]
631 -- Works in any variant of the renamer monad
633 checkDupOrQualNames doc_str rdr_names_w_loc
634 = -- Check for use of qualified names
635 mapRn_ (qualNameErr doc_str) quals `thenRn_`
636 checkDupNames doc_str rdr_names_w_loc
638 quals = filter (isQual . fst) rdr_names_w_loc
640 checkDupNames doc_str rdr_names_w_loc
641 = -- Check for duplicated names in a binding group
642 mapRn_ (dupNamesErr doc_str) dups
644 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
648 %************************************************************************
650 \subsection{GlobalRdrEnv}
652 %************************************************************************
655 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
656 -> Bool -- True <=> want unqualified import
657 -> (Name -> Provenance)
658 -> Avails -- Whats imported
659 -> Avails -- What's to be hidden
660 -- I.e. import (imports - hides)
664 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails hides deprecs
667 -- Make the name environment. We're talking about a
668 -- single module here, so there must be no name clashes.
669 -- In practice there only ever will be if it's the module
672 -- Add qualified names for the things that are available
673 -- (Qualified names are always imported)
674 gbl_env1 = foldl add_avail emptyRdrEnv avails
676 -- Delete (qualified names of) things that are hidden
677 gbl_env2 = foldl del_avail gbl_env1 hides
679 -- Add unqualified names
680 gbl_env3 | unqual_imp = foldl add_unqual gbl_env2 (rdrEnvToList gbl_env2)
681 | otherwise = gbl_env2
683 add_unqual env (qual_name, elts)
684 = foldl add_one env elts
686 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
687 unqual_name = unqualifyRdrName qual_name
688 -- The qualified import should only have added one
689 -- binding for each qualified name! But if there's an error in
690 -- the module (multiple bindings for the same name) we may get
691 -- duplicates. So the simple thing is to do the fold.
694 = foldl delOneFromGlobalRdrEnv env rdr_names
696 rdr_names = map (mkRdrQual this_mod . nameOccName)
700 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
701 add_avail env avail = foldl add_name env (availNames avail)
703 add_name env name -- Add qualified name only
704 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
706 occ = nameOccName name
707 elt = GRE name (mk_provenance name) (lookupDeprec deprecs name)
709 mkIfaceGlobalRdrEnv :: [(ModuleName,Avails)] -> GlobalRdrEnv
710 -- Used to construct a GlobalRdrEnv for an interface that we've
711 -- read from a .hi file. We can't construct the original top-level
712 -- environment because we don't have enough info, but we compromise
713 -- by making an environment from its exports
714 mkIfaceGlobalRdrEnv m_avails
715 = foldl add emptyRdrEnv m_avails
717 add env (mod,avails) = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True
718 (\n -> LocalDef) avails [] NoDeprecs)
719 -- The NoDeprecs is a bit of a hack I suppose
723 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
724 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
726 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
727 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
729 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
730 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
732 combine_globals :: [GlobalRdrElt] -- Old
733 -> [GlobalRdrElt] -- New
735 combine_globals ns_old ns_new -- ns_new is often short
736 = foldr add ns_old ns_new
738 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
741 choose n m | n `beats` m = n
744 (GRE n pn _) `beats` (GRE m pm _) = n==m && pn `hasBetterProv` pm
746 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
747 is_duplicate (GRE n1 LocalDef _) (GRE n2 LocalDef _) = False
748 is_duplicate (GRE n1 _ _) (GRE n2 _ _) = n1 == n2
751 We treat two bindings of a locally-defined name as a duplicate,
752 because they might be two separate, local defns and we want to report
753 and error for that, {\em not} eliminate a duplicate.
755 On the other hand, if you import the same name from two different
756 import statements, we {\em do} want to eliminate the duplicate, not report
759 If a module imports itself then there might be a local defn and an imported
760 defn of the same name; in this case the names will compare as equal, but
761 will still have different provenances.
764 @unQualInScope@ returns a function that takes a @Name@ and tells whether
765 its unqualified name is in scope. This is put as a boolean flag in
766 the @Name@'s provenance to guide whether or not to print the name qualified
770 unQualInScope :: GlobalRdrEnv -> Name -> Bool
771 -- True if 'f' is in scope, and has only one binding
772 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
774 = (`elemNameSet` unqual_names)
776 unqual_names :: NameSet
777 unqual_names = foldRdrEnv add emptyNameSet env
778 add rdr_name [GRE name _ _] unquals | isUnqual rdr_name = addOneToNameSet unquals name
779 add _ _ unquals = unquals
783 %************************************************************************
787 %************************************************************************
790 plusAvail (Avail n1) (Avail n2) = Avail n1
791 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
794 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
797 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
798 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
800 emptyAvailEnv = emptyNameEnv
801 unitAvailEnv :: AvailInfo -> AvailEnv
802 unitAvailEnv a = unitNameEnv (availName a) a
804 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
805 plusAvailEnv = plusNameEnv_C plusAvail
807 availEnvElts = nameEnvElts
809 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
810 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
812 availsToNameSet :: [AvailInfo] -> NameSet
813 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
815 availName :: GenAvailInfo name -> name
816 availName (Avail n) = n
817 availName (AvailTC n _) = n
819 availNames :: GenAvailInfo name -> [name]
820 availNames (Avail n) = [n]
821 availNames (AvailTC n ns) = ns
823 -------------------------------------
824 filterAvail :: RdrNameIE -- Wanted
825 -> AvailInfo -- Available
826 -> Maybe AvailInfo -- Resulting available;
827 -- Nothing if (any of the) wanted stuff isn't there
829 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
830 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
831 | otherwise = Nothing
833 is_wanted name = nameOccName name `elem` wanted_occs
834 sub_names_ok = all (`elem` avail_occs) wanted_occs
835 avail_occs = map nameOccName ns
836 wanted_occs = map rdrNameOcc (want:wants)
838 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
841 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
843 filterAvail (IEVar _) avail@(Avail n) = Just avail
844 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
846 wanted n = nameOccName n == occ
848 -- The second equation happens if we import a class op, thus
850 -- where op is a class operation
852 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
853 -- We don't complain even if the IE says T(..), but
854 -- no constrs/class ops of T are available
855 -- Instead that's caught with a warning by the caller
857 filterAvail ie avail = Nothing
859 -------------------------------------
860 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
861 -- Group by module and sort by occurrence
862 -- This keeps the list in canonical order
863 groupAvails this_mod avails
864 = [ (mkSysModuleNameFS fs, sortLt lt avails)
865 | (fs,avails) <- fmToList groupFM
868 groupFM :: FiniteMap FastString Avails
869 -- Deliberately use the FastString so we
870 -- get a canonical ordering
871 groupFM = foldl add emptyFM avails
873 add env avail = addToFM_C combine env mod_fs [avail']
875 mod_fs = moduleNameFS (moduleName avail_mod)
876 avail_mod = case nameModule_maybe (availName avail) of
879 combine old _ = avail':old
880 avail' = sortAvail avail
882 a1 `lt` a2 = occ1 < occ2
884 occ1 = nameOccName (availName a1)
885 occ2 = nameOccName (availName a2)
887 sortAvail :: AvailInfo -> AvailInfo
888 -- Sort the sub-names into canonical order.
889 -- The canonical order has the "main name" at the beginning
890 -- (if it's there at all)
891 sortAvail (Avail n) = Avail n
892 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
893 | otherwise = AvailTC n ( sortLt lt ns)
895 n1 `lt` n2 = nameOccName n1 < nameOccName n2
899 %************************************************************************
901 \subsection{Free variable manipulation}
903 %************************************************************************
907 mapFvRn f xs = mapRn f xs `thenRn` \ stuff ->
909 (ys, fvs_s) = unzip stuff
911 returnRn (ys, plusFVs fvs_s)
915 %************************************************************************
917 \subsection{Envt utility functions}
919 %************************************************************************
922 warnUnusedModules :: [ModuleName] -> RnM d ()
923 warnUnusedModules mods
924 = ifOptRn Opt_WarnUnusedImports (mapRn_ (addWarnRn . unused_mod) mods)
926 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
927 text "is imported, but nothing from it is used",
928 parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
931 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
932 warnUnusedImports names
933 = ifOptRn Opt_WarnUnusedImports (warnUnusedBinds names)
935 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
936 warnUnusedLocalBinds names
937 = ifOptRn Opt_WarnUnusedBinds (warnUnusedBinds [(n,LocalDef) | n<-names])
939 warnUnusedMatches names
940 = ifOptRn Opt_WarnUnusedMatches (warnUnusedGroup [(n,LocalDef) | n<-names])
942 -------------------------
944 warnUnusedBinds :: [(Name,Provenance)] -> RnM d ()
945 warnUnusedBinds names
946 = mapRn_ warnUnusedGroup groups
948 -- Group by provenance
949 groups = equivClasses cmp names
950 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
953 -------------------------
955 warnUnusedGroup :: [(Name,Provenance)] -> RnM d ()
956 warnUnusedGroup names
957 | null filtered_names = returnRn ()
958 | not is_local = returnRn ()
960 = pushSrcLocRn def_loc $
962 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
964 filtered_names = filter reportable names
965 (name1, prov1) = head filtered_names
966 (is_local, def_loc, msg)
968 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
970 NonLocalDef (UserImport mod loc _)
971 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
973 reportable (name,_) = case occNameUserString (nameOccName name) of
976 -- Haskell 98 encourages compilers to suppress warnings about
977 -- unused names in a pattern if they start with "_".
981 addNameClashErrRn rdr_name (np1:nps)
982 = addErrRn (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
983 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
985 msg1 = ptext SLIT("either") <+> mk_ref np1
986 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
987 mk_ref (GRE name prov _) = quotes (ppr name) <> comma <+> pprNameProvenance name prov
989 shadowedNameWarn shadow
990 = hsep [ptext SLIT("This binding for"),
992 ptext SLIT("shadows an existing binding")]
995 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
997 flavour = occNameFlavour (rdrNameOcc name)
999 qualNameErr descriptor (name,loc)
1000 = pushSrcLocRn loc $
1001 addErrRn (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1004 dupNamesErr descriptor ((name,loc) : dup_things)
1005 = pushSrcLocRn loc $
1006 addErrRn ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1010 warnDeprec :: Name -> DeprecTxt -> RnM d ()
1012 = ifOptRn Opt_WarnDeprecations $
1013 addWarnRn (sep [ text (occNameFlavour (nameOccName name)) <+>
1014 quotes (ppr name) <+> text "is deprecated:",