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, setNameModuleAndLoc, 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 puts into the cache the binder with the
70 -- module information set correctly. When the decl is later renamed,
71 -- the binding site will thereby get the correct module.
72 -- There maybe occurrences that don't have the correct Module, but
73 -- by the typechecker will propagate the binding definition to all
74 -- the occurrences, so that doesn't matter
76 newTopBinder mod rdr_name loc
77 | Just name <- isExact_maybe rdr_name
81 = newGlobalName mod (rdrNameOcc rdr_name) loc
83 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
84 newGlobalName mod occ loc
85 = -- First check the cache
86 getNameCache `thenM` \ name_supply ->
87 case lookupOrigNameCache (nsNames name_supply) mod occ of
89 -- A hit in the cache! We are at the binding site of the name.
90 -- This is the moment when we know the defining SrcLoc
91 -- of the Name. However, since we must have encountered an
92 -- occurrence before the binding site, this must be an
93 -- implicitly-imported name and we can't give a useful SrcLoc to
94 -- it. So we just leave it alone.
96 -- IMPORTANT: don't mess with wired-in names.
97 -- Their wired-in-ness is in the SrcLoc
99 Just name -> returnM name
101 -- Miss in the cache!
102 -- Build a completely new Name, and put it in the cache
103 Nothing -> addNewName name_supply mod occ loc
105 -- Look up a "system name" in the name cache.
106 -- This is done by the type checker...
107 lookupSysName :: Name -- Base name
108 -> (OccName -> OccName) -- Occurrence name modifier
109 -> TcRn m Name -- System name
110 lookupSysName base_name mk_sys_occ
111 = newGlobalName (nameModule base_name)
112 (mk_sys_occ (nameOccName base_name))
113 (nameSrcLoc base_name)
116 newGlobalNameFromRdrName rdr_name -- Qualified original name
117 = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
119 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
120 -- This one starts with a ModuleName, not a Module, because
121 -- we may be simply looking at an occurrence M.x in an interface file.
123 -- Used for *occurrences*. Even if we get a miss in the
124 -- original-name cache, we make a new External Name.
125 -- We get its Module either from the OrigNameCache, or (if this
126 -- is the first Name from that module) from the Finder
128 -- In the case of a miss, we have to make up the SrcLoc, but that's
129 -- OK: it must be an implicitly-imported Name, and that never occurs
130 -- in an error message.
132 newGlobalName2 mod_name occ
133 = getNameCache `thenM` \ name_supply ->
135 new_name mod = addNewName name_supply mod occ importedSrcLoc
137 case lookupModuleEnvByName (nsNames name_supply) mod_name of
138 Just (mod, occ_env) ->
139 -- There are some names from this module already
140 -- Next, look up in the OccNameEnv
141 case lookupFM occ_env occ of
142 Just name -> returnM name
143 Nothing -> new_name mod
145 Nothing -> -- No names from this module yet
146 ioToTcRn (findModule mod_name) `thenM` \ mb_loc ->
148 Just (mod, _) -> new_name mod
149 Nothing -> addErr (noModule mod_name) `thenM_`
150 -- Things have really gone wrong at this point,
151 -- so having the wrong package info in the
152 -- Module is the least of our worries.
153 new_name (mkHomeModule mod_name)
155 noModule mod_name = ptext SLIT("Can't find interface for module") <+> ppr mod_name
158 newIPName rdr_name_ip
159 = getNameCache `thenM` \ name_supply ->
161 ipcache = nsIPs name_supply
163 case lookupFM ipcache key of
164 Just name_ip -> returnM name_ip
165 Nothing -> setNameCache new_ns `thenM_`
168 (us', us1) = splitUniqSupply (nsUniqs name_supply)
169 uniq = uniqFromSupply us1
170 name_ip = mapIPName mk_name rdr_name_ip
171 mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
172 new_ipcache = addToFM ipcache key name_ip
173 new_ns = name_supply {nsUniqs = us', nsIPs = new_ipcache}
175 key = rdr_name_ip -- Ensures that ?x and %x get distinct Names
177 -- A local helper function
178 addNewName name_supply mod occ loc
179 = setNameCache new_name_supply `thenM_`
182 (new_name_supply, name) = newExternalName name_supply mod occ loc
185 newExternalName :: NameCache -> Module -> OccName -> SrcLoc
187 -- Allocate a new unique, manufacture a new External Name,
188 -- put it in the cache, and return the two
189 newExternalName name_supply mod occ loc
190 = (new_name_supply, name)
192 (us', us1) = splitUniqSupply (nsUniqs name_supply)
193 uniq = uniqFromSupply us1
194 name = mkExternalName uniq mod occ loc
195 new_cache = extend_name_cache (nsNames name_supply) mod occ name
196 new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
198 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
199 lookupOrigNameCache nc mod occ
200 = case lookupModuleEnv nc mod of
202 Just (_, occ_env) -> lookupFM occ_env occ
204 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
205 extendOrigNameCache nc name
206 = extend_name_cache nc (nameModule name) (nameOccName name) name
208 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
209 extend_name_cache nc mod occ name
210 = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
212 combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
215 %*********************************************************
217 \subsection{Looking up names}
219 %*********************************************************
221 Looking up a name in the RnEnv.
224 lookupBndrRn rdr_name
225 = getLocalRdrEnv `thenM` \ local_env ->
226 case lookupRdrEnv local_env rdr_name of
227 Just name -> returnM name
228 Nothing -> lookupTopBndrRn rdr_name
230 lookupTopBndrRn rdr_name
231 -- Look up a top-level local binder. We may be looking up an unqualified 'f',
232 -- and there may be several imported 'f's too, which must not confuse us.
233 -- So we have to filter out the non-local ones.
234 -- A separate function (importsFromLocalDecls) reports duplicate top level
235 -- decls, so here it's safe just to choose an arbitrary one.
237 -- There should never be a qualified name in a binding position
238 -- The parser could check this, but doesn't (yet)
240 = getSrcLocM `thenM` \ loc ->
241 qualNameErr (text "In its declaration") (rdr_name,loc) `thenM_`
242 returnM (mkUnboundName rdr_name)
245 = ASSERT( not (isOrig rdr_name) )
246 -- Original names are used only for occurrences,
249 getModeRn `thenM` \ mode ->
252 getSrcLocM `thenM` \ loc ->
253 newTopBinder mod rdr_name loc
255 other -> lookupTopSrcBndr rdr_name
257 lookupTopSrcBndr :: RdrName -> TcRn m Name
258 lookupTopSrcBndr rdr_name
259 = lookupTopSrcBndr_maybe rdr_name `thenM` \ maybe_name ->
261 Just name -> returnM name
262 Nothing -> unboundName rdr_name
265 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
266 -- Look up a source-code binder
268 -- Ignores imported names; for example, this is OK:
270 -- infix 9 f -- The 'f' here does not need to be qualified
271 -- f x = x -- Nor here, of course
273 lookupTopSrcBndr_maybe rdr_name
274 | Just name <- isExact_maybe rdr_name
275 -- This is here just to catch the PrelBase defn of (say) [] and similar
276 -- The parser reads the special syntax and returns an Exact RdrName
277 -- But the global_env contains only Qual RdrNames, so we won't
278 -- find it there; instead just get the name via the Orig route
280 -- We are at a binding site for the name, so check first that it
281 -- the current module is the correct one; otherwise GHC can get
282 -- very confused indeed. This test rejects code like
283 -- data T = (,) Int Int
284 -- unless we are in GHC.Tup
285 = getModule `thenM` \ mod ->
286 checkErr (moduleName mod == moduleName (nameModule name))
287 (badOrigBinding rdr_name) `thenM_`
291 = getGlobalRdrEnv `thenM` \ global_env ->
292 case lookupRdrEnv global_env rdr_name of
293 Nothing -> returnM Nothing
294 Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
295 [] -> returnM Nothing
296 (n:ns) -> returnM (Just n)
299 -- lookupSigOccRn is used for type signatures and pragmas
305 -- It's clear that the 'f' in the signature must refer to A.f
306 -- The Haskell98 report does not stipulate this, but it will!
307 -- So we must treat the 'f' in the signature in the same way
308 -- as the binding occurrence of 'f', using lookupBndrRn
309 lookupSigOccRn :: RdrName -> RnM Name
310 lookupSigOccRn = lookupBndrRn
312 -- lookupInstDeclBndr is used for the binders in an
313 -- instance declaration. Here we use the class name to
316 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
317 -- We use the selector name as the binder
318 lookupInstDeclBndr cls_name rdr_name
320 = -- Find all the things the class op name maps to
321 -- and pick the one with the right parent name
322 getGblEnv `thenM` \ gbl_env ->
324 avail_env = imp_env (tcg_imports gbl_env)
326 case lookupAvailEnv avail_env cls_name of
328 -- If the class itself isn't in scope, then cls_name will
329 -- be unboundName, and there'll already be an error for
330 -- that in the error list. Example:
331 -- e.g. import Prelude hiding( Ord )
332 -- instance Ord T where ...
333 -- The program is wrong, but that should not cause a crash.
334 returnM (mkUnboundName rdr_name)
336 Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
337 (n:ns)-> ASSERT( null ns ) returnM n
338 [] -> unboundName rdr_name
340 other -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
342 | isQual rdr_name -- Should never have a qualified name in a binding position
343 = getSrcLocM `thenM` \ loc ->
344 qualNameErr (text "In an instance method") (rdr_name,loc) `thenM_`
345 returnM (mkUnboundName rdr_name)
347 | otherwise -- Occurs in derived instances, where we just
348 -- refer directly to the right method, and avail_env
350 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
351 lookupOrigName rdr_name
354 occ = rdrNameOcc rdr_name
356 lookupSysBndr :: RdrName -> RnM Name
357 -- Used for the 'system binders' in a data type or class declaration
358 -- Do *not* look up in the RdrEnv; these system binders are never in scope
359 -- Instead, get the module from the monad... but remember that
360 -- where the module is depends on whether we are renaming source or
361 -- interface file stuff
362 lookupSysBndr rdr_name
363 = getSrcLocM `thenM` \ loc ->
364 getModeRn `thenM` \ mode ->
366 InterfaceMode mod -> newTopBinder mod rdr_name loc
367 other -> getModule `thenM` \ mod ->
368 newTopBinder mod rdr_name loc
370 -- lookupOccRn looks up an occurrence of a RdrName
371 lookupOccRn :: RdrName -> RnM Name
373 = getLocalRdrEnv `thenM` \ local_env ->
374 case lookupRdrEnv local_env rdr_name of
375 Just name -> returnM name
376 Nothing -> lookupGlobalOccRn rdr_name
378 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
379 -- environment. It's used only for
380 -- record field names
381 -- class op names in class and instance decls
383 lookupGlobalOccRn rdr_name
384 = getModeRn `thenM` \ mode ->
386 InterfaceMode mod -> lookupIfaceName mod rdr_name
387 SourceMode -> lookupSrcName rdr_name
390 | not (isQual rdr_name) ->
391 lookupSrcName rdr_name
393 -- We allow qualified names on the command line to refer to
394 -- *any* name exported by any module in scope, just as if
395 -- there was an "import qualified M" declaration for every
398 -- First look up the name in the normal environment. If
399 -- it isn't there, we manufacture a new occurrence of an
402 lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
404 Just name -> returnM name
405 Nothing -> lookupQualifiedName rdr_name
407 -- A qualified name on the command line can refer to any module at all: we
408 -- try to load the interface if we don't already have it.
409 lookupQualifiedName :: RdrName -> TcRn m Name
410 lookupQualifiedName rdr_name
412 mod = rdrNameModule rdr_name
413 occ = rdrNameOcc rdr_name
415 loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
416 case [ name | (_,avails) <- mi_exports iface,
418 name <- availNames avail,
419 nameOccName name == occ ] of
420 (n:ns) -> ASSERT (null ns) returnM n
421 _ -> unboundName rdr_name
423 lookupSrcName :: RdrName -> TcRn m Name
424 lookupSrcName rdr_name
425 = lookupSrcName_maybe rdr_name `thenM` \ mb_name ->
427 Nothing -> unboundName rdr_name
428 Just name -> returnM name
430 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
431 lookupSrcName_maybe rdr_name
432 | Just name <- isExact_maybe rdr_name -- Can occur in source code too
433 = returnM (Just name)
435 | isOrig rdr_name -- An original name
436 = newGlobalNameFromRdrName rdr_name `thenM` \ name ->
440 = lookupGRE rdr_name `thenM` \ mb_gre ->
442 Nothing -> returnM Nothing
443 Just gre -> returnM (Just (gre_name gre))
445 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
447 = getGlobalRdrEnv `thenM` \ global_env ->
448 case lookupRdrEnv global_env rdr_name of
449 Just [gre] -> case gre_deprec gre of
450 Nothing -> returnM (Just gre)
451 Just _ -> warnDeprec gre `thenM_`
453 Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff `thenM_`
455 Nothing -> return Nothing
457 lookupIfaceName :: Module -> RdrName -> TcRn m Name
458 -- An Unqual is allowed; interface files contain
459 -- unqualified names for locally-defined things, such as
460 -- constructors of a data type.
461 lookupIfaceName mod rdr_name
462 | isUnqual rdr_name = newGlobalName mod (rdrNameOcc rdr_name) importedSrcLoc
463 | otherwise = lookupOrigName rdr_name
465 lookupOrigName :: RdrName -> TcRn m Name
466 -- Just for original or exact names
467 lookupOrigName rdr_name
468 | Just n <- isExact_maybe rdr_name
469 -- This happens in derived code, which we
470 -- rename in InterfaceMode
473 | otherwise -- Usually Orig, but can be a Qual when
474 -- we are reading a .hi-boot file
475 = newGlobalNameFromRdrName rdr_name
478 dataTcOccs :: RdrName -> [RdrName]
479 -- If the input is a data constructor, return both it and a type
480 -- constructor. This is useful when we aren't sure which we are
483 | isDataOcc occ = [rdr_name, rdr_name_tc]
484 | otherwise = [rdr_name]
486 occ = rdrNameOcc rdr_name
487 rdr_name_tc = setRdrNameSpace rdr_name tcName
491 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
492 returnM (mkUnboundName rdr_name)
495 %*********************************************************
499 %*********************************************************
502 --------------------------------
503 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
504 -- Used for nested fixity decls
505 -- No need to worry about type constructors here,
506 -- Should check for duplicates but we don't
507 bindLocalFixities fixes thing_inside
508 | null fixes = thing_inside
509 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
510 extendFixityEnv new_bit thing_inside
512 rn_sig (FixitySig v fix src_loc)
513 = addSrcLoc src_loc $
514 lookupSigOccRn v `thenM` \ new_v ->
515 returnM (new_v, FixitySig new_v fix src_loc)
518 --------------------------------
519 lookupFixity is a bit strange.
521 * Nested local fixity decls are put in the local fixity env, which we
522 find with getFixtyEnv
524 * Imported fixities are found in the HIT or PIT
526 * Top-level fixity decls in this module may be for Names that are
527 either Global (constructors, class operations)
528 or Local/Exported (everything else)
529 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
530 We put them all in the local fixity environment
533 lookupFixityRn :: Name -> RnM Fixity
535 = getModule `thenM` \ this_mod ->
536 if nameIsLocalOrFrom this_mod name
537 then -- It's defined in this module
538 getFixityEnv `thenM` \ local_fix_env ->
539 returnM (lookupFixity local_fix_env name)
541 else -- It's imported
542 -- For imported names, we have to get their fixities by doing a
543 -- loadHomeInterface, and consulting the Ifaces that comes back
544 -- from that, because the interface file for the Name might not
545 -- have been loaded yet. Why not? Suppose you import module A,
546 -- which exports a function 'f', thus;
547 -- module CurrentModule where
549 -- module A( f ) where
551 -- Then B isn't loaded right away (after all, it's possible that
552 -- nothing from B will be used). When we come across a use of
553 -- 'f', we need to know its fixity, and it's then, and only
554 -- then, that we load B.hi. That is what's happening here.
555 loadInterface doc name_mod ImportBySystem `thenM` \ iface ->
556 returnM (lookupFixity (mi_fixities iface) name)
558 doc = ptext SLIT("Checking fixity for") <+> ppr name
559 name_mod = moduleName (nameModule name)
563 %*********************************************************
565 \subsection{Implicit free vars and sugar names}
567 %*********************************************************
569 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
570 mentioned explicitly, but which might be needed by the type checker.
573 implicitStmtFVs source_fvs -- Compiling a statement
574 = stmt_fvs `plusFV` implicitModuleFVs source_fvs
576 stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName]
577 -- These are all needed implicitly when compiling a statement
578 -- See TcModule.tc_stmts
580 implicitModuleFVs source_fvs
581 = mkTemplateHaskellFVs source_fvs `plusFV`
582 namesNeededForFlattening `plusFV`
585 -- This is a bit of a hack. When we see the Template-Haskell construct
587 -- we are going to need lots of the ``smart constructors'' defined in
588 -- the main Template Haskell data type module. Rather than treat them
589 -- all as free vars at every occurrence site, we just make the Q type
590 -- consructor a free var.... and then use that here to haul in the others
591 mkTemplateHaskellFVs source_fvs
593 -- Only if Template Haskell is enabled
594 | qTyConName `elemNameSet` source_fvs = templateHaskellNames
596 | otherwise = emptyFVs
598 -- ubiquitous_names are loaded regardless, because
599 -- they are needed in virtually every program
601 = mkFVs [unpackCStringName, unpackCStringFoldrName,
602 unpackCStringUtf8Name, eqStringName,
603 -- Virtually every program has error messages in it somewhere
604 getName unitTyCon, funTyConName, boolTyConName, intTyConName]
605 -- Add occurrences for very frequently used types.
606 -- (e.g. we don't want to be bothered with making
607 -- funTyCon a free var at every function application!)
610 %************************************************************************
612 \subsection{Re-bindable desugaring names}
614 %************************************************************************
616 Haskell 98 says that when you say "3" you get the "fromInteger" from the
617 Standard Prelude, regardless of what is in scope. However, to experiment
618 with having a language that is less coupled to the standard prelude, we're
619 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
620 happens to be in scope. Then you can
622 import MyPrelude as Prelude
623 to get the desired effect.
625 At the moment this just happens for
626 * fromInteger, fromRational on literals (in expressions and patterns)
627 * negate (in expressions)
628 * minus (arising from n+k patterns)
631 We store the relevant Name in the HsSyn tree, in
632 * HsIntegral/HsFractional
636 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
637 fromRationalName etc), but the renamer changes this to the appropriate user
638 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
640 We treat the orignal (standard) names as free-vars too, because the type checker
641 checks the type of the user thing against the type of the standard thing.
644 lookupSyntaxName :: Name -- The standard name
645 -> RnM (Name, FreeVars) -- Possibly a non-standard name
646 lookupSyntaxName std_name
647 = getModeRn `thenM` \ mode ->
648 if isInterfaceMode mode then
649 returnM (std_name, unitFV std_name)
650 -- Happens for 'derived' code
651 -- where we don't want to rebind
654 doptM Opt_NoImplicitPrelude `thenM` \ no_prelude ->
655 if not no_prelude then
656 returnM (std_name, unitFV std_name) -- Normal case
659 -- Get the similarly named thing from the local environment
660 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
661 returnM (usr_name, mkFVs [usr_name, std_name])
665 %*********************************************************
669 %*********************************************************
672 newLocalsRn :: [(RdrName,SrcLoc)]
674 newLocalsRn rdr_names_w_loc
675 = newUniqueSupply `thenM` \ us ->
677 uniqs = uniqsFromSupply us
678 names = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
679 | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
685 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
686 -> [(RdrName,SrcLoc)]
689 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
690 = getModeRn `thenM` \ mode ->
691 getLocalRdrEnv `thenM` \ local_env ->
692 getGlobalRdrEnv `thenM` \ global_env ->
694 -- Check for duplicate names
695 checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
697 -- Warn about shadowing, but only in source modules
699 check_shadow (rdr_name,loc)
700 | rdr_name `elemRdrEnv` local_env
701 || rdr_name `elemRdrEnv` global_env
702 = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
708 SourceMode -> ifOptM Opt_WarnNameShadowing $
709 mappM_ check_shadow rdr_names_w_loc
713 newLocalsRn rdr_names_w_loc `thenM` \ names ->
715 new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
717 setLocalRdrEnv new_local_env (enclosed_scope names)
719 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
720 -- A specialised variant when renaming stuff from interface
721 -- files (of which there is a lot)
723 -- * no checks for shadowing
725 -- * deal with free vars
726 bindCoreLocalRn rdr_name enclosed_scope
727 = getSrcLocM `thenM` \ loc ->
728 getLocalRdrEnv `thenM` \ name_env ->
729 newUnique `thenM` \ uniq ->
731 name = mkInternalName uniq (rdrNameOcc rdr_name) loc
732 new_name_env = extendRdrEnv name_env rdr_name name
734 setLocalRdrEnv new_name_env (enclosed_scope name)
736 bindCoreLocalsRn [] thing_inside = thing_inside []
737 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b $ \ name' ->
738 bindCoreLocalsRn bs $ \ names' ->
739 thing_inside (name':names')
741 bindLocalNames names enclosed_scope
742 = getLocalRdrEnv `thenM` \ name_env ->
743 setLocalRdrEnv (extendLocalRdrEnv name_env names)
746 bindLocalNamesFV names enclosed_scope
747 = bindLocalNames names $
748 enclosed_scope `thenM` \ (thing, fvs) ->
749 returnM (thing, delListFromNameSet fvs names)
752 -------------------------------------
753 bindLocalRn doc rdr_name enclosed_scope
754 = getSrcLocM `thenM` \ loc ->
755 bindLocatedLocalsRn doc [(rdr_name,loc)] $ \ (n:ns) ->
759 bindLocalsRn doc rdr_names enclosed_scope
760 = getSrcLocM `thenM` \ loc ->
761 bindLocatedLocalsRn doc
762 (rdr_names `zip` repeat loc)
765 -- binLocalsFVRn is the same as bindLocalsRn
766 -- except that it deals with free vars
767 bindLocalsFVRn doc rdr_names enclosed_scope
768 = bindLocalsRn doc rdr_names $ \ names ->
769 enclosed_scope names `thenM` \ (thing, fvs) ->
770 returnM (thing, delListFromNameSet fvs names)
772 -------------------------------------
773 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
774 -- This tiresome function is used only in rnSourceDecl on InstDecl
775 extendTyVarEnvFVRn tyvars enclosed_scope
776 = bindLocalNames tyvars enclosed_scope `thenM` \ (thing, fvs) ->
777 returnM (thing, delListFromNameSet fvs tyvars)
779 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
780 -> ([HsTyVarBndr Name] -> RnM a)
782 bindTyVarsRn doc_str tyvar_names enclosed_scope
783 = getSrcLocM `thenM` \ loc ->
785 located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names]
787 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
788 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
790 bindPatSigTyVars :: [RdrNameHsType]
793 -- Find the type variables in the pattern type
794 -- signatures that must be brought into scope
796 bindPatSigTyVars tys enclosed_scope
797 = getLocalRdrEnv `thenM` \ name_env ->
798 getSrcLocM `thenM` \ loc ->
800 forall_tyvars = nub [ tv | ty <- tys,
801 tv <- extractHsTyRdrTyVars ty,
802 not (tv `elemFM` name_env)
804 -- The 'nub' is important. For example:
805 -- f (x :: t) (y :: t) = ....
806 -- We don't want to complain about binding t twice!
808 located_tyvars = [(tv, loc) | tv <- forall_tyvars]
809 doc_sig = text "In a pattern type-signature"
811 bindLocatedLocalsRn doc_sig located_tyvars $ \ names ->
812 enclosed_scope `thenM` \ (thing, fvs) ->
813 returnM (thing, delListFromNameSet fvs names)
816 -------------------------------------
817 checkDupOrQualNames, checkDupNames :: SDoc
818 -> [(RdrName, SrcLoc)]
820 -- Works in any variant of the renamer monad
822 checkDupOrQualNames doc_str rdr_names_w_loc
823 = -- Check for use of qualified names
824 mappM_ (qualNameErr doc_str) quals `thenM_`
825 checkDupNames doc_str rdr_names_w_loc
827 quals = filter (isQual . fst) rdr_names_w_loc
829 checkDupNames doc_str rdr_names_w_loc
830 = -- Check for duplicated names in a binding group
831 mappM_ (dupNamesErr doc_str) dups
833 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
837 %************************************************************************
839 \subsection{GlobalRdrEnv}
841 %************************************************************************
844 mkGlobalRdrEnv :: ModuleName -- Imported module (after doing the "as M" name change)
845 -> Bool -- True <=> want unqualified import
846 -> (Name -> Provenance)
847 -> Avails -- Whats imported
851 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
854 -- Make the name environment. We're talking about a
855 -- single module here, so there must be no name clashes.
856 -- In practice there only ever will be if it's the module
859 -- Add qualified names for the things that are available
860 -- (Qualified names are always imported)
861 gbl_env1 = foldl add_avail emptyRdrEnv avails
863 -- Add unqualified names
864 gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
865 | otherwise = gbl_env1
867 add_unqual env (qual_name, elts)
868 = foldl add_one env elts
870 add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
871 unqual_name = unqualifyRdrName qual_name
872 -- The qualified import should only have added one
873 -- binding for each qualified name! But if there's an error in
874 -- the module (multiple bindings for the same name) we may get
875 -- duplicates. So the simple thing is to do the fold.
877 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
878 add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
880 add_name parent env name -- Add qualified name only
881 = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
883 occ = nameOccName name
884 elt = GRE {gre_name = name,
886 gre_prov = mk_provenance name,
887 gre_deprec = lookupDeprec deprecs name}
892 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
893 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
895 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
896 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
898 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv
899 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
901 combine_globals :: [GlobalRdrElt] -- Old
902 -> [GlobalRdrElt] -- New
904 combine_globals ns_old ns_new -- ns_new is often short
905 = foldr add ns_old ns_new
907 add n ns | any (is_duplicate n) ns_old = map (choose n) ns -- Eliminate duplicates
910 choose n m | n `beats` m = n
913 g1 `beats` g2 = gre_name g1 == gre_name g2 &&
914 gre_prov g1 `hasBetterProv` gre_prov g2
916 is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
917 is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
918 is_duplicate g1 g2 = gre_name g1 == gre_name g2
921 We treat two bindings of a locally-defined name as a duplicate,
922 because they might be two separate, local defns and we want to report
923 and error for that, {\em not} eliminate a duplicate.
925 On the other hand, if you import the same name from two different
926 import statements, we {\em do} want to eliminate the duplicate, not report
929 If a module imports itself then there might be a local defn and an imported
930 defn of the same name; in this case the names will compare as equal, but
931 will still have different provenances.
934 %************************************************************************
936 \subsection{Free variable manipulation}
938 %************************************************************************
942 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
944 (ys, fvs_s) = unzip stuff
946 returnM (ys, plusFVs fvs_s)
950 %************************************************************************
952 \subsection{Envt utility functions}
954 %************************************************************************
957 warnUnusedModules :: [ModuleName] -> TcRn m ()
958 warnUnusedModules mods
959 = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
961 unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+>
962 text "is imported, but nothing from it is used",
963 parens (ptext SLIT("except perhaps instances visible in") <+>
966 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
967 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
968 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
970 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
971 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
972 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
974 -------------------------
976 warnUnusedGREs gres = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
977 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
979 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
980 warnUnusedBinds names
981 = mappM_ warnUnusedGroup groups
983 -- Group by provenance
984 groups = equivClasses cmp names
985 (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
988 -------------------------
990 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
991 warnUnusedGroup names
992 | null filtered_names = returnM ()
993 | not is_local = returnM ()
995 = addSrcLoc def_loc $
997 sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
999 filtered_names = filter reportable names
1000 (name1, prov1) = head filtered_names
1001 (is_local, def_loc, msg)
1003 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
1005 NonLocalDef (UserImport mod loc _)
1006 -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
1008 reportable (name,_) = case occNameUserString (nameOccName name) of
1011 -- Haskell 98 encourages compilers to suppress warnings about
1012 -- unused names in a pattern if they start with "_".
1016 addNameClashErrRn rdr_name (np1:nps)
1017 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1018 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1020 msg1 = ptext SLIT("either") <+> mk_ref np1
1021 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1022 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1024 shadowedNameWarn shadow
1025 = hsep [ptext SLIT("This binding for"),
1026 quotes (ppr shadow),
1027 ptext SLIT("shadows an existing binding")]
1030 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1032 flavour = occNameFlavour (rdrNameOcc name)
1035 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1036 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1038 qualNameErr descriptor (name,loc)
1040 addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1043 dupNamesErr descriptor ((name,loc) : dup_things)
1045 addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1049 warnDeprec :: GlobalRdrElt -> TcRn m ()
1050 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1051 = ifOptM Opt_WarnDeprecations $
1052 addWarn (sep [ text (occNameFlavour (nameOccName name)) <+>
1053 quotes (ppr name) <+> text "is deprecated:",