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( loadInterface )
13 import FlattenInfo ( namesNeededForFlattening )
15 import RdrHsSyn ( RdrNameHsType, RdrNameFixitySig, extractHsTyRdrTyVars )
16 import RdrName ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
17 mkRdrUnqual, mkRdrQual, setRdrNameSpace, rdrNameOcc,
18 lookupRdrEnv, rdrEnvToList, elemRdrEnv,
19 extendRdrEnv, addListToRdrEnv, emptyRdrEnv,
20 isExact_maybe, unqualifyRdrName
22 import HsTypes ( hsTyVarName, replaceTyVarName )
23 import HscTypes ( Provenance(..), pprNameProvenance, hasBetterProv,
24 ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..),
25 GenAvailInfo(..), AvailInfo, Avails,
26 ModIface(..), NameCache(..), OrigNameCache,
27 Deprecations(..), lookupDeprec, isLocalGRE,
28 extendLocalRdrEnv, availName, availNames,
32 import Name ( Name, getName, nameIsLocalOrFrom,
33 isWiredInName, mkInternalName, mkExternalName, mkIPName,
34 nameSrcLoc, nameOccName, setNameSrcLoc, nameModule )
36 import OccName ( OccName, tcName, isDataOcc, occNameUserString, occNameFlavour,
38 import Module ( Module, ModuleName, moduleName, mkHomeModule,
39 lookupModuleEnv, lookupModuleEnvByName, extendModuleEnv_C )
40 import PrelNames ( mkUnboundName, intTyConName,
41 boolTyConName, funTyConName,
42 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
43 eqStringName, printName,
44 bindIOName, returnIOName, failIOName, thenIOName
47 import DsMeta ( templateHaskellNames, qTyConName )
49 import TysWiredIn ( unitTyCon ) -- A little odd
50 import Finder ( findModule )
53 import SrcLoc ( SrcLoc, importedSrcLoc )
55 import ListSetOps ( removeDups, equivClasses )
56 import BasicTypes ( mapIPName, FixitySig(..) )
59 import FastString ( FastString )
62 %*********************************************************
64 \subsection{Making new names}
66 %*********************************************************
69 newTopBinder :: Module -> RdrName -> SrcLoc -> TcRn m Name
70 newTopBinder mod rdr_name loc
71 | Just name <- isExact_maybe rdr_name
75 = ASSERT( not (isOrig rdr_name) || rdrNameModule rdr_name == moduleName mod )
76 -- When reading External Core we get Orig names as binders,
77 -- but they should agree with the module gotten from the monad
78 newGlobalName mod (rdrNameOcc rdr_name) loc
80 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
81 newGlobalName mod occ loc
82 = -- First check the cache
83 getNameCache `thenM` \ name_supply ->
84 case lookupOrigNameCache (nsNames name_supply) mod occ of
86 -- A hit in the cache! We are at the binding site of the name.
87 -- This is the moment when we know the defining SrcLoc
88 -- of the Name, so we set the SrcLoc of the name we return.
90 -- Main reason: then (bogus) multiple bindings of the same Name
91 -- get different SrcLocs can can be reported as such.
93 -- Possible other reason: it might be in the cache because we
94 -- encountered an occurrence before the binding site for an
95 -- implicitly-imported Name. Perhaps the current SrcLoc is
96 -- better... but not really: it'll still just say 'imported'
98 -- IMPORTANT: Don't mess with wired-in names.
99 -- Their wired-in-ness is in the SrcLoc
101 Just name | isWiredInName name -> returnM name
102 | otherwise -> returnM (setNameSrcLoc name loc)
104 -- Miss in the cache!
105 -- Build a completely new Name, and put it in the cache
106 Nothing -> addNewName name_supply mod occ loc
108 -- Look up a "system name" in the name cache.
109 -- This is done by the type checker...
110 lookupSysName :: Name -- Base name
111 -> (OccName -> OccName) -- Occurrence name modifier
112 -> TcRn m Name -- System name
113 lookupSysName base_name mk_sys_occ
114 = newGlobalName (nameModule base_name)
115 (mk_sys_occ (nameOccName base_name))
116 (nameSrcLoc base_name)
119 newGlobalNameFromRdrName rdr_name -- Qualified original name
120 = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
122 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
123 -- This one starts with a ModuleName, not a Module, because
124 -- we may be simply looking at an occurrence M.x in an interface file.
126 -- Used for *occurrences*. Even if we get a miss in the
127 -- original-name cache, we make a new External Name.
128 -- We get its Module either from the OrigNameCache, or (if this
129 -- is the first Name from that module) from the Finder
131 -- In the case of a miss, we have to make up the SrcLoc, but that's
132 -- OK: it must be an implicitly-imported Name, and that never occurs
133 -- in an error message.
135 newGlobalName2 mod_name occ
136 = getNameCache `thenM` \ name_supply ->
138 new_name mod = addNewName name_supply mod occ importedSrcLoc
140 case lookupModuleEnvByName (nsNames name_supply) mod_name of
141 Just (mod, occ_env) ->
142 -- There are some names from this module already
143 -- Next, look up in the OccNameEnv
144 case lookupFM occ_env occ of
145 Just name -> returnM name
146 Nothing -> new_name mod
148 Nothing -> -- No names from this module yet
149 ioToTcRn (findModule mod_name) `thenM` \ mb_loc ->
151 Right (mod, _) -> new_name mod
153 getDOpts `thenM` \ dflags ->
154 addErr (noIfaceErr dflags mod_name False files) `thenM_`
155 -- Things have really gone wrong at this point,
156 -- so having the wrong package info in the
157 -- Module is the least of our worries.
158 new_name (mkHomeModule mod_name)
161 newIPName rdr_name_ip
162 = getNameCache `thenM` \ name_supply ->
164 ipcache = nsIPs name_supply
166 case lookupFM ipcache key of
167 Just name_ip -> returnM name_ip
168 Nothing -> setNameCache new_ns `thenM_`
171 (us', us1) = splitUniqSupply (nsUniqs name_supply)
172 uniq = uniqFromSupply us1
173 name_ip = mapIPName mk_name rdr_name_ip
174 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
175 new_ipcache = addToFM ipcache key name_ip
176 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
178 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
180 -- A local helper function
181 addNewName name_supply mod occ loc
182 = setNameCache new_name_supply `thenM_`
185 (new_name_supply, name) = newExternalName name_supply mod occ loc
188 newExternalName :: NameCache -> Module -> OccName -> SrcLoc
190 -- Allocate a new unique, manufacture a new External Name,
191 -- put it in the cache, and return the two
192 newExternalName name_supply mod occ loc
193 = (new_name_supply, name)
195 (us', us1) = splitUniqSupply (nsUniqs name_supply)
196 uniq = uniqFromSupply us1
197 name = mkExternalName uniq mod occ loc
198 new_cache = extend_name_cache (nsNames name_supply) mod occ name
199 new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
201 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
202 lookupOrigNameCache nc mod occ
203 = case lookupModuleEnv nc mod of
205 Just (_, occ_env) -> lookupFM occ_env occ
207 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
208 extendOrigNameCache nc name
209 = extend_name_cache nc (nameModule name) (nameOccName name) name
211 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
212 extend_name_cache nc mod occ name
213 = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
215 combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
218 %*********************************************************
220 \subsection{Looking up names}
222 %*********************************************************
224 Looking up a name in the RnEnv.
227 lookupBndrRn rdr_name
228 = getLocalRdrEnv `thenM` \ local_env ->
229 case lookupRdrEnv local_env rdr_name of
230 Just name -> returnM name
231 Nothing -> lookupTopBndrRn rdr_name
233 lookupTopBndrRn rdr_name
234 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
235 -- and there may be several imported 'f's too, which must not confuse us.
236 -- So we have to filter out the non-local ones.
237 -- A separate function (importsFromLocalDecls) reports duplicate top level
238 -- decls, so here it's safe just to choose an arbitrary one.
240 -- There should never be a qualified name in a binding position in Haskell,
241 -- but there can be if we have read in an external-Core file.
242 -- The Haskell parser checks for the illegal qualified name in Haskell
243 -- source files, so we don't need to do so here.
245 = getModeRn `thenM` \ mode ->
248 getSrcLocM `thenM` \ loc ->
249 newTopBinder mod rdr_name loc
251 other -> lookupTopSrcBndr rdr_name
253 lookupTopSrcBndr :: RdrName -> TcRn m Name
254 lookupTopSrcBndr rdr_name
255 = lookupTopSrcBndr_maybe rdr_name `thenM` \ maybe_name ->
257 Just name -> returnM name
258 Nothing -> unboundName rdr_name
261 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
262 -- Look up a source-code binder
264 -- Ignores imported names; for example, this is OK:
266 -- infix 9 f -- The 'f' here does not need to be qualified
267 -- f x = x -- Nor here, of course
269 lookupTopSrcBndr_maybe rdr_name
270 | Just name <- isExact_maybe rdr_name
271 -- This is here just to catch the PrelBase defn of (say) [] and similar
272 -- The parser reads the special syntax and returns an Exact RdrName
273 -- But the global_env contains only Qual RdrNames, so we won't
274 -- find it there; instead just get the name via the Orig route
276 -- We are at a binding site for the name, so check first that it
277 -- the current module is the correct one; otherwise GHC can get
278 -- very confused indeed. This test rejects code like
279 -- data T = (,) Int Int
280 -- unless we are in GHC.Tup
281 = getModule `thenM` \ mod ->
282 checkErr (moduleName mod == moduleName (nameModule name))
283 (badOrigBinding rdr_name) `thenM_`
287 = getGlobalRdrEnv `thenM` \ global_env ->
288 case lookupRdrEnv global_env rdr_name of
289 Nothing -> returnM Nothing
290 Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
291 [] -> returnM Nothing
292 (n:ns) -> returnM (Just n)
295 -- lookupSigOccRn is used for type signatures and pragmas
301 -- It's clear that the 'f' in the signature must refer to A.f
302 -- The Haskell98 report does not stipulate this, but it will!
303 -- So we must treat the 'f' in the signature in the same way
304 -- as the binding occurrence of 'f', using lookupBndrRn
305 lookupSigOccRn :: RdrName -> RnM Name
306 lookupSigOccRn = lookupBndrRn
308 -- lookupInstDeclBndr is used for the binders in an
309 -- instance declaration. Here we use the class name to
312 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
313 -- We use the selector name as the binder
314 lookupInstDeclBndr cls_name rdr_name
316 = -- Find all the things the class op name maps to
317 -- and pick the one with the right parent name
318 getGblEnv `thenM` \ gbl_env ->
320 avail_env = imp_env (tcg_imports gbl_env)
322 case lookupAvailEnv avail_env cls_name of
324 -- If the class itself isn't in scope, then cls_name will
325 -- be unboundName, and there'll already be an error for
326 -- that in the error list. Example:
327 -- e.g. import Prelude hiding( Ord )
328 -- instance Ord T where ...
329 -- The program is wrong, but that should not cause a crash.
330 returnM (mkUnboundName rdr_name)
332 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
333 (n:ns)-> ASSERT( null ns ) returnM n
334 [] -> unboundName rdr_name
336 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
339 | otherwise -- Occurs in derived instances, where we just
340 -- refer directly to the right method, and avail_env
342 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
343 -- NB: qualified names are rejected by the parser
344 lookupOrigName rdr_name
347 occ = rdrNameOcc rdr_name
349 lookupSysBndr :: RdrName -> RnM Name
350 -- Used for the 'system binders' in a data type or class declaration
351 -- Do *not* look up in the RdrEnv; these system binders are never in scope
352 -- Instead, get the module from the monad... but remember that
353 -- where the module is depends on whether we are renaming source or
354 -- interface file stuff
355 lookupSysBndr rdr_name
356 = getSrcLocM `thenM` \ loc ->
357 getModeRn `thenM` \ mode ->
359 InterfaceMode mod -> newTopBinder mod rdr_name loc
360 other -> getModule `thenM` \ mod ->
361 newTopBinder mod rdr_name loc
363 -- lookupOccRn looks up an occurrence of a RdrName
364 lookupOccRn :: RdrName -> RnM Name
366 = getLocalRdrEnv `thenM` \ local_env ->
367 case lookupRdrEnv local_env rdr_name of
368 Just name -> returnM name
369 Nothing -> lookupGlobalOccRn rdr_name
371 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
372 -- environment. It's used only for
373 -- record field names
374 -- class op names in class and instance decls
376 lookupGlobalOccRn rdr_name
377 = getModeRn `thenM` \ mode ->
379 InterfaceMode mod -> lookupIfaceName mod rdr_name
380 SourceMode -> lookupSrcName rdr_name
383 | not (isQual rdr_name) ->
384 lookupSrcName rdr_name
386 -- We allow qualified names on the command line to refer to
387 -- *any* name exported by any module in scope, just as if
388 -- there was an "import qualified M" declaration for every
391 -- First look up the name in the normal environment. If
392 -- it isn't there, we manufacture a new occurrence of an
395 lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
397 Just name -> returnM name
398 Nothing -> lookupQualifiedName rdr_name
400 -- A qualified name on the command line can refer to any module at all: we
401 -- try to load the interface if we don't already have it.
402 lookupQualifiedName :: RdrName -> TcRn m Name
403 lookupQualifiedName rdr_name
405 mod = rdrNameModule rdr_name
406 occ = rdrNameOcc rdr_name
408 loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
409 case [ name | (_,avails) <- mi_exports iface,
411 name <- availNames avail,
412 nameOccName name == occ ] of
413 (n:ns) -> ASSERT (null ns) returnM n
414 _ -> unboundName rdr_name
416 lookupSrcName :: RdrName -> TcRn m Name
417 lookupSrcName rdr_name
418 = lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
420 Nothing -> unboundName rdr_name
421 Just name -> returnM name
423 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
424 lookupSrcName_maybe rdr_name
425 | Just name <- isExact_maybe rdr_name -- Can occur in source code too
426 = returnM (Just name)
428 | isOrig rdr_name -- An original name
429 = newGlobalNameFromRdrName rdr_name `thenM` \ name ->
433 = lookupGRE rdr_name `thenM` \ mb_gre ->
435 Nothing -> returnM Nothing
436 Just gre -> returnM (Just (gre_name gre))
438 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
440 = getGlobalRdrEnv `thenM` \ global_env ->
441 case lookupRdrEnv global_env rdr_name of
442 Just [gre] -> case gre_deprec gre of
443 Nothing -> returnM (Just gre)
444 Just _ -> warnDeprec gre `thenM_`
446 Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff `thenM_`
448 Nothing -> return Nothing
450 lookupIfaceName :: Module -> RdrName -> TcRn m Name
451 -- An Unqual is allowed; interface files contain
452 -- unqualified names for locally-defined things, such as
453 -- constructors of a data type.
454 lookupIfaceName mod rdr_name
455 | isUnqual rdr_name = newGlobalName mod (rdrNameOcc rdr_name) importedSrcLoc
456 | otherwise = lookupOrigName rdr_name
458 lookupOrigName :: RdrName -> TcRn m Name
459 -- Just for original or exact names
460 lookupOrigName rdr_name
461 | Just n <- isExact_maybe rdr_name
462 -- This happens in derived code, which we
463 -- rename in InterfaceMode
466 | otherwise -- Usually Orig, but can be a Qual when
467 -- we are reading a .hi-boot file
468 = newGlobalNameFromRdrName rdr_name
471 dataTcOccs :: RdrName -> [RdrName]
472 -- If the input is a data constructor, return both it and a type
473 -- constructor. This is useful when we aren't sure which we are
476 | isDataOcc occ = [rdr_name, rdr_name_tc]
477 | otherwise = [rdr_name]
479 occ = rdrNameOcc rdr_name
480 rdr_name_tc = setRdrNameSpace rdr_name tcName
484 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
485 returnM (mkUnboundName rdr_name)
488 %*********************************************************
492 %*********************************************************
495 --------------------------------
496 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
497 -- Used for nested fixity decls
498 -- No need to worry about type constructors here,
499 -- Should check for duplicates but we don't
500 bindLocalFixities fixes thing_inside
501 | null fixes = thing_inside
502 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
503 extendFixityEnv new_bit thing_inside
505 rn_sig (FixitySig v fix src_loc)
506 = addSrcLoc src_loc $
507 lookupSigOccRn v `thenM` \ new_v ->
508 returnM (new_v, FixitySig new_v fix src_loc)
511 --------------------------------
512 lookupFixity is a bit strange.
514 * Nested local fixity decls are put in the local fixity env, which we
515 find with getFixtyEnv
517 * Imported fixities are found in the HIT or PIT
519 * Top-level fixity decls in this module may be for Names that are
520 either Global (constructors, class operations)
521 or Local/Exported (everything else)
522 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
523 We put them all in the local fixity environment
526 lookupFixityRn :: Name -> RnM Fixity
528 = getModule `thenM` \ this_mod ->
529 if nameIsLocalOrFrom this_mod name
530 then -- It's defined in this module
531 getFixityEnv `thenM` \ local_fix_env ->
532 returnM (lookupFixity local_fix_env name)
534 else -- It's imported
535 -- For imported names, we have to get their fixities by doing a
536 -- loadHomeInterface, and consulting the Ifaces that comes back
537 -- from that, because the interface file for the Name might not
538 -- have been loaded yet. Why not? Suppose you import module A,
539 -- which exports a function 'f', thus;
540 -- module CurrentModule where
542 -- module A( f ) where
544 -- Then B isn't loaded right away (after all, it's possible that
545 -- nothing from B will be used). When we come across a use of
546 -- 'f', we need to know its fixity, and it's then, and only
547 -- then, that we load B.hi. That is what's happening here.
548 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
549 returnM (lookupFixity (mi_fixities iface) name)
551 doc = ptext SLIT("Checking fixity for") <+> ppr name
552 name_mod = moduleName (nameModule name)
556 %*********************************************************
558 \subsection{Implicit free vars and sugar names}
560 %*********************************************************
562 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
563 mentioned explicitly, but which might be needed by the type checker.
566 implicitStmtFVs source_fvs -- Compiling a statement
567 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
569 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName]
570 -- These are all needed implicitly when compiling a statement
571 -- See TcModule.tc_stmts
573 implicitModuleFVs source_fvs
574 = mkTemplateHaskellFVs source_fvs `plusFV`
575 namesNeededForFlattening `plusFV`
579 thProxyName :: NameSet
580 mkTemplateHaskellFVs :: NameSet -> NameSet
581 -- This is a bit of a hack. When we see the Template-Haskell construct
583 -- we are going to need lots of the ``smart constructors'' defined in
584 -- the main Template Haskell data type module. Rather than treat them
585 -- all as free vars at every occurrence site, we just make the Q type
586 -- consructor a free var.... and then use that here to haul in the others
589 --------------- Template Haskell enabled --------------
590 thProxyName = unitFV qTyConName
592 mkTemplateHaskellFVs source_fvs
593 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
594 | otherwise = emptyFVs
597 --------------- Template Haskell disabled --------------
599 thProxyName = emptyFVs
600 mkTemplateHaskellFVs source_fvs = emptyFVs
602 --------------------------------------------------------
604 -- ubiquitous_names are loaded regardless, because
605 -- they are needed in virtually every program
607 = mkFVs [unpackCStringName, unpackCStringFoldrName,
608 unpackCStringUtf8Name, eqStringName,
609 -- Virtually every program has error messages in it somewhere
610 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
611 -- Add occurrences for very frequently used types.
612 -- (e.g. we don't want to be bothered with making
613 -- funTyCon a free var at every function application!)
616 %************************************************************************
618 \subsection{Re-bindable desugaring names}
620 %************************************************************************
622 Haskell 98 says that when you say "3" you get the "fromInteger" from the
623 Standard Prelude, regardless of what is in scope. However, to experiment
624 with having a language that is less coupled to the standard prelude, we're
625 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
626 happens to be in scope. Then you can
628 import MyPrelude as Prelude
629 to get the desired effect.
631 At the moment this just happens for
632 * fromInteger, fromRational on literals (in expressions and patterns)
633 * negate (in expressions)
634 * minus (arising from n+k patterns)
637 We store the relevant Name in the HsSyn tree, in
638 * HsIntegral/HsFractional
642 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
643 fromRationalName etc), but the renamer changes this to the appropriate user
644 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
646 We treat the orignal (standard) names as free-vars too, because the type checker
647 checks the type of the user thing against the type of the standard thing.
650 lookupSyntaxName :: Name -- The standard name
651 -> RnM (Name, FreeVars) -- Possibly a non-standard name
652 lookupSyntaxName std_name
653 = getModeRn `thenM` \ mode ->
654 if isInterfaceMode mode then
655 returnM (std_name, unitFV std_name)
656 -- Happens for 'derived' code
657 -- where we don't want to rebind
660 doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
661 if not no_prelude then
662 returnM (std_name, unitFV std_name) -- Normal case
665 -- Get the similarly named thing from the local environment
666 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
667 returnM (usr_name, mkFVs [usr_name, std_name])
671 %*********************************************************
675 %*********************************************************
678 newLocalsRn :: [(RdrName,SrcLoc)]
680 newLocalsRn rdr_names_w_loc
681 = newUniqueSupply `thenM` \ us ->
683 uniqs = uniqsFromSupply us
684 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
685 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
691 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
692 -> [(RdrName,SrcLoc)]
695 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
696 = getModeRn `thenM` \ mode ->
697 getLocalRdrEnv `thenM` \ local_env ->
698 getGlobalRdrEnv `thenM` \ global_env ->
700 -- Check for duplicate names
701 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
703 -- Warn about shadowing, but only in source modules
705 check_shadow (rdr_name,loc)
706 | rdr_name `elemRdrEnv` local_env
707 || rdr_name `elemRdrEnv` global_env
708 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
714 SourceMode -> ifOptM Opt_WarnNameShadowing $
715 mappM_ check_shadow rdr_names_w_loc
719 newLocalsRn rdr_names_w_loc `thenM` \ names ->
721 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
723 setLocalRdrEnv new_local_env (enclosed_scope names)
725 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
726 -- A specialised variant when renaming stuff from interface
727 -- files (of which there is a lot)
729 -- * no checks for shadowing
731 -- * deal with free vars
732 bindCoreLocalRn rdr_name enclosed_scope
733 = getSrcLocM `thenM` \ loc ->
734 getLocalRdrEnv `thenM` \ name_env ->
735 newUnique `thenM` \ uniq ->
737 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
738 new_name_env = extendRdrEnv name_env rdr_name name
740 setLocalRdrEnv new_name_env (enclosed_scope name)
742 bindCoreLocalsRn [] thing_inside = thing_inside []
743 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
744 bindCoreLocalsRn bs $ \ names' ->
745 thing_inside (name':names')
747 bindLocalNames names enclosed_scope
748 = getLocalRdrEnv `thenM` \ name_env ->
749 setLocalRdrEnv (extendLocalRdrEnv name_env names)
752 bindLocalNamesFV names enclosed_scope
753 = bindLocalNames names $
754 enclosed_scope `thenM` \ (thing, fvs) ->
755 returnM (thing, delListFromNameSet fvs names)
758 -------------------------------------
759 bindLocalRn doc rdr_name enclosed_scope
760 = getSrcLocM `thenM` \ loc ->
761 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
765 bindLocalsRn doc rdr_names enclosed_scope
766 = getSrcLocM `thenM` \ loc ->
767 bindLocatedLocalsRn doc
768 (rdr_names `zip` repeat loc)
771 -- binLocalsFVRn is the same as bindLocalsRn
772 -- except that it deals with free vars
773 bindLocalsFVRn doc rdr_names enclosed_scope
774 = bindLocalsRn doc rdr_names $ \ names ->
775 enclosed_scope names `thenM` \ (thing, fvs) ->
776 returnM (thing, delListFromNameSet fvs names)
778 -------------------------------------
779 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
780 -- This tiresome function is used only in rnSourceDecl on InstDecl
781 extendTyVarEnvFVRn tyvars enclosed_scope
782 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
783 returnM (thing, delListFromNameSet fvs tyvars)
785 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
786 -> ([HsTyVarBndr Name] -> RnM a)
788 bindTyVarsRn doc_str tyvar_names enclosed_scope
789 = getSrcLocM `thenM` \ loc ->
791 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
793 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
794 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
796 bindPatSigTyVars :: [RdrNameHsType]
799 -- Find the type variables in the pattern type
800 -- signatures that must be brought into scope
802 bindPatSigTyVars tys enclosed_scope
803 = getLocalRdrEnv `thenM` \ name_env ->
804 getSrcLocM `thenM` \ loc ->
806 forall_tyvars = nub [ tv | ty <- tys,
807 tv <- extractHsTyRdrTyVars ty,
808 not (tv `elemFM` name_env)
810 -- The 'nub' is important. For example:
811 -- f (x :: t) (y :: t) = ....
812 -- We don't want to complain about binding t twice!
814 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
815 doc_sig = text "In a pattern type-signature"
817 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
818 enclosed_scope `thenM` \ (thing, fvs) ->
819 returnM (thing, delListFromNameSet fvs names)
822 -------------------------------------
823 checkDupOrQualNames, checkDupNames :: SDoc
824 -> [(RdrName, SrcLoc)]
826 -- Works in any variant of the renamer monad
828 checkDupOrQualNames doc_str rdr_names_w_loc
829 = -- Qualified names in patterns are now rejected by the parser
830 -- but I'm not 100% certain that it finds all cases, so I've left
831 -- this check in for now. Should go eventually.
832 -- Hmm. Sooner rather than later.. data type decls
833 -- mappM_ (qualNameErr doc_str) quals `thenM_`
834 checkDupNames doc_str rdr_names_w_loc
836 quals = filter (isQual . fst) rdr_names_w_loc
838 checkDupNames doc_str rdr_names_w_loc
839 = -- Check for duplicated names in a binding group
840 mappM_ (dupNamesErr doc_str) dups
842 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
846 %************************************************************************
848 \subsection{GlobalRdrEnv}
850 %************************************************************************
853 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
854 -> Bool -- True <=> want unqualified import
855 -> (Name -> Provenance)
856 -> Avails -- Whats imported
860 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
863 -- Make the name environment. We're talking about a
864 -- single module here, so there must be no name clashes.
865 -- In practice there only ever will be if it's the module
868 -- Add qualified names for the things that are available
869 -- (Qualified names are always imported)
870 gbl_env1 = foldl add_avail emptyRdrEnv avails
872 -- Add unqualified names
873 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
874 | otherwise = gbl_env1
876 add_unqual env (qual_name, elts)
877 = foldl add_one env elts
879 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
880 unqual_name = unqualifyRdrName qual_name
881 -- The qualified import should only have added one
882 -- binding for each qualified name! But if there's an error in
883 -- the module (multiple bindings for the same name) we may get
884 -- duplicates. So the simple thing is to do the fold.
886 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
887 add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
889 add_name parent env name -- Add qualified name only
890 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
892 occ = nameOccName name
893 elt = GRE {gre_name = name,
894 gre_parent = if name == parent
897 gre_prov = mk_provenance name,
898 gre_deprec = lookupDeprec deprecs name}
903 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
904 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
906 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
907 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
909 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
910 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
912 combine_globals :: [GlobalRdrElt] -- Old
913 -> [GlobalRdrElt] -- New
915 combine_globals ns_old ns_new -- ns_new is often short
916 = foldr add ns_old ns_new
918 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
921 choose n m | n `beats` m = n
924 g1 `beats` g2 = gre_name g1 == gre_name g2 &&
925 gre_prov g1 `hasBetterProv` gre_prov g2
927 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
928 is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
929 is_duplicate g1 g2 = gre_name g1 == gre_name g2
932 We treat two bindings of a locally-defined name as a duplicate,
933 because they might be two separate, local defns and we want to report
934 and error for that, {\em not} eliminate a duplicate.
936 On the other hand, if you import the same name from two different
937 import statements, we {\em do} want to eliminate the duplicate, not report
940 If a module imports itself then there might be a local defn and an imported
941 defn of the same name; in this case the names will compare as equal, but
942 will still have different provenances.
945 %************************************************************************
947 \subsection{Free variable manipulation}
949 %************************************************************************
953 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
955 (ys, fvs_s) = unzip stuff
957 returnM (ys, plusFVs fvs_s)
961 %************************************************************************
963 \subsection{Envt utility functions}
965 %************************************************************************
968 warnUnusedModules :: [ModuleName] -> TcRn m ()
969 warnUnusedModules mods
970 = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
972 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
973 text "is imported, but nothing from it is used",
974 parens (ptext SLIT("except perhaps instances visible in") <+>
977 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
978 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
979 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
981 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
982 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
983 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
985 -------------------------
987 warnUnusedGREs gres = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
988 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
990 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
991 warnUnusedBinds names
992 = mappM_ warnUnusedGroup groups
994 -- Group by provenance
995 groups = equivClasses cmp (filter reportable names)
996 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
998 reportable (name,_) = reportIfUnused (nameOccName name)
1001 -------------------------
1003 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
1004 warnUnusedGroup names
1005 = addSrcLoc def_loc $
1007 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) names)))]
1009 (name1, prov1) = head names
1010 loc1 = nameSrcLoc name1
1011 (def_loc, msg) = case prov1 of
1012 LocalDef -> (loc1, unused_msg)
1013 NonLocalDef (UserImport mod loc _) -> (loc, imp_from mod)
1015 unused_msg = text "Defined but not used"
1016 imp_from mod = text "Imported from" <+> quotes (ppr mod) <+> text "but not used"
1020 addNameClashErrRn rdr_name (np1:nps)
1021 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1022 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1024 msg1 = ptext SLIT("either") <+> mk_ref np1
1025 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1026 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1028 shadowedNameWarn shadow
1029 = hsep [ptext SLIT("This binding for"),
1030 quotes (ppr shadow),
1031 ptext SLIT("shadows an existing binding")]
1034 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1036 flavour = occNameFlavour (rdrNameOcc name)
1039 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1040 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1042 qualNameErr descriptor (name,loc)
1044 addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1047 dupNamesErr descriptor ((name,loc) : dup_things)
1049 addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1053 noIfaceErr dflags mod_name boot_file files
1054 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
1058 | verbosity dflags < 3 =
1059 text "(use -v to see a list of the files searched for)"
1061 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1063 warnDeprec :: GlobalRdrElt -> TcRn m ()
1064 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1065 = ifOptM Opt_WarnDeprecations $
1066 addWarn (sep [ text (occNameFlavour (nameOccName name)) <+>
1067 quotes (ppr name) <+> text "is deprecated:",