2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[RnEnv]{Environment manipulation for the renamer monad}
7 #include "HsVersions.h"
9 module RnEnv where -- Export everything
13 import CmdLineOpts ( opt_WarnNameShadowing )
15 import RdrHsSyn ( RdrName(..), SYN_IE(RdrNameIE),
16 rdrNameOcc, ieOcc, isQual, qual
18 import HsTypes ( getTyVarName, replaceTyVarName )
19 import BasicTypes ( Fixity(..), FixityDirection(..) )
21 import Name ( Name, OccName(..), Provenance(..), DefnInfo(..), ExportFlag(..), NamedThing(..),
22 occNameString, occNameFlavour,
23 SYN_IE(NameSet), emptyNameSet, addListToNameSet,
24 mkLocalName, mkGlobalName, modAndOcc, isLocallyDefinedName,
25 isWiredInName, nameOccName, setNameProvenance, isVarOcc, getNameProvenance,
26 pprProvenance, pprOccName, pprModule, pprNameProvenance
28 import TyCon ( TyCon )
29 import TysWiredIn ( tupleTyCon, listTyCon, charTyCon, intTyCon )
32 import Unique ( Unique, unboundKey )
33 import UniqFM ( Uniquable(..) )
34 import Maybes ( maybeToBool )
36 import SrcLoc ( SrcLoc, noSrcLoc )
38 import Outputable ( PprStyle(..) )
39 import Util --( panic, removeDups, pprTrace, assertPanic )
40 #if __GLASGOW_HASKELL__ >= 202
47 %*********************************************************
49 \subsection{Making new names}
51 %*********************************************************
54 newGlobalName :: Module -> OccName -> RnM s d Name
56 = -- First check the cache
57 getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
58 let key = (mod,occ) in
59 case lookupFM cache key of
61 -- A hit in the cache! Return it, but change the src loc
62 -- of the thing we've found if this is a second definition site
63 -- (that is, if loc /= NoSrcLoc)
64 Just name -> returnRn name
66 -- Miss in the cache, so build a new original name,
67 -- and put it in the cache
70 (us', us1) = splitUniqSupply us
72 name = mkGlobalName uniq mod occ VanillaDefn Implicit
73 cache' = addToFM cache key name
75 setNameSupplyRn (us', inst_ns, cache') `thenRn_`
78 newLocallyDefinedGlobalName :: Module -> OccName
79 -> (Name -> ExportFlag) -> SrcLoc
81 newLocallyDefinedGlobalName mod occ rec_exp_fn loc
82 = -- First check the cache
83 getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
85 -- We are at the binding site for a locally-defined thing, so
86 -- you might think it can't be in the cache, but it can if it's a
87 -- wired in thing. In that case we need to use the correct unique etc...
88 -- so all we do is replace its provenance.
89 -- If it's not in the cache we put it there with the correct provenance.
90 -- The idea is that, after all this, the cache
91 -- will contain a Name with the correct Provenance (i.e. Local)
93 -- Actually, there's a catch. If this is the *second* binding for something
94 -- we want to allocate a *fresh* unique, rather than using the same Name as before.
95 -- Otherwise we don't detect conflicting definitions of the same top-level name!
96 -- So the only time we re-use a Name already in the cache is when it's one of
97 -- the Implicit magic-unique ones mentioned in the previous para
99 provenance = LocalDef (rec_exp_fn new_name) loc
100 (us', us1) = splitUniqSupply us
103 new_name = case lookupFM cache key of
104 Just name | is_implicit_prov
105 -> setNameProvenance name provenance
107 is_implicit_prov = case getNameProvenance name of
110 other -> mkGlobalName uniq mod occ VanillaDefn provenance
112 new_cache = addToFM cache key new_name
114 setNameSupplyRn (us', inst_ns, new_cache) `thenRn_`
117 -- newSysName is used to create the names for
118 -- a) default methods
119 -- These are never mentioned explicitly in source code (hence no point in looking
120 -- them up in the NameEnv), but when reading an interface file
121 -- we may want to slurp in their pragma info. In the source file itself we
122 -- need to create these names too so that we export them into the inferface file for this module.
124 newSysName :: OccName -> ExportFlag -> SrcLoc -> RnMS s Name
125 newSysName occ export_flag loc
126 = getModeRn `thenRn` \ mode ->
127 getModuleRn `thenRn` \ mod_name ->
129 SourceMode -> newLocallyDefinedGlobalName
133 InterfaceMode _ -> newGlobalName mod_name occ
135 -- newDfunName is a variant, specially for dfuns.
136 -- When renaming derived definitions we are in *interface* mode (because we can trip
137 -- over original names), but we still want to make the Dfun locally-defined.
138 -- So we can't use whether or not we're in source mode to decide the locally-defined question.
139 newDfunName :: Maybe RdrName -> SrcLoc -> RnMS s Name
140 newDfunName Nothing src_loc -- Local instance decls have a "Nothing"
141 = getModuleRn `thenRn` \ mod_name ->
142 newInstUniq `thenRn` \ inst_uniq ->
144 dfun_occ = VarOcc (_PK_ ("$d" ++ show inst_uniq))
146 newLocallyDefinedGlobalName mod_name dfun_occ
147 (\_ -> Exported) src_loc
149 newDfunName (Just n) src_loc -- Imported ones have "Just n"
150 = getModuleRn `thenRn` \ mod_name ->
151 newGlobalName mod_name (rdrNameOcc n)
154 newLocalNames :: [(RdrName,SrcLoc)] -> RnM s d [Name]
155 newLocalNames rdr_names
156 = getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
159 (us', us1) = splitUniqSupply us
160 uniqs = getUniques n us1
161 locals = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
162 | ((rdr_name,loc), uniq) <- rdr_names `zip` uniqs
165 setNameSupplyRn (us', inst_ns, cache) `thenRn_`
168 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
169 -- during compiler debugging.
170 mkUnboundName :: RdrName -> Name
171 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
173 isUnboundName :: Name -> Bool
174 isUnboundName name = uniqueOf name == unboundKey
178 bindLocatedLocalsRn :: (PprStyle -> Doc) -- Documentation string for error message
179 -> [(RdrName,SrcLoc)]
180 -> ([Name] -> RnMS s a)
182 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
183 = checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
185 getNameEnv `thenRn` \ name_env ->
186 (if opt_WarnNameShadowing
188 mapRn (check_shadow name_env) rdr_names_w_loc
193 newLocalNames rdr_names_w_loc `thenRn` \ names ->
195 new_name_env = addListToFM name_env (map fst rdr_names_w_loc `zip` names)
197 setNameEnv new_name_env (enclosed_scope names)
199 check_shadow name_env (rdr_name,loc)
200 = case lookupFM name_env rdr_name of
201 Nothing -> returnRn ()
202 Just name -> pushSrcLocRn loc $
203 addWarnRn (shadowedNameWarn rdr_name)
205 bindLocalsRn doc_str rdr_names enclosed_scope
206 = getSrcLocRn `thenRn` \ loc ->
207 bindLocatedLocalsRn (\_ -> text doc_str)
208 (rdr_names `zip` repeat loc)
211 bindTyVarsRn doc_str tyvar_names enclosed_scope
212 = getSrcLocRn `thenRn` \ loc ->
214 located_tyvars = [(getTyVarName tv, loc) | tv <- tyvar_names]
216 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
217 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
219 -- Works in any variant of the renamer monad
220 checkDupOrQualNames, checkDupNames :: (PprStyle -> Doc)
221 -> [(RdrName, SrcLoc)]
224 checkDupOrQualNames doc_str rdr_names_w_loc
225 = -- Check for use of qualified names
226 mapRn (qualNameErr doc_str) quals `thenRn_`
227 checkDupNames doc_str rdr_names_w_loc
229 quals = filter (isQual.fst) rdr_names_w_loc
231 checkDupNames doc_str rdr_names_w_loc
232 = -- Check for dupicated names in a binding group
233 mapRn (dupNamesErr doc_str) dups `thenRn_`
236 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `cmp` n2) rdr_names_w_loc
240 %*********************************************************
242 \subsection{Looking up names}
244 %*********************************************************
246 Looking up a name in the RnEnv.
249 lookupRn :: NameEnv -> RdrName -> RnMS s Name
250 lookupRn name_env rdr_name
251 = case lookupFM name_env rdr_name of
254 Just name -> returnRn name
257 Nothing -> getModeRn `thenRn` \ mode ->
259 -- Not found when processing source code; so fail
260 SourceMode -> failWithRn (mkUnboundName rdr_name)
261 (unknownNameErr rdr_name)
263 -- Not found when processing an imported declaration,
264 -- so we create a new name for the purpose
268 Qual mod_name occ -> newGlobalName mod_name occ
270 -- An Unqual is allowed; interface files contain
271 -- unqualified names for locally-defined things, such as
272 -- constructors of a data type.
273 Unqual occ -> getModuleRn `thenRn ` \ mod_name ->
274 newGlobalName mod_name occ
277 lookupBndrRn rdr_name
278 = getNameEnv `thenRn` \ name_env ->
279 lookupRn name_env rdr_name
281 -- Just like lookupRn except that we record the occurrence too
282 -- Perhaps surprisingly, even wired-in names are recorded.
283 -- Why? So that we know which wired-in names are referred to when
284 -- deciding which instance declarations to import.
285 lookupOccRn :: RdrName -> RnMS s Name
287 = getNameEnv `thenRn` \ name_env ->
288 lookupRn name_env rdr_name `thenRn` \ name ->
289 addOccurrenceName name
291 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
292 -- environment. It's used for record field names only.
293 lookupGlobalOccRn :: RdrName -> RnMS s Name
294 lookupGlobalOccRn rdr_name
295 = getGlobalNameEnv `thenRn` \ name_env ->
296 lookupRn name_env rdr_name `thenRn` \ name ->
297 addOccurrenceName name
301 -- lookupImplicitOccRn takes an RdrName representing an *original* name, and
302 -- adds it to the occurrence pool so that it'll be loaded later. This is
303 -- used when language constructs (such as monad comprehensions, overloaded literals,
304 -- or deriving clauses) require some stuff to be loaded that isn't explicitly
305 -- mentioned in the code.
307 -- This doesn't apply in interface mode, where everything is explicit, but
308 -- we don't check for this case: it does no harm to record an "extra" occurrence
309 -- and lookupImplicitOccRn isn't used much in interface mode (it's only the
310 -- Nothing clause of rnDerivs that calls it at all I think).
312 -- For List and Tuple types it's important to get the correct
313 -- isLocallyDefined flag, which is used in turn when deciding
314 -- whether there are any instance decls in this module are "special".
315 -- The name cache should have the correct provenance, though.
317 lookupImplicitOccRn :: RdrName -> RnMS s Name
318 lookupImplicitOccRn (Qual mod occ)
319 = newGlobalName mod occ `thenRn` \ name ->
320 addOccurrenceName name
322 addImplicitOccRn :: Name -> RnMS s Name
323 addImplicitOccRn name = addOccurrenceName name
325 addImplicitOccsRn :: [Name] -> RnMS s ()
326 addImplicitOccsRn names = addOccurrenceNames names
328 listType_RDR = qual (modAndOcc listType_name)
329 tupleType_RDR n = qual (modAndOcc (tupleType_name n))
331 charType_name = getName charTyCon
332 listType_name = getName listTyCon
333 tupleType_name n = getName (tupleTyCon n)
337 lookupFixity :: RdrName -> RnMS s Fixity
338 lookupFixity rdr_name
339 = getFixityEnv `thenRn` \ fixity_env ->
340 returnRn (lookupFixityEnv fixity_env rdr_name)
345 %************************************************************************
347 \subsection{Envt utility functions}
349 %************************************************************************
351 =============== RnEnv ================
353 plusRnEnv (RnEnv n1 f1) (RnEnv n2 f2)
354 = plusNameEnvRn n1 n2 `thenRn` \ n ->
355 plusFixityEnvRn f1 f2 `thenRn` \ f ->
359 =============== NameEnv ================
361 plusNameEnvRn :: NameEnv -> NameEnv -> RnM s d NameEnv
363 = mapRn (addErrRn.nameClashErr) (conflictsFM (/=) n1 n2) `thenRn_`
364 returnRn (n1 `plusFM` n2)
366 addOneToNameEnv :: NameEnv -> RdrName -> Name -> NameEnv
367 addOneToNameEnv env rdr_name name = addToFM env rdr_name name
369 lookupNameEnv :: NameEnv -> RdrName -> Maybe Name
370 lookupNameEnv = lookupFM
372 delOneFromNameEnv :: NameEnv -> RdrName -> NameEnv
373 delOneFromNameEnv env rdr_name = delFromFM env rdr_name
376 =============== FixityEnv ================
378 plusFixityEnvRn f1 f2
379 = mapRn (addErrRn.fixityClashErr) (conflictsFM bad_fix f1 f2) `thenRn_`
380 returnRn (f1 `plusFM` f2)
382 addOneToFixityEnv env rdr_name fixity = addToFM env rdr_name fixity
384 lookupFixityEnv env rdr_name
385 = case lookupFM env rdr_name of
386 Just (fixity,_) -> fixity
387 Nothing -> Fixity 9 InfixL -- Default case
389 bad_fix :: (Fixity, Provenance) -> (Fixity, Provenance) -> Bool
390 bad_fix (f1,_) (f2,_) = f1 /= f2
392 pprFixityProvenance :: PprStyle -> (Fixity,Provenance) -> Doc
393 pprFixityProvenance sty (fixity, prov) = pprProvenance sty prov
398 =============== Avails ================
400 emptyModuleAvails :: ModuleAvails
401 plusModuleAvails :: ModuleAvails -> ModuleAvails -> ModuleAvails
402 lookupModuleAvails :: ModuleAvails -> Module -> Maybe [AvailInfo]
404 emptyModuleAvails = emptyFM
405 plusModuleAvails = plusFM_C (++)
406 lookupModuleAvails = lookupFM
410 =============== AvailInfo ================
412 plusAvail (Avail n1) (Avail n2) = Avail n1
413 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n1 (nub (ns1 ++ ns2))
414 plusAvail a NotAvailable = a
415 plusAvail NotAvailable a = a
418 plusAvail a1 a2 = panic ("RnEnv.plusAvail " ++ (show (hsep [pprAvail PprDebug a1,pprAvail PprDebug a2])))
421 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
422 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
424 availsToNameSet :: [AvailInfo] -> NameSet
425 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
427 availName :: AvailInfo -> Name
428 availName (Avail n) = n
429 availName (AvailTC n _) = n
431 availNames :: AvailInfo -> [Name]
432 availNames NotAvailable = []
433 availNames (Avail n) = [n]
434 availNames (AvailTC n ns) = ns
436 -- availEntityNames is used to extract the names that can appear on their own in
437 -- an export or import list. For class decls, class methods can appear on their
438 -- own, thus import A( op )
439 -- but constructors cannot; thus
441 -- means import type T from B, not constructor T.
443 availEntityNames :: AvailInfo -> [Name]
444 availEntityNames NotAvailable = []
445 availEntityNames (Avail n) = [n]
446 availEntityNames (AvailTC n ns) = n : filter (isVarOcc . nameOccName) ns
448 filterAvail :: RdrNameIE -- Wanted
449 -> AvailInfo -- Available
450 -> AvailInfo -- Resulting available;
451 -- NotAvailable if wanted stuff isn't there
453 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
454 | sub_names_ok = AvailTC n (filter is_wanted ns)
455 | otherwise = pprTrace "filterAvail" (hsep [ppr PprDebug ie, pprAvail PprDebug avail]) $
458 is_wanted name = nameOccName name `elem` wanted_occs
459 sub_names_ok = all (`elem` avail_occs) wanted_occs
460 avail_occs = map nameOccName ns
461 wanted_occs = map rdrNameOcc (want:wants)
463 filterAvail (IEThingAbs _) (AvailTC n ns)
464 | n `elem` ns = AvailTC n [n]
466 filterAvail (IEThingAbs _) avail@(Avail n) = avail -- Type synonyms
468 filterAvail (IEVar _) avail@(Avail n) = avail
469 filterAvail (IEVar v) avail@(AvailTC n ns) = AvailTC n (filter wanted ns)
471 wanted n = nameOccName n == occ
473 -- The second equation happens if we import a class op, thus
475 -- where op is a class operation
477 filterAvail (IEThingAll _) avail@(AvailTC _ _) = avail
479 filterAvail ie avail = NotAvailable
482 -- In interfaces, pprAvail gets given the OccName of the "host" thing
483 pprAvail PprInterface avail = ppr_avail (pprOccName PprInterface . nameOccName) avail
484 pprAvail sty avail = ppr_avail (ppr sty) avail
486 ppr_avail pp_name NotAvailable = ptext SLIT("NotAvailable")
487 ppr_avail pp_name (AvailTC n ns) = hsep [
489 parens $ hsep $ punctuate comma $
492 ppr_avail pp_name (Avail n) = pp_name n
498 %************************************************************************
500 \subsection{Finite map utilities}
502 %************************************************************************
505 Generally useful function on finite maps to check for overlap.
509 => (b->b->Bool) -- False <=> no conflict; you can pick either
510 -> FiniteMap a b -> FiniteMap a b
512 conflictsFM bad fm1 fm2
513 = filter (\(a,(b1,b2)) -> bad b1 b2)
514 (fmToList (intersectFM_C (\b1 b2 -> (b1,b2)) fm1 fm2))
518 -> FiniteMap a b -> a -> b
520 conflictFM bad fm key elt
521 = case lookupFM fm key of
522 Just elt' | bad elt elt' -> [(key,(elt,elt'))]
527 %************************************************************************
529 \subsection{Envt utility functions}
531 %************************************************************************
535 nameClashErr (rdr_name, (name1,name2)) sty
536 = hang (hsep [ptext SLIT("Conflicting definitions for:"), ppr sty rdr_name])
537 4 (vcat [pprNameProvenance sty name1,
538 pprNameProvenance sty name2])
540 fixityClashErr (rdr_name, (fp1,fp2)) sty
541 = hang (hsep [ptext SLIT("Conflicting fixities for:"), ppr sty rdr_name])
542 4 (vcat [pprFixityProvenance sty fp1,
543 pprFixityProvenance sty fp2])
545 shadowedNameWarn shadow sty
546 = hcat [ptext SLIT("This binding for"),
548 ptext SLIT("shadows an existing binding")]
550 unknownNameErr name sty
551 = sep [text flavour, ptext SLIT("not in scope:"), ppr sty name]
553 flavour = occNameFlavour (rdrNameOcc name)
555 qualNameErr descriptor (name,loc)
557 addErrRn (\sty -> hsep [ ptext SLIT("Invalid use of qualified name"),
562 dupNamesErr descriptor ((name,loc) : dup_things)
564 addErrRn (\sty -> hsep [ptext SLIT("Conflicting definitions for"),
566 ptext SLIT("in"), descriptor sty])