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, getSrcLoc, nameIsLocalOrFrom, isWiredInName,
33 mkInternalName, mkExternalName, mkIPName, nameSrcLoc,
34 nameOccName, setNameSrcLoc, nameModule )
36 import OccName ( OccName, tcName, isDataOcc, occNameUserString, occNameFlavour )
37 import Module ( Module, ModuleName, moduleName, mkHomeModule,
38 lookupModuleEnv, lookupModuleEnvByName, extendModuleEnv_C )
39 import PrelNames ( mkUnboundName, intTyConName,
40 boolTyConName, funTyConName,
41 unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
42 eqStringName, printName,
43 bindIOName, returnIOName, failIOName, thenIOName
46 import DsMeta ( templateHaskellNames, qTyConName )
48 import TysWiredIn ( unitTyCon ) -- A little odd
49 import Finder ( findModule )
52 import SrcLoc ( SrcLoc, noSrcLoc, importedSrcLoc )
54 import ListSetOps ( removeDups, equivClasses )
55 import BasicTypes ( mapIPName, FixitySig(..) )
58 import FastString ( FastString )
61 %*********************************************************
63 \subsection{Making new names}
65 %*********************************************************
68 newTopBinder :: Module -> RdrName -> SrcLoc -> TcRn m Name
69 newTopBinder mod rdr_name loc
70 | Just name <- isExact_maybe rdr_name
74 = newGlobalName mod (rdrNameOcc rdr_name) loc
76 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
77 newGlobalName mod occ loc
78 = -- First check the cache
79 getNameCache `thenM` \ name_supply ->
80 case lookupOrigNameCache (nsNames name_supply) mod occ of
82 -- A hit in the cache! We are at the binding site of the name.
83 -- This is the moment when we know the defining SrcLoc
84 -- of the Name, so we set the SrcLoc of the name we return.
86 -- Main reason: then (bogus) multiple bindings of the same Name
87 -- get different SrcLocs can can be reported as such.
89 -- Possible other reason: it might be in the cache because we
90 -- encountered an occurrence before the binding site for an
91 -- implicitly-imported Name. Perhaps the current SrcLoc is
92 -- better... but not really: it'll still just say 'imported'
94 -- IMPORTANT: Don't mess with wired-in names.
95 -- Their wired-in-ness is in the SrcLoc
97 Just name | isWiredInName name -> returnM name
98 | otherwise -> returnM (setNameSrcLoc name loc)
100 -- Miss in the cache!
101 -- Build a completely new Name, and put it in the cache
102 Nothing -> addNewName name_supply mod occ loc
104 -- Look up a "system name" in the name cache.
105 -- This is done by the type checker...
106 lookupSysName :: Name -- Base name
107 -> (OccName -> OccName) -- Occurrence name modifier
108 -> TcRn m Name -- System name
109 lookupSysName base_name mk_sys_occ
110 = newGlobalName (nameModule base_name)
111 (mk_sys_occ (nameOccName base_name))
112 (nameSrcLoc base_name)
115 newGlobalNameFromRdrName rdr_name -- Qualified original name
116 = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
118 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
119 -- This one starts with a ModuleName, not a Module, because
120 -- we may be simply looking at an occurrence M.x in an interface file.
122 -- Used for *occurrences*. Even if we get a miss in the
123 -- original-name cache, we make a new External Name.
124 -- We get its Module either from the OrigNameCache, or (if this
125 -- is the first Name from that module) from the Finder
127 -- In the case of a miss, we have to make up the SrcLoc, but that's
128 -- OK: it must be an implicitly-imported Name, and that never occurs
129 -- in an error message.
131 newGlobalName2 mod_name occ
132 = getNameCache `thenM` \ name_supply ->
134 new_name mod = addNewName name_supply mod occ importedSrcLoc
136 case lookupModuleEnvByName (nsNames name_supply) mod_name of
137 Just (mod, occ_env) ->
138 -- There are some names from this module already
139 -- Next, look up in the OccNameEnv
140 case lookupFM occ_env occ of
141 Just name -> returnM name
142 Nothing -> new_name mod
144 Nothing -> -- No names from this module yet
145 ioToTcRn (findModule mod_name) `thenM` \ mb_loc ->
147 Just (mod, _) -> new_name mod
148 Nothing -> addErr (noModule mod_name) `thenM_`
149 -- Things have really gone wrong at this point,
150 -- so having the wrong package info in the
151 -- Module is the least of our worries.
152 new_name (mkHomeModule mod_name)
154 noModule mod_name = ptext SLIT("Can't find interface for module") <+> ppr mod_name
157 newIPName rdr_name_ip
158 = getNameCache `thenM` \ name_supply ->
160 ipcache = nsIPs name_supply
162 case lookupFM ipcache key of
163 Just name_ip -> returnM name_ip
164 Nothing -> setNameCache new_ns `thenM_`
167 (us', us1) = splitUniqSupply (nsUniqs name_supply)
168 uniq = uniqFromSupply us1
169 name_ip = mapIPName mk_name rdr_name_ip
170 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
171 new_ipcache = addToFM ipcache key name_ip
172 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
174 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
176 -- A local helper function
177 addNewName name_supply mod occ loc
178 = setNameCache new_name_supply `thenM_`
181 (new_name_supply, name) = newExternalName name_supply mod occ loc
184 newExternalName :: NameCache -> Module -> OccName -> SrcLoc
186 -- Allocate a new unique, manufacture a new External Name,
187 -- put it in the cache, and return the two
188 newExternalName name_supply mod occ loc
189 = (new_name_supply, name)
191 (us', us1) = splitUniqSupply (nsUniqs name_supply)
192 uniq = uniqFromSupply us1
193 name = mkExternalName uniq mod occ loc
194 new_cache = extend_name_cache (nsNames name_supply) mod occ name
195 new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
197 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
198 lookupOrigNameCache nc mod occ
199 = case lookupModuleEnv nc mod of
201 Just (_, occ_env) -> lookupFM occ_env occ
203 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
204 extendOrigNameCache nc name
205 = extend_name_cache nc (nameModule name) (nameOccName name) name
207 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
208 extend_name_cache nc mod occ name
209 = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
211 combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
214 %*********************************************************
216 \subsection{Looking up names}
218 %*********************************************************
220 Looking up a name in the RnEnv.
223 lookupBndrRn rdr_name
224 = getLocalRdrEnv `thenM` \ local_env ->
225 case lookupRdrEnv local_env rdr_name of
226 Just name -> returnM name
227 Nothing -> lookupTopBndrRn rdr_name
229 lookupTopBndrRn rdr_name
230 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
231 -- and there may be several imported 'f's too, which must not confuse us.
232 -- So we have to filter out the non-local ones.
233 -- A separate function (importsFromLocalDecls) reports duplicate top level
234 -- decls, so here it's safe just to choose an arbitrary one.
236 -- There should never be a qualified name in a binding position
237 -- The parser could check this, but doesn't (yet)
239 = getSrcLocM `thenM` \ loc ->
240 qualNameErr (text "In its declaration") (rdr_name,loc) `thenM_`
241 returnM (mkUnboundName rdr_name)
244 = ASSERT( not (isOrig rdr_name) )
245 -- Original names are used only for occurrences,
248 getModeRn `thenM` \ mode ->
251 getSrcLocM `thenM` \ loc ->
252 newTopBinder mod rdr_name loc
254 other -> lookupTopSrcBndr rdr_name
256 lookupTopSrcBndr :: RdrName -> TcRn m Name
257 lookupTopSrcBndr rdr_name
258 = lookupTopSrcBndr_maybe rdr_name `thenM` \ maybe_name ->
260 Just name -> returnM name
261 Nothing -> unboundName rdr_name
264 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
265 -- Look up a source-code binder
267 -- Ignores imported names; for example, this is OK:
269 -- infix 9 f -- The 'f' here does not need to be qualified
270 -- f x = x -- Nor here, of course
272 lookupTopSrcBndr_maybe rdr_name
273 | Just name <- isExact_maybe rdr_name
274 -- This is here just to catch the PrelBase defn of (say) [] and similar
275 -- The parser reads the special syntax and returns an Exact RdrName
276 -- But the global_env contains only Qual RdrNames, so we won't
277 -- find it there; instead just get the name via the Orig route
279 -- We are at a binding site for the name, so check first that it
280 -- the current module is the correct one; otherwise GHC can get
281 -- very confused indeed. This test rejects code like
282 -- data T = (,) Int Int
283 -- unless we are in GHC.Tup
284 = getModule `thenM` \ mod ->
285 checkErr (moduleName mod == moduleName (nameModule name))
286 (badOrigBinding rdr_name) `thenM_`
290 = getGlobalRdrEnv `thenM` \ global_env ->
291 case lookupRdrEnv global_env rdr_name of
292 Nothing -> returnM Nothing
293 Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
294 [] -> returnM Nothing
295 (n:ns) -> returnM (Just n)
298 -- lookupSigOccRn is used for type signatures and pragmas
304 -- It's clear that the 'f' in the signature must refer to A.f
305 -- The Haskell98 report does not stipulate this, but it will!
306 -- So we must treat the 'f' in the signature in the same way
307 -- as the binding occurrence of 'f', using lookupBndrRn
308 lookupSigOccRn :: RdrName -> RnM Name
309 lookupSigOccRn = lookupBndrRn
311 -- lookupInstDeclBndr is used for the binders in an
312 -- instance declaration. Here we use the class name to
315 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
316 -- We use the selector name as the binder
317 lookupInstDeclBndr cls_name rdr_name
319 = -- Find all the things the class op name maps to
320 -- and pick the one with the right parent name
321 getGblEnv `thenM` \ gbl_env ->
323 avail_env = imp_env (tcg_imports gbl_env)
325 case lookupAvailEnv avail_env cls_name of
327 -- If the class itself isn't in scope, then cls_name will
328 -- be unboundName, and there'll already be an error for
329 -- that in the error list. Example:
330 -- e.g. import Prelude hiding( Ord )
331 -- instance Ord T where ...
332 -- The program is wrong, but that should not cause a crash.
333 returnM (mkUnboundName rdr_name)
335 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
336 (n:ns)-> ASSERT( null ns ) returnM n
337 [] -> unboundName rdr_name
339 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
341 | isQual rdr_name -- Should never have a qualified name in a binding position
342 = getSrcLocM `thenM` \ loc ->
343 qualNameErr (text "In an instance method") (rdr_name,loc) `thenM_`
344 returnM (mkUnboundName rdr_name)
346 | otherwise -- Occurs in derived instances, where we just
347 -- refer directly to the right method, and avail_env
349 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
350 lookupOrigName rdr_name
353 occ = rdrNameOcc rdr_name
355 lookupSysBndr :: RdrName -> RnM Name
356 -- Used for the 'system binders' in a data type or class declaration
357 -- Do *not* look up in the RdrEnv; these system binders are never in scope
358 -- Instead, get the module from the monad... but remember that
359 -- where the module is depends on whether we are renaming source or
360 -- interface file stuff
361 lookupSysBndr rdr_name
362 = getSrcLocM `thenM` \ loc ->
363 getModeRn `thenM` \ mode ->
365 InterfaceMode mod -> newTopBinder mod rdr_name loc
366 other -> getModule `thenM` \ mod ->
367 newTopBinder mod rdr_name loc
369 -- lookupOccRn looks up an occurrence of a RdrName
370 lookupOccRn :: RdrName -> RnM Name
372 = getLocalRdrEnv `thenM` \ local_env ->
373 case lookupRdrEnv local_env rdr_name of
374 Just name -> returnM name
375 Nothing -> lookupGlobalOccRn rdr_name
377 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
378 -- environment. It's used only for
379 -- record field names
380 -- class op names in class and instance decls
382 lookupGlobalOccRn rdr_name
383 = getModeRn `thenM` \ mode ->
385 InterfaceMode mod -> lookupIfaceName mod rdr_name
386 SourceMode -> lookupSrcName rdr_name
389 | not (isQual rdr_name) ->
390 lookupSrcName rdr_name
392 -- We allow qualified names on the command line to refer to
393 -- *any* name exported by any module in scope, just as if
394 -- there was an "import qualified M" declaration for every
397 -- First look up the name in the normal environment. If
398 -- it isn't there, we manufacture a new occurrence of an
401 lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
403 Just name -> returnM name
404 Nothing -> lookupQualifiedName rdr_name
406 -- A qualified name on the command line can refer to any module at all: we
407 -- try to load the interface if we don't already have it.
408 lookupQualifiedName :: RdrName -> TcRn m Name
409 lookupQualifiedName rdr_name
411 mod = rdrNameModule rdr_name
412 occ = rdrNameOcc rdr_name
414 loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
415 case [ name | (_,avails) <- mi_exports iface,
417 name <- availNames avail,
418 nameOccName name == occ ] of
419 (n:ns) -> ASSERT (null ns) returnM n
420 _ -> unboundName rdr_name
422 lookupSrcName :: RdrName -> TcRn m Name
423 lookupSrcName rdr_name
424 = lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
426 Nothing -> unboundName rdr_name
427 Just name -> returnM name
429 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
430 lookupSrcName_maybe rdr_name
431 | Just name <- isExact_maybe rdr_name -- Can occur in source code too
432 = returnM (Just name)
434 | isOrig rdr_name -- An original name
435 = newGlobalNameFromRdrName rdr_name `thenM` \ name ->
439 = lookupGRE rdr_name `thenM` \ mb_gre ->
441 Nothing -> returnM Nothing
442 Just gre -> returnM (Just (gre_name gre))
444 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
446 = getGlobalRdrEnv `thenM` \ global_env ->
447 case lookupRdrEnv global_env rdr_name of
448 Just [gre] -> case gre_deprec gre of
449 Nothing -> returnM (Just gre)
450 Just _ -> warnDeprec gre `thenM_`
452 Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff `thenM_`
454 Nothing -> return Nothing
456 lookupIfaceName :: Module -> RdrName -> TcRn m Name
457 -- An Unqual is allowed; interface files contain
458 -- unqualified names for locally-defined things, such as
459 -- constructors of a data type.
460 lookupIfaceName mod rdr_name
461 | isUnqual rdr_name = newGlobalName mod (rdrNameOcc rdr_name) importedSrcLoc
462 | otherwise = lookupOrigName rdr_name
464 lookupOrigName :: RdrName -> TcRn m Name
465 -- Just for original or exact names
466 lookupOrigName rdr_name
467 | Just n <- isExact_maybe rdr_name
468 -- This happens in derived code, which we
469 -- rename in InterfaceMode
472 | otherwise -- Usually Orig, but can be a Qual when
473 -- we are reading a .hi-boot file
474 = newGlobalNameFromRdrName rdr_name
477 dataTcOccs :: RdrName -> [RdrName]
478 -- If the input is a data constructor, return both it and a type
479 -- constructor. This is useful when we aren't sure which we are
482 | isDataOcc occ = [rdr_name, rdr_name_tc]
483 | otherwise = [rdr_name]
485 occ = rdrNameOcc rdr_name
486 rdr_name_tc = setRdrNameSpace rdr_name tcName
490 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
491 returnM (mkUnboundName rdr_name)
494 %*********************************************************
498 %*********************************************************
501 --------------------------------
502 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
503 -- Used for nested fixity decls
504 -- No need to worry about type constructors here,
505 -- Should check for duplicates but we don't
506 bindLocalFixities fixes thing_inside
507 | null fixes = thing_inside
508 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
509 extendFixityEnv new_bit thing_inside
511 rn_sig (FixitySig v fix src_loc)
512 = addSrcLoc src_loc $
513 lookupSigOccRn v `thenM` \ new_v ->
514 returnM (new_v, FixitySig new_v fix src_loc)
517 --------------------------------
518 lookupFixity is a bit strange.
520 * Nested local fixity decls are put in the local fixity env, which we
521 find with getFixtyEnv
523 * Imported fixities are found in the HIT or PIT
525 * Top-level fixity decls in this module may be for Names that are
526 either Global (constructors, class operations)
527 or Local/Exported (everything else)
528 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
529 We put them all in the local fixity environment
532 lookupFixityRn :: Name -> RnM Fixity
534 = getModule `thenM` \ this_mod ->
535 if nameIsLocalOrFrom this_mod name
536 then -- It's defined in this module
537 getFixityEnv `thenM` \ local_fix_env ->
538 returnM (lookupFixity local_fix_env name)
540 else -- It's imported
541 -- For imported names, we have to get their fixities by doing a
542 -- loadHomeInterface, and consulting the Ifaces that comes back
543 -- from that, because the interface file for the Name might not
544 -- have been loaded yet. Why not? Suppose you import module A,
545 -- which exports a function 'f', thus;
546 -- module CurrentModule where
548 -- module A( f ) where
550 -- Then B isn't loaded right away (after all, it's possible that
551 -- nothing from B will be used). When we come across a use of
552 -- 'f', we need to know its fixity, and it's then, and only
553 -- then, that we load B.hi. That is what's happening here.
554 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
555 returnM (lookupFixity (mi_fixities iface) name)
557 doc = ptext SLIT("Checking fixity for") <+> ppr name
558 name_mod = moduleName (nameModule name)
562 %*********************************************************
564 \subsection{Implicit free vars and sugar names}
566 %*********************************************************
568 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
569 mentioned explicitly, but which might be needed by the type checker.
572 implicitStmtFVs source_fvs -- Compiling a statement
573 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
575 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName]
576 -- These are all needed implicitly when compiling a statement
577 -- See TcModule.tc_stmts
579 implicitModuleFVs source_fvs
580 = mkTemplateHaskellFVs source_fvs `plusFV`
581 namesNeededForFlattening `plusFV`
584 -- This is a bit of a hack. When we see the Template-Haskell construct
586 -- we are going to need lots of the ``smart constructors'' defined in
587 -- the main Template Haskell data type module. Rather than treat them
588 -- all as free vars at every occurrence site, we just make the Q type
589 -- consructor a free var.... and then use that here to haul in the others
590 mkTemplateHaskellFVs source_fvs
592 -- Only if Template Haskell is enabled
593 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
595 | otherwise = emptyFVs
597 -- ubiquitous_names are loaded regardless, because
598 -- they are needed in virtually every program
600 = mkFVs [unpackCStringName, unpackCStringFoldrName,
601 unpackCStringUtf8Name, eqStringName,
602 -- Virtually every program has error messages in it somewhere
603 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
604 -- Add occurrences for very frequently used types.
605 -- (e.g. we don't want to be bothered with making
606 -- funTyCon a free var at every function application!)
609 %************************************************************************
611 \subsection{Re-bindable desugaring names}
613 %************************************************************************
615 Haskell 98 says that when you say "3" you get the "fromInteger" from the
616 Standard Prelude, regardless of what is in scope. However, to experiment
617 with having a language that is less coupled to the standard prelude, we're
618 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
619 happens to be in scope. Then you can
621 import MyPrelude as Prelude
622 to get the desired effect.
624 At the moment this just happens for
625 * fromInteger, fromRational on literals (in expressions and patterns)
626 * negate (in expressions)
627 * minus (arising from n+k patterns)
630 We store the relevant Name in the HsSyn tree, in
631 * HsIntegral/HsFractional
635 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
636 fromRationalName etc), but the renamer changes this to the appropriate user
637 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
639 We treat the orignal (standard) names as free-vars too, because the type checker
640 checks the type of the user thing against the type of the standard thing.
643 lookupSyntaxName :: Name -- The standard name
644 -> RnM (Name, FreeVars) -- Possibly a non-standard name
645 lookupSyntaxName std_name
646 = getModeRn `thenM` \ mode ->
647 if isInterfaceMode mode then
648 returnM (std_name, unitFV std_name)
649 -- Happens for 'derived' code
650 -- where we don't want to rebind
653 doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
654 if not no_prelude then
655 returnM (std_name, unitFV std_name) -- Normal case
658 -- Get the similarly named thing from the local environment
659 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
660 returnM (usr_name, mkFVs [usr_name, std_name])
664 %*********************************************************
668 %*********************************************************
671 newLocalsRn :: [(RdrName,SrcLoc)]
673 newLocalsRn rdr_names_w_loc
674 = newUniqueSupply `thenM` \ us ->
676 uniqs = uniqsFromSupply us
677 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
678 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
684 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
685 -> [(RdrName,SrcLoc)]
688 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
689 = getModeRn `thenM` \ mode ->
690 getLocalRdrEnv `thenM` \ local_env ->
691 getGlobalRdrEnv `thenM` \ global_env ->
693 -- Check for duplicate names
694 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
696 -- Warn about shadowing, but only in source modules
698 check_shadow (rdr_name,loc)
699 | rdr_name `elemRdrEnv` local_env
700 || rdr_name `elemRdrEnv` global_env
701 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
707 SourceMode -> ifOptM Opt_WarnNameShadowing $
708 mappM_ check_shadow rdr_names_w_loc
712 newLocalsRn rdr_names_w_loc `thenM` \ names ->
714 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
716 setLocalRdrEnv new_local_env (enclosed_scope names)
718 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
719 -- A specialised variant when renaming stuff from interface
720 -- files (of which there is a lot)
722 -- * no checks for shadowing
724 -- * deal with free vars
725 bindCoreLocalRn rdr_name enclosed_scope
726 = getSrcLocM `thenM` \ loc ->
727 getLocalRdrEnv `thenM` \ name_env ->
728 newUnique `thenM` \ uniq ->
730 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
731 new_name_env = extendRdrEnv name_env rdr_name name
733 setLocalRdrEnv new_name_env (enclosed_scope name)
735 bindCoreLocalsRn [] thing_inside = thing_inside []
736 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
737 bindCoreLocalsRn bs $ \ names' ->
738 thing_inside (name':names')
740 bindLocalNames names enclosed_scope
741 = getLocalRdrEnv `thenM` \ name_env ->
742 setLocalRdrEnv (extendLocalRdrEnv name_env names)
745 bindLocalNamesFV names enclosed_scope
746 = bindLocalNames names $
747 enclosed_scope `thenM` \ (thing, fvs) ->
748 returnM (thing, delListFromNameSet fvs names)
751 -------------------------------------
752 bindLocalRn doc rdr_name enclosed_scope
753 = getSrcLocM `thenM` \ loc ->
754 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
758 bindLocalsRn doc rdr_names enclosed_scope
759 = getSrcLocM `thenM` \ loc ->
760 bindLocatedLocalsRn doc
761 (rdr_names `zip` repeat loc)
764 -- binLocalsFVRn is the same as bindLocalsRn
765 -- except that it deals with free vars
766 bindLocalsFVRn doc rdr_names enclosed_scope
767 = bindLocalsRn doc rdr_names $ \ names ->
768 enclosed_scope names `thenM` \ (thing, fvs) ->
769 returnM (thing, delListFromNameSet fvs names)
771 -------------------------------------
772 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
773 -- This tiresome function is used only in rnSourceDecl on InstDecl
774 extendTyVarEnvFVRn tyvars enclosed_scope
775 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
776 returnM (thing, delListFromNameSet fvs tyvars)
778 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
779 -> ([HsTyVarBndr Name] -> RnM a)
781 bindTyVarsRn doc_str tyvar_names enclosed_scope
782 = getSrcLocM `thenM` \ loc ->
784 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
786 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
787 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
789 bindPatSigTyVars :: [RdrNameHsType]
792 -- Find the type variables in the pattern type
793 -- signatures that must be brought into scope
795 bindPatSigTyVars tys enclosed_scope
796 = getLocalRdrEnv `thenM` \ name_env ->
797 getSrcLocM `thenM` \ loc ->
799 forall_tyvars = nub [ tv | ty <- tys,
800 tv <- extractHsTyRdrTyVars ty,
801 not (tv `elemFM` name_env)
803 -- The 'nub' is important. For example:
804 -- f (x :: t) (y :: t) = ....
805 -- We don't want to complain about binding t twice!
807 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
808 doc_sig = text "In a pattern type-signature"
810 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
811 enclosed_scope `thenM` \ (thing, fvs) ->
812 returnM (thing, delListFromNameSet fvs names)
815 -------------------------------------
816 checkDupOrQualNames, checkDupNames :: SDoc
817 -> [(RdrName, SrcLoc)]
819 -- Works in any variant of the renamer monad
821 checkDupOrQualNames doc_str rdr_names_w_loc
822 = -- Check for use of qualified names
823 mappM_ (qualNameErr doc_str) quals `thenM_`
824 checkDupNames doc_str rdr_names_w_loc
826 quals = filter (isQual . fst) rdr_names_w_loc
828 checkDupNames doc_str rdr_names_w_loc
829 = -- Check for duplicated names in a binding group
830 mappM_ (dupNamesErr doc_str) dups
832 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
836 %************************************************************************
838 \subsection{GlobalRdrEnv}
840 %************************************************************************
843 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
844 -> Bool -- True <=> want unqualified import
845 -> (Name -> Provenance)
846 -> Avails -- Whats imported
850 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
853 -- Make the name environment. We're talking about a
854 -- single module here, so there must be no name clashes.
855 -- In practice there only ever will be if it's the module
858 -- Add qualified names for the things that are available
859 -- (Qualified names are always imported)
860 gbl_env1 = foldl add_avail emptyRdrEnv avails
862 -- Add unqualified names
863 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
864 | otherwise = gbl_env1
866 add_unqual env (qual_name, elts)
867 = foldl add_one env elts
869 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
870 unqual_name = unqualifyRdrName qual_name
871 -- The qualified import should only have added one
872 -- binding for each qualified name! But if there's an error in
873 -- the module (multiple bindings for the same name) we may get
874 -- duplicates. So the simple thing is to do the fold.
876 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
877 add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
879 add_name parent env name -- Add qualified name only
880 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
882 occ = nameOccName name
883 elt = GRE {gre_name = name,
885 gre_prov = mk_provenance name,
886 gre_deprec = lookupDeprec deprecs name}
891 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
892 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
894 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
895 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
897 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
898 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
900 combine_globals :: [GlobalRdrElt] -- Old
901 -> [GlobalRdrElt] -- New
903 combine_globals ns_old ns_new -- ns_new is often short
904 = foldr add ns_old ns_new
906 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
909 choose n m | n `beats` m = n
912 g1 `beats` g2 = gre_name g1 == gre_name g2 &&
913 gre_prov g1 `hasBetterProv` gre_prov g2
915 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
916 is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
917 is_duplicate g1 g2 = gre_name g1 == gre_name g2
920 We treat two bindings of a locally-defined name as a duplicate,
921 because they might be two separate, local defns and we want to report
922 and error for that, {\em not} eliminate a duplicate.
924 On the other hand, if you import the same name from two different
925 import statements, we {\em do} want to eliminate the duplicate, not report
928 If a module imports itself then there might be a local defn and an imported
929 defn of the same name; in this case the names will compare as equal, but
930 will still have different provenances.
933 %************************************************************************
935 \subsection{Free variable manipulation}
937 %************************************************************************
941 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
943 (ys, fvs_s) = unzip stuff
945 returnM (ys, plusFVs fvs_s)
949 %************************************************************************
951 \subsection{Envt utility functions}
953 %************************************************************************
956 warnUnusedModules :: [ModuleName] -> TcRn m ()
957 warnUnusedModules mods
958 = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
960 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
961 text "is imported, but nothing from it is used",
962 parens (ptext SLIT("except perhaps instances visible in") <+>
965 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
966 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
967 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
969 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
970 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
971 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
973 -------------------------
975 warnUnusedGREs gres = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
976 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
978 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
979 warnUnusedBinds names
980 = mappM_ warnUnusedGroup groups
982 -- Group by provenance
983 groups = equivClasses cmp names
984 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
987 -------------------------
989 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
990 warnUnusedGroup names
991 | null filtered_names = returnM ()
992 | not is_local = returnM ()
994 = addSrcLoc def_loc $
996 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
998 filtered_names = filter reportable names
999 (name1, prov1) = head filtered_names
1000 (is_local, def_loc, msg)
1002 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
1004 NonLocalDef (UserImport mod loc _)
1005 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
1007 reportable (name,_) = case occNameUserString (nameOccName name) of
1010 -- Haskell 98 encourages compilers to suppress warnings about
1011 -- unused names in a pattern if they start with "_".
1015 addNameClashErrRn rdr_name (np1:nps)
1016 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1017 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1019 msg1 = ptext SLIT("either") <+> mk_ref np1
1020 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1021 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1023 shadowedNameWarn shadow
1024 = hsep [ptext SLIT("This binding for"),
1025 quotes (ppr shadow),
1026 ptext SLIT("shadows an existing binding")]
1029 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1031 flavour = occNameFlavour (rdrNameOcc name)
1034 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1035 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1037 qualNameErr descriptor (name,loc)
1039 addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1042 dupNamesErr descriptor ((name,loc) : dup_things)
1044 addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1048 warnDeprec :: GlobalRdrElt -> TcRn m ()
1049 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1050 = ifOptM Opt_WarnDeprecations $
1051 addWarn (sep [ text (occNameFlavour (nameOccName name)) <+>
1052 quotes (ppr name) <+> text "is deprecated:",