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 FlattenInfo ( namesNeededForFlattening )
15 import RdrHsSyn ( RdrNameIE, RdrNameHsType, extractHsTyRdrTyVars )
16 import RdrName ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
17 mkRdrUnqual, mkRdrQual,
18 lookupRdrEnv, foldRdrEnv, rdrEnvToList, elemRdrEnv,
21 import HsTypes ( hsTyVarName, replaceTyVarName )
22 import HscTypes ( Provenance(..), pprNameProvenance, hasBetterProv,
23 ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), AvailEnv,
24 AvailInfo, Avails, GenAvailInfo(..), NameSupply(..),
25 ModIface(..), GhciMode(..),
26 Deprecations(..), lookupDeprec,
31 getSrcLoc, nameIsLocalOrFrom,
32 mkInternalName, mkExternalName,
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, main_RDR_Unqual,
44 runMainName, 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 )
57 import BasicTypes ( mapIPName )
59 import UniqFM ( lookupWithDefaultUFM )
60 import Maybe ( mapMaybe )
62 import FastString ( FastString )
65 %*********************************************************
67 \subsection{Making new names}
69 %*********************************************************
72 newTopBinder :: Module -> RdrName -> SrcLoc -> RnM d Name
73 -- newTopBinder puts into the cache the binder with the
74 -- module information set correctly. When the decl is later renamed,
75 -- the binding site will thereby get the correct module.
76 -- There maybe occurrences that don't have the correct Module, but
77 -- by the typechecker will propagate the binding definition to all
78 -- the occurrences, so that doesn't matter
80 newTopBinder mod rdr_name loc
81 = -- First check the cache
83 -- There should never be a qualified name in a binding position (except in instance decls)
84 -- The parser doesn't check this because the same parser parses instance decls
85 (if isQual rdr_name then
86 qualNameErr (text "In its declaration") (rdr_name,loc)
91 getNameSupplyRn `thenRn` \ name_supply ->
93 occ = rdrNameOcc rdr_name
94 key = (moduleName mod, occ)
95 cache = nsNames name_supply
97 case lookupFM cache key of
99 -- A hit in the cache! We are at the binding site of the name, and
100 -- this is the moment when we know all about
101 -- a) the Name's host Module (in particular, which
102 -- package it comes from)
103 -- b) its defining SrcLoc
104 -- So we update this info
107 new_name = setNameModuleAndLoc name mod loc
108 new_cache = addToFM cache key new_name
110 setNameSupplyRn (name_supply {nsNames = new_cache}) `thenRn_`
111 -- traceRn (text "newTopBinder: overwrite" <+> ppr new_name) `thenRn_`
114 -- Miss in the cache!
115 -- Build a completely new Name, and put it in the cache
116 -- Even for locally-defined names we use implicitImportProvenance;
117 -- updateProvenances will set it to rights
119 (us', us1) = splitUniqSupply (nsUniqs name_supply)
120 uniq = uniqFromSupply us1
121 new_name = mkExternalName uniq mod occ loc
122 new_cache = addToFM cache key new_name
124 setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
125 -- traceRn (text "newTopBinder: new" <+> ppr new_name) `thenRn_`
129 newGlobalName :: ModuleName -> OccName -> RnM d Name
130 -- Used for *occurrences*. We make a place-holder Name, really just
131 -- to agree on its unique, which gets overwritten when we read in
132 -- the binding occurence later (newTopBinder)
133 -- The place-holder Name doesn't have the right SrcLoc, and its
134 -- Module won't have the right Package either.
136 -- (We have to pass a ModuleName, not a Module, because we may be
137 -- simply looking at an occurrence M.x in an interface file.)
139 -- This means that a renamed program may have incorrect info
140 -- on implicitly-imported occurrences, but the correct info on the
141 -- *binding* declaration. It's the type checker that propagates the
142 -- correct information to all the occurrences.
143 -- Since implicitly-imported names never occur in error messages,
144 -- it doesn't matter that we get the correct info in place till later,
145 -- (but since it affects DLL-ery it does matter that we get it right
147 newGlobalName mod_name occ
148 = getNameSupplyRn `thenRn` \ name_supply ->
150 key = (mod_name, occ)
151 cache = nsNames name_supply
153 case lookupFM cache key of
154 Just name -> -- traceRn (text "newGlobalName: hit" <+> ppr name) `thenRn_`
157 Nothing -> setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache}) `thenRn_`
158 -- traceRn (text "newGlobalName: new" <+> ppr name) `thenRn_`
161 (us', us1) = splitUniqSupply (nsUniqs name_supply)
162 uniq = uniqFromSupply us1
163 mod = mkVanillaModule mod_name
164 name = mkExternalName uniq mod occ noSrcLoc
165 new_cache = addToFM cache key name
167 newIPName rdr_name_ip
168 = getNameSupplyRn `thenRn` \ name_supply ->
170 ipcache = nsIPs name_supply
172 case lookupFM ipcache key of
173 Just name_ip -> returnRn name_ip
174 Nothing -> setNameSupplyRn new_ns `thenRn_`
177 (us', us1) = splitUniqSupply (nsUniqs name_supply)
178 uniq = uniqFromSupply us1
179 name_ip = mapIPName mk_name rdr_name_ip
180 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
181 new_ipcache = addToFM ipcache key name_ip
182 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
184 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
187 %*********************************************************
189 \subsection{Looking up names}
191 %*********************************************************
193 Looking up a name in the RnEnv.
196 lookupBndrRn rdr_name
197 = getLocalNameEnv `thenRn` \ local_env ->
198 case lookupRdrEnv local_env rdr_name of
199 Just name -> returnRn name
200 Nothing -> lookupTopBndrRn rdr_name
202 lookupTopBndrRn rdr_name
203 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
204 -- and there may be several imported 'f's too, which must not confuse us.
205 -- So we have to filter out the non-local ones.
206 -- A separate function (importsFromLocalDecls) reports duplicate top level
207 -- decls, so here it's safe just to choose an arbitrary one.
210 -- This is here just to catch the PrelBase defn of (say) [] and similar
211 -- The parser reads the special syntax and returns an Orig RdrName
212 -- But the global_env contains only Qual RdrNames, so we won't
213 -- find it there; instead just get the name via the Orig route
214 = lookupOrigName rdr_name
217 = getModeRn `thenRn` \ mode ->
218 if isInterfaceMode mode
219 then lookupIfaceName rdr_name
221 getModuleRn `thenRn` \ mod ->
222 getGlobalNameEnv `thenRn` \ global_env ->
223 case lookup_local mod global_env rdr_name of
224 Just name -> returnRn name
225 Nothing -> failWithRn (mkUnboundName rdr_name)
226 (unknownNameErr rdr_name)
228 lookup_local mod global_env rdr_name
229 = case lookupRdrEnv global_env rdr_name of
231 Just gres -> case [n | GRE n _ _ <- gres, nameIsLocalOrFrom mod n] of
236 -- lookupSigOccRn is used for type signatures and pragmas
242 -- It's clear that the 'f' in the signature must refer to A.f
243 -- The Haskell98 report does not stipulate this, but it will!
244 -- So we must treat the 'f' in the signature in the same way
245 -- as the binding occurrence of 'f', using lookupBndrRn
246 lookupSigOccRn :: RdrName -> RnMS Name
247 lookupSigOccRn = lookupBndrRn
249 -- lookupInstDeclBndr is used for the binders in an
250 -- instance declaration. Here we use the class name to
253 lookupInstDeclBndr :: Name -> RdrName -> RnMS Name
254 -- We use the selector name as the binder
255 lookupInstDeclBndr cls_name rdr_name
256 | isOrig rdr_name -- Occurs in derived instances, where we just
257 -- refer diectly to the right method
258 = lookupOrigName rdr_name
261 = getGlobalAvails `thenRn` \ avail_env ->
262 case lookupNameEnv avail_env cls_name of
263 -- The class itself isn't in scope, so cls_name is unboundName
264 -- e.g. import Prelude hiding( Ord )
265 -- instance Ord T where ...
266 -- The program is wrong, but that should not cause a crash.
267 Nothing -> returnRn (mkUnboundName rdr_name)
268 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
269 (n:ns)-> ASSERT( null ns ) returnRn n
270 [] -> failWithRn (mkUnboundName rdr_name)
271 (unknownNameErr rdr_name)
272 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
274 occ = rdrNameOcc rdr_name
276 -- lookupOccRn looks up an occurrence of a RdrName
277 lookupOccRn :: RdrName -> RnMS Name
279 = getLocalNameEnv `thenRn` \ local_env ->
280 case lookupRdrEnv local_env rdr_name of
281 Just name -> returnRn name
282 Nothing -> lookupGlobalOccRn rdr_name
284 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
285 -- environment. It's used only for
286 -- record field names
287 -- class op names in class and instance decls
289 lookupGlobalOccRn rdr_name
290 = getModeRn `thenRn` \ mode ->
291 if (isInterfaceMode mode)
292 then lookupIfaceName rdr_name
295 getGlobalNameEnv `thenRn` \ global_env ->
297 SourceMode -> lookupSrcName global_env rdr_name
300 | not (isQual rdr_name) ->
301 lookupSrcName global_env rdr_name
303 -- We allow qualified names on the command line to refer to
304 -- *any* name exported by any module in scope, just as if
305 -- there was an "import qualified M" declaration for every
308 -- First look up the name in the normal environment. If
309 -- it isn't there, we manufacture a new occurrence of an
312 case lookupRdrEnv global_env rdr_name of
313 Just _ -> lookupSrcName global_env rdr_name
314 Nothing -> lookupQualifiedName rdr_name
316 -- a qualified name on the command line can refer to any module at all: we
317 -- try to load the interface if we don't already have it.
318 lookupQualifiedName :: RdrName -> RnM d Name
319 lookupQualifiedName rdr_name
321 mod = rdrNameModule rdr_name
322 occ = rdrNameOcc rdr_name
324 loadInterface (ppr rdr_name) mod ImportByUser `thenRn` \ iface ->
325 case [ name | (_,avails) <- mi_exports iface,
327 name <- availNames avail,
328 nameOccName name == occ ] of
329 (n:ns) -> ASSERT (null ns) returnRn n
330 _ -> failWithRn (mkUnboundName rdr_name) (unknownNameErr rdr_name)
332 lookupSrcName :: GlobalRdrEnv -> RdrName -> RnM d Name
333 -- NB: passed GlobalEnv explicitly, not necessarily in RnMS monad
334 lookupSrcName global_env rdr_name
335 | isOrig rdr_name -- Can occur in source code too
336 = lookupOrigName rdr_name
339 = case lookupRdrEnv global_env rdr_name of
340 Just [GRE name _ Nothing] -> returnRn name
341 Just [GRE name _ (Just deprec)] -> warnDeprec name deprec `thenRn_`
343 Just stuff@(GRE name _ _ : _) -> addNameClashErrRn rdr_name stuff `thenRn_`
345 Nothing -> failWithRn (mkUnboundName rdr_name)
346 (unknownNameErr rdr_name)
348 lookupOrigName :: RdrName -> RnM d Name
349 lookupOrigName rdr_name
350 = -- NO: ASSERT( isOrig rdr_name )
351 -- Now that .hi-boot files are read by the main parser, they contain
352 -- ordinary qualified names (which we treat as Orig names here).
353 newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
355 lookupIfaceUnqual :: RdrName -> RnM d Name
356 lookupIfaceUnqual rdr_name
357 = ASSERT( isUnqual rdr_name )
358 -- An Unqual is allowed; interface files contain
359 -- unqualified names for locally-defined things, such as
360 -- constructors of a data type.
361 getModuleRn `thenRn ` \ mod ->
362 newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
364 lookupIfaceName :: RdrName -> RnM d Name
365 lookupIfaceName rdr_name
366 | isUnqual rdr_name = lookupIfaceUnqual rdr_name
367 | otherwise = lookupOrigName rdr_name
370 @lookupOrigName@ takes an RdrName representing an {\em original}
371 name, and adds it to the occurrence pool so that it'll be loaded
372 later. This is used when language constructs (such as monad
373 comprehensions, overloaded literals, or deriving clauses) require some
374 stuff to be loaded that isn't explicitly mentioned in the code.
376 This doesn't apply in interface mode, where everything is explicit,
377 but we don't check for this case: it does no harm to record an
378 ``extra'' occurrence and @lookupOrigNames@ isn't used much in
379 interface mode (it's only the @Nothing@ clause of @rnDerivs@ that
380 calls it at all I think).
382 \fbox{{\em Jan 98: this comment is wrong: @rnHsType@ uses it quite a bit.}}
385 lookupOrigNames :: [RdrName] -> RnM d NameSet
386 lookupOrigNames rdr_names
387 = mapRn lookupOrigName rdr_names `thenRn` \ names ->
388 returnRn (mkNameSet names)
391 lookupSysBinder is used for the "system binders" of a type, class, or
392 instance decl. It ensures that the module is set correctly in the
393 name cache, and sets the provenance on the returned name too. The
394 returned name will end up actually in the type, class, or instance.
397 lookupSysBinder rdr_name
398 = ASSERT( isUnqual rdr_name )
399 getModuleRn `thenRn` \ mod ->
400 getSrcLocRn `thenRn` \ loc ->
401 newTopBinder mod rdr_name loc
405 %*********************************************************
407 \subsection{Implicit free vars and sugar names}
409 %*********************************************************
411 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
412 mentioned explicitly, but which might be needed by the type checker.
415 getImplicitStmtFVs -- Compiling a statement
416 = returnRn (mkFVs [printName, bindIOName, returnIOName, failIOName]
417 `plusFV` ubiquitousNames)
418 -- These are all needed implicitly when compiling a statement
419 -- See TcModule.tc_stmts
421 getImplicitModuleFVs decls -- Compiling a module
422 = lookupOrigNames deriv_occs `thenRn` \ deriving_names ->
423 returnRn (deriving_names `plusFV` ubiquitousNames)
425 -- deriv_classes is now a list of HsTypes, so a "normal" one
426 -- appears as a (HsClassP c []). The non-normal ones for the new
427 -- newtype-deriving extension, and they don't require any
428 -- implicit names, so we can silently filter them out.
429 deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
430 HsClassP cls [] <- deriv_classes,
431 occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
433 -- ubiquitous_names are loaded regardless, because
434 -- they are needed in virtually every program
436 = mkFVs [unpackCStringName, unpackCStringFoldrName,
437 unpackCStringUtf8Name, eqStringName]
438 -- Virtually every program has error messages in it somewhere
441 mkFVs [getName unitTyCon, funTyConName, boolTyConName, intTyConName]
442 -- Add occurrences for very frequently used types.
443 -- (e.g. we don't want to be bothered with making funTyCon a
444 -- free var at every function application!)
446 namesNeededForFlattening
447 -- this will be empty unless flattening is activated
449 checkMain ghci_mode mod_name gbl_env
450 -- LOOKUP main IF WE'RE IN MODULE Main
451 -- The main point of this is to drag in the declaration for 'main',
452 -- its in another module, and for the Prelude function 'runMain',
453 -- so that the type checker will find them
455 -- We have to return the main_name separately, because it's a
456 -- bona fide 'use', and should be recorded as such, but the others
458 | mod_name /= mAIN_Name
459 = returnRn (Nothing, emptyFVs, emptyFVs)
461 | not (main_RDR_Unqual `elemRdrEnv` gbl_env)
462 = complain_no_main `thenRn_`
463 returnRn (Nothing, emptyFVs, emptyFVs)
466 = lookupSrcName gbl_env main_RDR_Unqual `thenRn` \ main_name ->
467 returnRn (Just main_name, unitFV main_name, unitFV runMainName)
470 complain_no_main | ghci_mode == Interactive = addWarnRn noMainMsg
471 | otherwise = addErrRn noMainMsg
472 -- In interactive mode, only warn about the absence of main
475 %************************************************************************
477 \subsection{Re-bindable desugaring names}
479 %************************************************************************
481 Haskell 98 says that when you say "3" you get the "fromInteger" from the
482 Standard Prelude, regardless of what is in scope. However, to experiment
483 with having a language that is less coupled to the standard prelude, we're
484 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
485 happens to be in scope. Then you can
487 import MyPrelude as Prelude
488 to get the desired effect.
490 At the moment this just happens for
491 * fromInteger, fromRational on literals (in expressions and patterns)
492 * negate (in expressions)
493 * minus (arising from n+k patterns)
495 We store the relevant Name in the HsSyn tree, in
496 * HsIntegral/HsFractional
499 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
500 fromRationalName etc), but the renamer changes this to the appropriate user
501 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
504 lookupSyntaxName :: Name -- The standard name
505 -> RnMS Name -- Possibly a non-standard name
506 lookupSyntaxName std_name
507 = doptRn Opt_NoImplicitPrelude `thenRn` \ no_prelude ->
508 if not no_prelude then
509 returnRn std_name -- Normal case
512 rdr_name = mkRdrUnqual (nameOccName std_name)
513 -- Get the similarly named thing from the local environment
519 %*********************************************************
523 %*********************************************************
526 newLocalsRn :: [(RdrName,SrcLoc)]
528 newLocalsRn rdr_names_w_loc
529 = getNameSupplyRn `thenRn` \ name_supply ->
531 (us', us1) = splitUniqSupply (nsUniqs name_supply)
532 uniqs = uniqsFromSupply us1
533 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
534 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
537 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
541 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
542 -> [(RdrName,SrcLoc)]
543 -> ([Name] -> RnMS a)
545 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
546 = getModeRn `thenRn` \ mode ->
547 getLocalNameEnv `thenRn` \ local_env ->
548 getGlobalNameEnv `thenRn` \ global_env ->
550 -- Check for duplicate names
551 checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
553 -- Warn about shadowing, but only in source modules
555 check_shadow (rdr_name,loc)
556 | rdr_name `elemRdrEnv` local_env
557 || rdr_name `elemRdrEnv` global_env
558 = pushSrcLocRn loc $ addWarnRn (shadowedNameWarn rdr_name)
564 SourceMode -> ifOptRn Opt_WarnNameShadowing $
565 mapRn_ check_shadow rdr_names_w_loc
569 newLocalsRn rdr_names_w_loc `thenRn` \ names ->
571 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
573 setLocalNameEnv new_local_env (enclosed_scope names)
575 bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
576 -- A specialised variant when renaming stuff from interface
577 -- files (of which there is a lot)
579 -- * no checks for shadowing
581 -- * deal with free vars
582 bindCoreLocalRn rdr_name enclosed_scope
583 = getSrcLocRn `thenRn` \ loc ->
584 getLocalNameEnv `thenRn` \ name_env ->
585 getNameSupplyRn `thenRn` \ name_supply ->
587 (us', us1) = splitUniqSupply (nsUniqs name_supply)
588 uniq = uniqFromSupply us1
589 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
591 setNameSupplyRn (name_supply {nsUniqs = us'}) `thenRn_`
593 new_name_env = extendRdrEnv name_env rdr_name name
595 setLocalNameEnv new_name_env (enclosed_scope name)
597 bindCoreLocalsRn [] thing_inside = thing_inside []
598 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
599 bindCoreLocalsRn bs $ \ names' ->
600 thing_inside (name':names')
602 bindLocalNames names enclosed_scope
603 = getLocalNameEnv `thenRn` \ name_env ->
604 setLocalNameEnv (extendLocalRdrEnv name_env names)
607 bindLocalNamesFV names enclosed_scope
608 = bindLocalNames names $
609 enclosed_scope `thenRn` \ (thing, fvs) ->
610 returnRn (thing, delListFromNameSet fvs names)
613 -------------------------------------
614 bindLocalRn doc rdr_name enclosed_scope
615 = getSrcLocRn `thenRn` \ loc ->
616 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
620 bindLocalsRn doc rdr_names enclosed_scope
621 = getSrcLocRn `thenRn` \ loc ->
622 bindLocatedLocalsRn doc
623 (rdr_names `zip` repeat loc)
626 -- binLocalsFVRn is the same as bindLocalsRn
627 -- except that it deals with free vars
628 bindLocalsFVRn doc rdr_names enclosed_scope
629 = bindLocalsRn doc rdr_names $ \ names ->
630 enclosed_scope names `thenRn` \ (thing, fvs) ->
631 returnRn (thing, delListFromNameSet fvs names)
633 -------------------------------------
634 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
635 -- This tiresome function is used only in rnSourceDecl on InstDecl
636 extendTyVarEnvFVRn tyvars enclosed_scope
637 = bindLocalNames tyvars enclosed_scope `thenRn` \ (thing, fvs) ->
638 returnRn (thing, delListFromNameSet fvs tyvars)
640 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
641 -> ([HsTyVarBndr Name] -> RnMS a)
643 bindTyVarsRn doc_str tyvar_names enclosed_scope
644 = getSrcLocRn `thenRn` \ loc ->
646 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
648 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
649 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
651 bindPatSigTyVars :: [RdrNameHsType]
652 -> RnMS (a, FreeVars)
653 -> RnMS (a, FreeVars)
654 -- Find the type variables in the pattern type
655 -- signatures that must be brought into scope
657 bindPatSigTyVars tys enclosed_scope
658 = getLocalNameEnv `thenRn` \ name_env ->
659 getSrcLocRn `thenRn` \ loc ->
661 forall_tyvars = nub [ tv | ty <- tys,
662 tv <- extractHsTyRdrTyVars ty,
663 not (tv `elemFM` name_env)
665 -- The 'nub' is important. For example:
666 -- f (x :: t) (y :: t) = ....
667 -- We don't want to complain about binding t twice!
669 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
670 doc_sig = text "In a pattern type-signature"
672 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
673 enclosed_scope `thenRn` \ (thing, fvs) ->
674 returnRn (thing, delListFromNameSet fvs names)
677 -------------------------------------
678 checkDupOrQualNames, checkDupNames :: SDoc
679 -> [(RdrName, SrcLoc)]
681 -- Works in any variant of the renamer monad
683 checkDupOrQualNames doc_str rdr_names_w_loc
684 = -- Check for use of qualified names
685 mapRn_ (qualNameErr doc_str) quals `thenRn_`
686 checkDupNames doc_str rdr_names_w_loc
688 quals = filter (isQual . fst) rdr_names_w_loc
690 checkDupNames doc_str rdr_names_w_loc
691 = -- Check for duplicated names in a binding group
692 mapRn_ (dupNamesErr doc_str) dups
694 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
698 %************************************************************************
700 \subsection{GlobalRdrEnv}
702 %************************************************************************
705 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
706 -> Bool -- True <=> want unqualified import
707 -> (Name -> Provenance)
708 -> Avails -- Whats imported
712 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
715 -- Make the name environment. We're talking about a
716 -- single module here, so there must be no name clashes.
717 -- In practice there only ever will be if it's the module
720 -- Add qualified names for the things that are available
721 -- (Qualified names are always imported)
722 gbl_env1 = foldl add_avail emptyRdrEnv avails
724 -- Add unqualified names
725 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
726 | otherwise = gbl_env1
728 add_unqual env (qual_name, elts)
729 = foldl add_one env elts
731 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
732 unqual_name = unqualifyRdrName qual_name
733 -- The qualified import should only have added one
734 -- binding for each qualified name! But if there's an error in
735 -- the module (multiple bindings for the same name) we may get
736 -- duplicates. So the simple thing is to do the fold.
738 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
739 add_avail env avail = foldl add_name env (availNames avail)
741 add_name env name -- Add qualified name only
742 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
744 occ = nameOccName name
745 elt = GRE name (mk_provenance name) (lookupDeprec deprecs name)
749 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
750 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
752 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
753 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
755 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
756 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
758 combine_globals :: [GlobalRdrElt] -- Old
759 -> [GlobalRdrElt] -- New
761 combine_globals ns_old ns_new -- ns_new is often short
762 = foldr add ns_old ns_new
764 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
767 choose n m | n `beats` m = n
770 (GRE n pn _) `beats` (GRE m pm _) = n==m && pn `hasBetterProv` pm
772 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
773 is_duplicate (GRE n1 LocalDef _) (GRE n2 LocalDef _) = False
774 is_duplicate (GRE n1 _ _) (GRE n2 _ _) = n1 == n2
777 We treat two bindings of a locally-defined name as a duplicate,
778 because they might be two separate, local defns and we want to report
779 and error for that, {\em not} eliminate a duplicate.
781 On the other hand, if you import the same name from two different
782 import statements, we {\em do} want to eliminate the duplicate, not report
785 If a module imports itself then there might be a local defn and an imported
786 defn of the same name; in this case the names will compare as equal, but
787 will still have different provenances.
790 @unQualInScope@ returns a function that takes a @Name@ and tells whether
791 its unqualified name is in scope. This is put as a boolean flag in
792 the @Name@'s provenance to guide whether or not to print the name qualified
796 unQualInScope :: GlobalRdrEnv -> Name -> Bool
797 -- True if 'f' is in scope, and has only one binding,
798 -- and the thing it is bound to is the name we are looking for
799 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
801 -- This fn is only efficient if the shared
802 -- partial application is used a lot.
804 = (`elemNameSet` unqual_names)
806 unqual_names :: NameSet
807 unqual_names = foldRdrEnv add emptyNameSet env
808 add rdr_name [GRE name _ _] unquals | isUnqual rdr_name = addOneToNameSet unquals name
809 add _ _ unquals = unquals
813 %************************************************************************
817 %************************************************************************
820 plusAvail (Avail n1) (Avail n2) = Avail n1
821 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
824 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
827 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
828 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
830 unitAvailEnv :: AvailInfo -> AvailEnv
831 unitAvailEnv a = unitNameEnv (availName a) a
833 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
834 plusAvailEnv = plusNameEnv_C plusAvail
836 availEnvElts = nameEnvElts
838 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
839 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
841 availsToNameSet :: [AvailInfo] -> NameSet
842 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
844 availName :: GenAvailInfo name -> name
845 availName (Avail n) = n
846 availName (AvailTC n _) = n
848 availNames :: GenAvailInfo name -> [name]
849 availNames (Avail n) = [n]
850 availNames (AvailTC n ns) = ns
852 -------------------------------------
853 filterAvail :: RdrNameIE -- Wanted
854 -> AvailInfo -- Available
855 -> Maybe AvailInfo -- Resulting available;
856 -- Nothing if (any of the) wanted stuff isn't there
858 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
859 | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
860 | otherwise = Nothing
862 is_wanted name = nameOccName name `elem` wanted_occs
863 sub_names_ok = all (`elem` avail_occs) wanted_occs
864 avail_occs = map nameOccName ns
865 wanted_occs = map rdrNameOcc (want:wants)
867 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
870 filterAvail (IEThingAbs _) avail@(Avail n) = Just avail -- Type synonyms
872 filterAvail (IEVar _) avail@(Avail n) = Just avail
873 filterAvail (IEVar v) avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
875 wanted n = nameOccName n == occ
877 -- The second equation happens if we import a class op, thus
879 -- where op is a class operation
881 filterAvail (IEThingAll _) avail@(AvailTC _ _) = Just avail
882 -- We don't complain even if the IE says T(..), but
883 -- no constrs/class ops of T are available
884 -- Instead that's caught with a warning by the caller
886 filterAvail ie avail = Nothing
888 -------------------------------------
889 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
890 -- Group by module and sort by occurrence
891 -- This keeps the list in canonical order
892 groupAvails this_mod avails
893 = [ (mkSysModuleNameFS fs, sortLt lt avails)
894 | (fs,avails) <- fmToList groupFM
897 groupFM :: FiniteMap FastString Avails
898 -- Deliberately use the FastString so we
899 -- get a canonical ordering
900 groupFM = foldl add emptyFM avails
902 add env avail = addToFM_C combine env mod_fs [avail']
904 mod_fs = moduleNameFS (moduleName avail_mod)
905 avail_mod = case nameModule_maybe (availName avail) of
908 combine old _ = avail':old
909 avail' = sortAvail avail
911 a1 `lt` a2 = occ1 < occ2
913 occ1 = nameOccName (availName a1)
914 occ2 = nameOccName (availName a2)
916 sortAvail :: AvailInfo -> AvailInfo
917 -- Sort the sub-names into canonical order.
918 -- The canonical order has the "main name" at the beginning
919 -- (if it's there at all)
920 sortAvail (Avail n) = Avail n
921 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
922 | otherwise = AvailTC n ( sortLt lt ns)
924 n1 `lt` n2 = nameOccName n1 < nameOccName n2
928 pruneAvails :: (Name -> Bool) -- Keep if this is True
931 pruneAvails keep avails
932 = mapMaybe del avails
934 del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
935 del (Avail n) | keep n = Just (Avail n)
936 | otherwise = Nothing
937 del (AvailTC n ns) | null ns' = Nothing
938 | otherwise = Just (AvailTC n ns')
943 %************************************************************************
945 \subsection{Free variable manipulation}
947 %************************************************************************
951 mapFvRn f xs = mapRn f xs `thenRn` \ stuff ->
953 (ys, fvs_s) = unzip stuff
955 returnRn (ys, plusFVs fvs_s)
959 %************************************************************************
961 \subsection{Envt utility functions}
963 %************************************************************************
966 warnUnusedModules :: [ModuleName] -> RnM d ()
967 warnUnusedModules mods
968 = ifOptRn Opt_WarnUnusedImports (mapRn_ (addWarnRn . unused_mod) mods)
970 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
971 text "is imported, but nothing from it is used",
972 parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
975 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
976 warnUnusedImports names
977 = ifOptRn Opt_WarnUnusedImports (warnUnusedBinds names)
979 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
980 warnUnusedLocalBinds names
981 = ifOptRn Opt_WarnUnusedBinds (warnUnusedBinds [(n,LocalDef) | n<-names])
983 warnUnusedMatches names
984 = ifOptRn Opt_WarnUnusedMatches (warnUnusedGroup [(n,LocalDef) | n<-names])
986 -------------------------
988 warnUnusedBinds :: [(Name,Provenance)] -> RnM d ()
989 warnUnusedBinds names
990 = mapRn_ warnUnusedGroup groups
992 -- Group by provenance
993 groups = equivClasses cmp names
994 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
997 -------------------------
999 warnUnusedGroup :: [(Name,Provenance)] -> RnM d ()
1000 warnUnusedGroup names
1001 | null filtered_names = returnRn ()
1002 | not is_local = returnRn ()
1004 = pushSrcLocRn def_loc $
1006 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
1008 filtered_names = filter reportable names
1009 (name1, prov1) = head filtered_names
1010 (is_local, def_loc, msg)
1012 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
1014 NonLocalDef (UserImport mod loc _)
1015 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
1017 reportable (name,_) = case occNameUserString (nameOccName name) of
1020 -- Haskell 98 encourages compilers to suppress warnings about
1021 -- unused names in a pattern if they start with "_".
1025 addNameClashErrRn rdr_name (np1:nps)
1026 = addErrRn (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1027 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1029 msg1 = ptext SLIT("either") <+> mk_ref np1
1030 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1031 mk_ref (GRE name prov _) = quotes (ppr name) <> comma <+> pprNameProvenance name prov
1033 shadowedNameWarn shadow
1034 = hsep [ptext SLIT("This binding for"),
1035 quotes (ppr shadow),
1036 ptext SLIT("shadows an existing binding")]
1038 noMainMsg = ptext SLIT("No 'main' defined in module Main")
1041 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1043 flavour = occNameFlavour (rdrNameOcc name)
1045 qualNameErr descriptor (name,loc)
1046 = pushSrcLocRn loc $
1047 addErrRn (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1050 dupNamesErr descriptor ((name,loc) : dup_things)
1051 = pushSrcLocRn loc $
1052 addErrRn ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1056 warnDeprec :: Name -> DeprecTxt -> RnM d ()
1058 = ifOptRn Opt_WarnDeprecations $
1059 addWarnRn (sep [ text (occNameFlavour (nameOccName name)) <+>
1060 quotes (ppr name) <+> text "is deprecated:",