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 RnHsSyn ( RenamedHsDecl )
16 import RdrHsSyn ( RdrNameIE )
17 import RdrName ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
18 mkRdrUnqual, mkRdrQual, qualifyRdrName, lookupRdrEnv, foldRdrEnv
20 import HsTypes ( hsTyVarName, replaceTyVarName )
21 import HscTypes ( Provenance(..), pprNameProvenance, hasBetterProv,
22 ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), AvailEnv,
23 AvailInfo, Avails, GenAvailInfo(..), NameSupply(..),
24 Deprecations(..), lookupDeprec
29 mkLocalName, mkGlobalName,
30 mkIPName, nameOccName, nameModule_maybe,
31 setNameModuleAndLoc, mkNameEnv
33 import Name ( extendNameEnv_C, plusNameEnv_C, nameEnvElts )
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
47 import TysWiredIn ( unitTyCon ) -- A little odd
50 import SrcLoc ( SrcLoc, noSrcLoc )
52 import ListSetOps ( removeDups, equivClasses )
53 import Util ( sortLt )
55 import UniqFM ( lookupWithDefaultUFM )
56 import Maybes ( orElse )
58 import FastString ( FastString )
61 %*********************************************************
63 \subsection{Making new names}
65 %*********************************************************
68 newTopBinder :: Module -> RdrName -> SrcLoc -> RnM d Name
69 -- newTopBinder puts into the cache the binder with the
70 -- module information set correctly. When the decl is later renamed,
71 -- the binding site will thereby get the correct module.
72 -- There maybe occurrences that don't have the correct Module, but
73 -- by the typechecker will propagate the binding definition to all
74 -- the occurrences, so that doesn't matter
76 newTopBinder mod rdr_name loc
77 = -- First check the cache
79 -- There should never be a qualified name in a binding position (except in instance decls)
80 -- The parser doesn't check this because the same parser parses instance decls
81 (if isQual rdr_name then
82 qualNameErr (text "its declaration") (rdr_name,loc)
87 getNameSupplyRn `thenRn` \ name_supply ->
89 occ = rdrNameOcc rdr_name
90 key = (moduleName mod, occ)
91 cache = nsNames name_supply
93 case lookupFM cache key of
95 -- A hit in the cache! We are at the binding site of the name, and
96 -- this is the moment when we know all about
97 -- a) the Name's host Module (in particular, which
98 -- package it comes from)
99 -- b) its defining SrcLoc
100 -- So we update this info
103 new_name = setNameModuleAndLoc name mod loc
104 new_cache = addToFM cache key new_name
106 setNameSupplyRn (name_supply {nsNames = new_cache}) `thenRn_`
107 -- traceRn (text "newTopBinder: overwrite" <+> ppr new_name) `thenRn_`
110 -- Miss in the cache!
111 -- Build a completely new Name, and put it in the cache
112 -- Even for locally-defined names we use implicitImportProvenance;
113 -- updateProvenances will set it to rights
115 (us', us1) = splitUniqSupply (nsUniqs name_supply)
116 uniq = uniqFromSupply us1
117 new_name = mkGlobalName uniq mod occ loc
118 new_cache = addToFM cache key new_name
120 setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
121 -- traceRn (text "newTopBinder: new" <+> ppr new_name) `thenRn_`
125 newGlobalName :: ModuleName -> OccName -> RnM d Name
126 -- Used for *occurrences*. We make a place-holder Name, really just
127 -- to agree on its unique, which gets overwritten when we read in
128 -- the binding occurence later (newTopBinder)
129 -- The place-holder Name doesn't have the right SrcLoc, and its
130 -- Module won't have the right Package either.
132 -- (We have to pass a ModuleName, not a Module, because we may be
133 -- simply looking at an occurrence M.x in an interface file.)
135 -- This means that a renamed program may have incorrect info
136 -- on implicitly-imported occurrences, but the correct info on the
137 -- *binding* declaration. It's the type checker that propagates the
138 -- correct information to all the occurrences.
139 -- Since implicitly-imported names never occur in error messages,
140 -- it doesn't matter that we get the correct info in place till later,
141 -- (but since it affects DLL-ery it does matter that we get it right
143 newGlobalName mod_name occ
144 = getNameSupplyRn `thenRn` \ name_supply ->
146 key = (mod_name, occ)
147 cache = nsNames name_supply
149 case lookupFM cache key of
150 Just name -> -- traceRn (text "newGlobalName: hit" <+> ppr name) `thenRn_`
153 Nothing -> setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
154 -- traceRn (text "newGlobalName: new" <+> ppr name) `thenRn_`
157 (us', us1) = splitUniqSupply (nsUniqs name_supply)
158 uniq = uniqFromSupply us1
159 mod = mkVanillaModule mod_name
160 name = mkGlobalName uniq mod occ noSrcLoc
161 new_cache = addToFM cache key name
164 = getNameSupplyRn `thenRn` \ name_supply ->
166 ipcache = nsIPs name_supply
168 case lookupFM ipcache key of
169 Just name -> returnRn name
170 Nothing -> setNameSupplyRn (name_supply {nsUniqs = us', nsIPs = new_ipcache}) `thenRn_`
173 (us', us1) = splitUniqSupply (nsUniqs name_supply)
174 uniq = uniqFromSupply us1
175 name = mkIPName uniq key
176 new_ipcache = addToFM ipcache key name
177 where key = (rdrNameOcc rdr_name)
180 %*********************************************************
182 \subsection{Looking up names}
184 %*********************************************************
186 Looking up a name in the RnEnv.
189 lookupBndrRn rdr_name
190 = getLocalNameEnv `thenRn` \ local_env ->
191 case lookupRdrEnv local_env rdr_name of
192 Just name -> returnRn name
193 Nothing -> lookupTopBndrRn rdr_name
195 lookupTopBndrRn rdr_name
196 = getModeRn `thenRn` \ mode ->
197 if isInterfaceMode mode
198 then lookupIfaceName rdr_name
199 else -- Source mode, so look up a *qualified* version
200 -- of the name, so that we get the right one even
201 -- if there are many with the same occ name
202 -- There must *be* a binding
203 getModuleRn `thenRn` \ mod ->
204 getGlobalNameEnv `thenRn` \ global_env ->
205 lookupSrcName global_env (qualifyRdrName (moduleName mod) rdr_name)
207 -- lookupSigOccRn is used for type signatures and pragmas
213 -- It's clear that the 'f' in the signature must refer to A.f
214 -- The Haskell98 report does not stipulate this, but it will!
215 -- So we must treat the 'f' in the signature in the same way
216 -- as the binding occurrence of 'f', using lookupBndrRn
217 lookupSigOccRn :: RdrName -> RnMS Name
218 lookupSigOccRn = lookupBndrRn
220 -- lookupOccRn looks up an occurrence of a RdrName
221 lookupOccRn :: RdrName -> RnMS Name
223 = getLocalNameEnv `thenRn` \ local_env ->
224 case lookupRdrEnv local_env rdr_name of
225 Just name -> returnRn name
226 Nothing -> lookupGlobalOccRn rdr_name
228 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
229 -- environment. It's used only for
230 -- record field names
231 -- class op names in class and instance decls
233 lookupGlobalOccRn rdr_name
234 = getModeRn `thenRn` \ mode ->
235 if (isInterfaceMode mode)
236 then lookupIfaceName rdr_name
239 getGlobalNameEnv `thenRn` \ global_env ->
241 SourceMode -> lookupSrcName global_env rdr_name
244 | not (isQual rdr_name) ->
245 lookupSrcName global_env rdr_name
247 -- We allow qualified names on the command line to refer to
248 -- *any* name exported by any module in scope, just as if
249 -- there was an "import qualified M" declaration for every
252 -- First look up the name in the normal environment. If
253 -- it isn't there, we manufacture a new occurrence of an
256 case lookupRdrEnv global_env rdr_name of
257 Just _ -> lookupSrcName global_env rdr_name
258 Nothing -> lookupQualifiedName rdr_name
260 -- a qualified name on the command line can refer to any module at all: we
261 -- try to load the interface if we don't already have it.
262 lookupQualifiedName :: RdrName -> RnM d Name
263 lookupQualifiedName rdr_name
265 mod = rdrNameModule rdr_name
266 occ = rdrNameOcc rdr_name
268 loadInterface (ppr rdr_name) mod ImportBySystem `thenRn` \ iface ->
269 case [ name | (_,avails) <- mi_exports iface,
271 name <- availNames avail,
272 nameOccName name == occ ] of
273 (n:ns) -> ASSERT (null ns) returnRn n
274 _ -> failWithRn (mkUnboundName rdr_name) (unknownNameErr rdr_name)
276 lookupSrcName :: GlobalRdrEnv -> RdrName -> RnM d Name
277 -- NB: passed GlobalEnv explicitly, not necessarily in RnMS monad
278 lookupSrcName global_env rdr_name
279 | isOrig rdr_name -- Can occur in source code too
280 = lookupOrigName rdr_name
283 = case lookupRdrEnv global_env rdr_name of
284 Just [GRE name _ Nothing] -> returnRn name
285 Just [GRE name _ (Just deprec)] -> warnDeprec name deprec `thenRn_`
287 Just stuff@(GRE name _ _ : _) -> addNameClashErrRn rdr_name stuff `thenRn_`
289 Nothing -> failWithRn (mkUnboundName rdr_name)
290 (unknownNameErr rdr_name)
292 lookupOrigName :: RdrName -> RnM d Name
293 lookupOrigName rdr_name
294 = ASSERT( isOrig rdr_name )
295 newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
297 lookupIfaceUnqual :: RdrName -> RnM d Name
298 lookupIfaceUnqual rdr_name
299 = ASSERT( isUnqual rdr_name )
300 -- An Unqual is allowed; interface files contain
301 -- unqualified names for locally-defined things, such as
302 -- constructors of a data type.
303 getModuleRn `thenRn ` \ mod ->
304 newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
306 lookupIfaceName :: RdrName -> RnM d Name
307 lookupIfaceName rdr_name
308 | isUnqual rdr_name = lookupIfaceUnqual rdr_name
309 | otherwise = lookupOrigName rdr_name
312 @lookupOrigName@ takes an RdrName representing an {\em original}
313 name, and adds it to the occurrence pool so that it'll be loaded
314 later. This is used when language constructs (such as monad
315 comprehensions, overloaded literals, or deriving clauses) require some
316 stuff to be loaded that isn't explicitly mentioned in the code.
318 This doesn't apply in interface mode, where everything is explicit,
319 but we don't check for this case: it does no harm to record an
320 ``extra'' occurrence and @lookupOrigNames@ isn't used much in
321 interface mode (it's only the @Nothing@ clause of @rnDerivs@ that
322 calls it at all I think).
324 \fbox{{\em Jan 98: this comment is wrong: @rnHsType@ uses it quite a bit.}}
327 lookupOrigNames :: [RdrName] -> RnM d NameSet
328 lookupOrigNames rdr_names
329 = mapRn lookupOrigName rdr_names `thenRn` \ names ->
330 returnRn (mkNameSet names)
333 lookupSysBinder is used for the "system binders" of a type, class, or
334 instance decl. It ensures that the module is set correctly in the
335 name cache, and sets the provenance on the returned name too. The
336 returned name will end up actually in the type, class, or instance.
339 lookupSysBinder rdr_name
340 = ASSERT( isUnqual rdr_name )
341 getModuleRn `thenRn` \ mod ->
342 getSrcLocRn `thenRn` \ loc ->
343 newTopBinder mod rdr_name loc
347 %*********************************************************
349 \subsection{Implicit free vars and sugar names}
351 %*********************************************************
353 @addImplicitFVs@ forces the renamer to slurp in some things which aren't
354 mentioned explicitly, but which might be needed by the type checker.
357 addImplicitFVs :: GlobalRdrEnv
358 -> Maybe (ModuleName, [RenamedHsDecl]) -- Nothing when compling an expression
359 -> FreeVars -- Free in the source
360 -> RnMG (FreeVars, SyntaxMap) -- Augmented source free vars
362 addImplicitFVs gbl_env maybe_mod source_fvs
363 = -- Find out what re-bindable names to use for desugaring
364 rnSyntaxNames gbl_env source_fvs `thenRn` \ (source_fvs1, sugar_map) ->
366 -- Find implicit FVs thade
367 extra_implicits maybe_mod `thenRn` \ extra_fvs ->
370 implicit_fvs = ubiquitousNames `plusFV` extra_fvs
371 slurp_fvs = implicit_fvs `plusFV` source_fvs1
372 -- It's important to do the "plus" this way round, so that
373 -- when compiling the prelude, locally-defined (), Bool, etc
374 -- override the implicit ones.
376 returnRn (slurp_fvs, sugar_map)
379 extra_implicits Nothing -- Compiling an expression
380 = returnRn (unitFV printName) -- print :: a -> IO () may be needed later
382 extra_implicits (Just (mod_name, decls)) -- Compiling a module
383 = lookupOrigNames deriv_occs `thenRn` \ deriving_names ->
384 returnRn (deriving_names `plusFV` implicit_main)
386 -- Add occurrences for IO or PrimIO
387 implicit_main | mod_name == mAIN_Name
388 || mod_name == pREL_MAIN_Name = unitFV ioTyConName
389 | otherwise = emptyFVs
391 deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
392 cls <- deriv_classes,
393 occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
395 -- ubiquitous_names are loaded regardless, because
396 -- they are needed in virtually every program
398 = mkFVs [unpackCStringName, unpackCStringFoldrName,
399 unpackCStringUtf8Name, eqStringName]
400 -- Virtually every program has error messages in it somewhere
403 mkFVs [getName unitTyCon, funTyConName, boolTyConName, intTyConName]
404 -- Add occurrences for very frequently used types.
405 -- (e.g. we don't want to be bothered with making funTyCon a
406 -- free var at every function application!)
410 implicitGates :: Name -> FreeVars
411 -- If we load class Num, add Integer to the gates
412 -- This takes account of the fact that Integer might be needed for
413 -- defaulting, but we don't want to load Integer (and all its baggage)
414 -- if there's no numeric stuff needed.
415 -- Similarly for class Fractional and Double
417 -- NB: If we load (say) Floating, we'll end up loading Fractional too,
418 -- since Fractional is a superclass of Floating
419 implicitGates cls | cls `hasKey` numClassKey = unitFV integerTyConName
420 | cls `hasKey` fractionalClassKey = unitFV doubleTyConName
421 | otherwise = emptyFVs
425 rnSyntaxNames :: GlobalRdrEnv -> FreeVars -> RnMG (FreeVars, SyntaxMap)
426 -- Look up the re-bindable syntactic sugar names
427 -- Any errors arising from these lookups may surprise the
428 -- programmer, since they aren't explicitly mentioned, and
429 -- the src line will be unhelpful (ToDo)
431 rnSyntaxNames gbl_env source_fvs
432 = doptRn Opt_NoImplicitPrelude `thenRn` \ no_prelude ->
433 if not no_prelude then
434 returnRn (source_fvs, vanillaSyntaxMap)
437 -- There's a -fno-implicit-prelude flag,
438 -- so build the re-mapping function
440 reqd_syntax_list = filter is_reqd syntaxList
441 is_reqd (n,_) = n `elemNameSet` source_fvs
442 lookup (n,rn) = lookupSrcName gbl_env rn `thenRn` \ rn' ->
445 mapRn lookup reqd_syntax_list `thenRn` \ rn_syntax_list ->
447 -- Delete the proxies and add the actuals
448 proxies = map fst rn_syntax_list
449 actuals = map snd rn_syntax_list
450 new_source_fvs = (proxies `delFVs` source_fvs) `plusFV` mkFVs actuals
452 syntax_env = mkNameEnv rn_syntax_list
453 syntax_map n = lookupNameEnv syntax_env n `orElse` n
455 returnRn (new_source_fvs, syntax_map)
459 %*********************************************************
463 %*********************************************************
466 newLocalsRn :: [(RdrName,SrcLoc)]
468 newLocalsRn rdr_names_w_loc
469 = getNameSupplyRn `thenRn` \ name_supply ->
471 n = length rdr_names_w_loc
472 (us', us1) = splitUniqSupply (nsUniqs name_supply)
473 uniqs = uniqsFromSupply n us1
474 names = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
475 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
478 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
482 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
483 -> [(RdrName,SrcLoc)]
484 -> ([Name] -> RnMS a)
486 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
487 = getModeRn `thenRn` \ mode ->
488 getLocalNameEnv `thenRn` \ name_env ->
490 -- Check for duplicate names
491 checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
493 doptRn Opt_WarnNameShadowing `thenRn` \ warn_shadow ->
495 -- Warn about shadowing, but only in source modules
497 SourceMode | warn_shadow -> mapRn_ (check_shadow name_env) rdr_names_w_loc
501 newLocalsRn rdr_names_w_loc `thenRn` \ names ->
503 new_local_env = addListToRdrEnv name_env (map fst rdr_names_w_loc `zip` names)
505 setLocalNameEnv new_local_env (enclosed_scope names)
508 check_shadow name_env (rdr_name,loc)
509 = case lookupRdrEnv name_env rdr_name of
510 Nothing -> returnRn ()
511 Just name -> pushSrcLocRn loc $
512 addWarnRn (shadowedNameWarn rdr_name)
514 bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
515 -- A specialised variant when renaming stuff from interface
516 -- files (of which there is a lot)
518 -- * no checks for shadowing
520 -- * deal with free vars
521 bindCoreLocalRn rdr_name enclosed_scope
522 = getSrcLocRn `thenRn` \ loc ->
523 getLocalNameEnv `thenRn` \ name_env ->
524 getNameSupplyRn `thenRn` \ name_supply ->
526 (us', us1) = splitUniqSupply (nsUniqs name_supply)
527 uniq = uniqFromSupply us1
528 name = mkLocalName uniq (rdrNameOcc rdr_name) loc
530 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
532 new_name_env = extendRdrEnv name_env rdr_name name
534 setLocalNameEnv new_name_env (enclosed_scope name)
536 bindCoreLocalsRn [] thing_inside = thing_inside []
537 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
538 bindCoreLocalsRn bs $ \ names' ->
539 thing_inside (name':names')
541 bindLocalNames names enclosed_scope
542 = getLocalNameEnv `thenRn` \ name_env ->
543 setLocalNameEnv (addListToRdrEnv name_env pairs)
546 pairs = [(mkRdrUnqual (nameOccName n), n) | n <- names]
548 bindLocalNamesFV names enclosed_scope
549 = bindLocalNames names $
550 enclosed_scope `thenRn` \ (thing, fvs) ->
551 returnRn (thing, delListFromNameSet fvs names)
554 -------------------------------------
555 bindLocalRn doc rdr_name enclosed_scope
556 = getSrcLocRn `thenRn` \ loc ->
557 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
561 bindLocalsRn doc rdr_names enclosed_scope
562 = getSrcLocRn `thenRn` \ loc ->
563 bindLocatedLocalsRn doc
564 (rdr_names `zip` repeat loc)
567 -- binLocalsFVRn is the same as bindLocalsRn
568 -- except that it deals with free vars
569 bindLocalsFVRn doc rdr_names enclosed_scope
570 = bindLocalsRn doc rdr_names $ \ names ->
571 enclosed_scope names `thenRn` \ (thing, fvs) ->
572 returnRn (thing, delListFromNameSet fvs names)
574 -------------------------------------
575 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
576 -- This tiresome function is used only in rnSourceDecl on InstDecl
577 extendTyVarEnvFVRn tyvars enclosed_scope
578 = bindLocalNames tyvars enclosed_scope `thenRn` \ (thing, fvs) ->
579 returnRn (thing, delListFromNameSet fvs tyvars)
581 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
582 -> ([HsTyVarBndr Name] -> RnMS a)
584 bindTyVarsRn doc_str tyvar_names enclosed_scope
585 = bindTyVars2Rn doc_str tyvar_names $ \ names tyvars ->
586 enclosed_scope tyvars
588 -- Gruesome name: return Names as well as HsTyVars
589 bindTyVars2Rn :: SDoc -> [HsTyVarBndr RdrName]
590 -> ([Name] -> [HsTyVarBndr Name] -> RnMS a)
592 bindTyVars2Rn doc_str tyvar_names enclosed_scope
593 = getSrcLocRn `thenRn` \ loc ->
595 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
597 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
598 enclosed_scope names (zipWith replaceTyVarName tyvar_names names)
600 bindTyVarsFVRn :: SDoc -> [HsTyVarBndr RdrName]
601 -> ([HsTyVarBndr Name] -> RnMS (a, FreeVars))
602 -> RnMS (a, FreeVars)
603 bindTyVarsFVRn doc_str rdr_names enclosed_scope
604 = bindTyVars2Rn doc_str rdr_names $ \ names tyvars ->
605 enclosed_scope tyvars `thenRn` \ (thing, fvs) ->
606 returnRn (thing, delListFromNameSet fvs names)
608 bindTyVarsFV2Rn :: SDoc -> [HsTyVarBndr RdrName]
609 -> ([Name] -> [HsTyVarBndr Name] -> RnMS (a, FreeVars))
610 -> RnMS (a, FreeVars)
611 bindTyVarsFV2Rn doc_str rdr_names enclosed_scope
612 = bindTyVars2Rn doc_str rdr_names $ \ names tyvars ->
613 enclosed_scope names tyvars `thenRn` \ (thing, fvs) ->
614 returnRn (thing, delListFromNameSet fvs names)
616 bindNakedTyVarsFVRn :: SDoc -> [RdrName]
617 -> ([Name] -> RnMS (a, FreeVars))
618 -> RnMS (a, FreeVars)
619 bindNakedTyVarsFVRn doc_str tyvar_names enclosed_scope
620 = getSrcLocRn `thenRn` \ loc ->
622 located_tyvars = [(tv, loc) | tv <- tyvar_names]
624 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
625 enclosed_scope names `thenRn` \ (thing, fvs) ->
626 returnRn (thing, delListFromNameSet fvs names)
629 -------------------------------------
630 checkDupOrQualNames, checkDupNames :: SDoc
631 -> [(RdrName, SrcLoc)]
633 -- Works in any variant of the renamer monad
635 checkDupOrQualNames doc_str rdr_names_w_loc
636 = -- Check for use of qualified names
637 mapRn_ (qualNameErr doc_str) quals `thenRn_`
638 checkDupNames doc_str rdr_names_w_loc
640 quals = filter (isQual . fst) rdr_names_w_loc
642 checkDupNames doc_str rdr_names_w_loc
643 = -- Check for duplicated names in a binding group
644 mapRn_ (dupNamesErr doc_str) dups
646 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
650 %************************************************************************
652 \subsection{GlobalRdrEnv}
654 %************************************************************************
657 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
658 -> Bool -- True <=> want unqualified import
659 -> Bool -- True <=> want qualified import
660 -> [AvailInfo] -- What's to be hidden (but only the unqualified
661 -- version is hidden)
662 -> (Name -> Provenance)
663 -> Avails -- Whats imported and how
667 mkGlobalRdrEnv this_mod unqual_imp qual_imp hides
668 mk_provenance avails deprecs
671 -- Make the name environment. We're talking about a
672 -- single module here, so there must be no name clashes.
673 -- In practice there only ever will be if it's the module
676 -- Add the things that are available
677 gbl_env1 = foldl add_avail emptyRdrEnv avails
679 -- Delete things that are hidden
680 gbl_env2 = foldl del_avail gbl_env1 hides
682 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
683 add_avail env avail = foldl add_name env (availNames avail)
686 | qual_imp && unqual_imp = env3
691 env1 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
692 env2 = addOneToGlobalRdrEnv env (mkRdrUnqual occ) elt
693 env3 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) elt
694 occ = nameOccName name
695 elt = GRE name (mk_provenance name) (lookupDeprec deprecs name)
697 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
699 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
701 mkIfaceGlobalRdrEnv :: [(ModuleName,Avails)] -> GlobalRdrEnv
702 -- Used to construct a GlobalRdrEnv for an interface that we've
703 -- read from a .hi file. We can't construct the original top-level
704 -- environment because we don't have enough info, but we compromise
705 -- by making an environment from its exports
706 mkIfaceGlobalRdrEnv m_avails
707 = foldl add emptyRdrEnv m_avails
709 add env (mod,avails) = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True False []
710 (\n -> LocalDef) avails NoDeprecs)
711 -- The NoDeprecs is a bit of a hack I suppose
715 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
716 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
718 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
719 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
721 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
722 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
724 combine_globals :: [GlobalRdrElt] -- Old
725 -> [GlobalRdrElt] -- New
727 combine_globals ns_old ns_new -- ns_new is often short
728 = foldr add ns_old ns_new
730 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
733 choose n m | n `beats` m = n
736 (GRE n pn _) `beats` (GRE m pm _) = n==m && pn `hasBetterProv` pm
738 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
739 is_duplicate (GRE n1 LocalDef _) (GRE n2 LocalDef _) = False
740 is_duplicate (GRE n1 _ _) (GRE n2 _ _) = n1 == n2
743 We treat two bindings of a locally-defined name as a duplicate,
744 because they might be two separate, local defns and we want to report
745 and error for that, {\em not} eliminate a duplicate.
747 On the other hand, if you import the same name from two different
748 import statements, we {\em do} want to eliminate the duplicate, not report
751 If a module imports itself then there might be a local defn and an imported
752 defn of the same name; in this case the names will compare as equal, but
753 will still have different provenances.
756 @unQualInScope@ returns a function that takes a @Name@ and tells whether
757 its unqualified name is in scope. This is put as a boolean flag in
758 the @Name@'s provenance to guide whether or not to print the name qualified
762 unQualInScope :: GlobalRdrEnv -> Name -> Bool
764 = (`elemNameSet` unqual_names)
766 unqual_names :: NameSet
767 unqual_names = foldRdrEnv add emptyNameSet env
768 add rdr_name [GRE name _ _] unquals | isUnqual rdr_name = addOneToNameSet unquals name
769 add _ _ unquals = unquals
773 %************************************************************************
777 %************************************************************************
780 plusAvail (Avail n1) (Avail n2) = Avail n1
781 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
784 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
787 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
788 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
790 emptyAvailEnv = emptyNameEnv
791 unitAvailEnv :: AvailInfo -> AvailEnv
792 unitAvailEnv a = unitNameEnv (availName a) a
794 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
795 plusAvailEnv = plusNameEnv_C plusAvail
797 availEnvElts = nameEnvElts
799 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
800 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
802 availsToNameSet :: [AvailInfo] -> NameSet
803 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
805 availName :: GenAvailInfo name -> name
806 availName (Avail n) = n
807 availName (AvailTC n _) = n
809 availNames :: GenAvailInfo name -> [name]
810 availNames (Avail n) = [n]
811 availNames (AvailTC n ns) = ns
813 -------------------------------------
814 filterAvail :: RdrNameIE -- Wanted
815 -> AvailInfo -- Available
816 -> Maybe AvailInfo -- Resulting available;
817 -- Nothing if (any of the) wanted stuff isn't there
819 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
820 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
821 | otherwise = Nothing
823 is_wanted name = nameOccName name `elem` wanted_occs
824 sub_names_ok = all (`elem` avail_occs) wanted_occs
825 avail_occs = map nameOccName ns
826 wanted_occs = map rdrNameOcc (want:wants)
828 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
831 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
833 filterAvail (IEVar _) avail@(Avail n) = Just avail
834 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
836 wanted n = nameOccName n == occ
838 -- The second equation happens if we import a class op, thus
840 -- where op is a class operation
842 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
843 -- We don't complain even if the IE says T(..), but
844 -- no constrs/class ops of T are available
845 -- Instead that's caught with a warning by the caller
847 filterAvail ie avail = Nothing
849 -------------------------------------
850 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
851 -- Group by module and sort by occurrence
852 -- This keeps the list in canonical order
853 groupAvails this_mod avails
854 = [ (mkSysModuleNameFS fs, sortLt lt avails)
855 | (fs,avails) <- fmToList groupFM
858 groupFM :: FiniteMap FastString Avails
859 -- Deliberately use the FastString so we
860 -- get a canonical ordering
861 groupFM = foldl add emptyFM avails
863 add env avail = addToFM_C combine env mod_fs [avail']
865 mod_fs = moduleNameFS (moduleName avail_mod)
866 avail_mod = case nameModule_maybe (availName avail) of
869 combine old _ = avail':old
870 avail' = sortAvail avail
872 a1 `lt` a2 = occ1 < occ2
874 occ1 = nameOccName (availName a1)
875 occ2 = nameOccName (availName a2)
877 sortAvail :: AvailInfo -> AvailInfo
878 -- Sort the sub-names into canonical order.
879 -- The canonical order has the "main name" at the beginning
880 -- (if it's there at all)
881 sortAvail (Avail n) = Avail n
882 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
883 | otherwise = AvailTC n ( sortLt lt ns)
885 n1 `lt` n2 = nameOccName n1 < nameOccName n2
889 %************************************************************************
891 \subsection{Free variable manipulation}
893 %************************************************************************
897 mapFvRn f xs = mapRn f xs `thenRn` \ stuff ->
899 (ys, fvs_s) = unzip stuff
901 returnRn (ys, plusFVs fvs_s)
905 %************************************************************************
907 \subsection{Envt utility functions}
909 %************************************************************************
912 warnUnusedModules :: [ModuleName] -> RnM d ()
913 warnUnusedModules mods
914 = doptRn Opt_WarnUnusedImports `thenRn` \ warn ->
915 if warn then mapRn_ (addWarnRn . unused_mod) mods
918 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
919 text "is imported, but nothing from it is used",
920 parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
923 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
924 warnUnusedImports names
925 = doptRn Opt_WarnUnusedImports `thenRn` \ warn ->
926 if warn then warnUnusedBinds names else returnRn ()
928 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
929 warnUnusedLocalBinds names
930 = doptRn Opt_WarnUnusedBinds `thenRn` \ warn ->
931 if warn then warnUnusedBinds [(n,LocalDef) | n<-names]
934 warnUnusedMatches names
935 = doptRn Opt_WarnUnusedMatches `thenRn` \ warn ->
936 if warn then warnUnusedGroup [(n,LocalDef) | n<-names]
939 -------------------------
941 warnUnusedBinds :: [(Name,Provenance)] -> RnM d ()
942 warnUnusedBinds names
943 = mapRn_ warnUnusedGroup groups
945 -- Group by provenance
946 groups = equivClasses cmp names
947 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
950 -------------------------
952 warnUnusedGroup :: [(Name,Provenance)] -> RnM d ()
953 warnUnusedGroup names
954 | null filtered_names = returnRn ()
955 | not is_local = returnRn ()
957 = pushSrcLocRn def_loc $
959 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
961 filtered_names = filter reportable names
962 (name1, prov1) = head filtered_names
963 (is_local, def_loc, msg)
965 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
967 NonLocalDef (UserImport mod loc _)
968 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
970 reportable (name,_) = case occNameUserString (nameOccName name) of
973 -- Haskell 98 encourages compilers to suppress warnings about
974 -- unused names in a pattern if they start with "_".
978 addNameClashErrRn rdr_name (np1:nps)
979 = addErrRn (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
980 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
982 msg1 = ptext SLIT("either") <+> mk_ref np1
983 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
984 mk_ref (GRE name prov _) = quotes (ppr name) <> comma <+> pprNameProvenance name prov
986 shadowedNameWarn shadow
987 = hsep [ptext SLIT("This binding for"),
989 ptext SLIT("shadows an existing binding")]
992 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
994 flavour = occNameFlavour (rdrNameOcc name)
996 qualNameErr descriptor (name,loc)
998 addErrRn (hsep [ ptext SLIT("Invalid use of qualified name"),
1003 dupNamesErr descriptor ((name,loc) : dup_things)
1004 = pushSrcLocRn loc $
1005 addErrRn ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1007 (ptext SLIT("in") <+> descriptor))
1009 warnDeprec :: Name -> DeprecTxt -> RnM d ()
1011 = doptRn Opt_WarnDeprecations `thenRn` \ warn_drs ->
1012 if not warn_drs then returnRn () else
1013 addWarnRn (sep [ text (occNameFlavour (nameOccName name)) <+>
1014 quotes (ppr name) <+> text "is deprecated:",