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
11 IMPORT_1_3(List (nub))
14 import CmdLineOpts ( opt_WarnNameShadowing )
16 import RdrHsSyn ( RdrName(..), SYN_IE(RdrNameIE),
17 rdrNameOcc, ieOcc, isQual, qual
19 import HsTypes ( getTyVarName, replaceTyVarName )
20 import BasicTypes ( Fixity(..), FixityDirection(..) )
22 import Name ( Name, OccName(..), Provenance(..), DefnInfo(..), ExportFlag(..), NamedThing(..),
23 occNameString, occNameFlavour,
24 SYN_IE(NameSet), emptyNameSet, addListToNameSet,
25 mkLocalName, mkGlobalName, modAndOcc, isLocallyDefinedName,
26 isWiredInName, nameOccName, setNameProvenance, isVarOcc, getNameProvenance,
27 pprProvenance, pprOccName, pprModule, pprNameProvenance
29 import TyCon ( TyCon )
30 import TysWiredIn ( tupleTyCon, listTyCon, charTyCon, intTyCon )
33 import Unique ( Unique, unboundKey )
34 import UniqFM ( Uniquable(..) )
35 import Maybes ( maybeToBool )
37 import SrcLoc ( SrcLoc, noSrcLoc )
39 import Outputable ( PprStyle(..) )
40 import Util --( panic, removeDups, pprTrace, assertPanic )
46 %*********************************************************
48 \subsection{Making new names}
50 %*********************************************************
53 newGlobalName :: Module -> OccName -> RnM s d Name
55 = -- First check the cache
56 getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
57 let key = (mod,occ) in
58 case lookupFM cache key of
60 -- A hit in the cache! Return it, but change the src loc
61 -- of the thing we've found if this is a second definition site
62 -- (that is, if loc /= NoSrcLoc)
63 Just name -> returnRn name
65 -- Miss in the cache, so build a new original name,
66 -- and put it in the cache
69 (us', us1) = splitUniqSupply us
71 name = mkGlobalName uniq mod occ VanillaDefn Implicit
72 cache' = addToFM cache key name
74 setNameSupplyRn (us', inst_ns, cache') `thenRn_`
77 newLocallyDefinedGlobalName :: Module -> OccName
78 -> (Name -> ExportFlag) -> SrcLoc
80 newLocallyDefinedGlobalName mod occ rec_exp_fn loc
81 = -- First check the cache
82 getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
84 -- We are at the binding site for a locally-defined thing, so
85 -- you might think it can't be in the cache, but it can if it's a
86 -- wired in thing. In that case we need to use the correct unique etc...
87 -- so all we do is replace its provenance.
88 -- If it's not in the cache we put it there with the correct provenance.
89 -- The idea is that, after all this, the cache
90 -- will contain a Name with the correct Provenance (i.e. Local)
92 -- Actually, there's a catch. If this is the *second* binding for something
93 -- we want to allocate a *fresh* unique, rather than using the same Name as before.
94 -- Otherwise we don't detect conflicting definitions of the same top-level name!
95 -- So the only time we re-use a Name already in the cache is when it's one of
96 -- the Implicit magic-unique ones mentioned in the previous para
98 provenance = LocalDef (rec_exp_fn new_name) loc
99 (us', us1) = splitUniqSupply us
102 new_name = case lookupFM cache key of
103 Just name | is_implicit_prov
104 -> setNameProvenance name provenance
106 is_implicit_prov = case getNameProvenance name of
109 other -> mkGlobalName uniq mod occ VanillaDefn provenance
111 new_cache = addToFM cache key new_name
113 setNameSupplyRn (us', inst_ns, new_cache) `thenRn_`
116 -- newSysName is used to create the names for
117 -- a) default methods
118 -- These are never mentioned explicitly in source code (hence no point in looking
119 -- them up in the NameEnv), but when reading an interface file
120 -- we may want to slurp in their pragma info. In the source file itself we
121 -- need to create these names too so that we export them into the inferface file for this module.
123 newSysName :: OccName -> ExportFlag -> SrcLoc -> RnMS s Name
124 newSysName occ export_flag loc
125 = getModeRn `thenRn` \ mode ->
126 getModuleRn `thenRn` \ mod_name ->
128 SourceMode -> newLocallyDefinedGlobalName
132 InterfaceMode _ -> newGlobalName mod_name occ
134 -- newDfunName is a variant, specially for dfuns.
135 -- When renaming derived definitions we are in *interface* mode (because we can trip
136 -- over original names), but we still want to make the Dfun locally-defined.
137 -- So we can't use whether or not we're in source mode to decide the locally-defined question.
138 newDfunName :: Maybe RdrName -> SrcLoc -> RnMS s Name
139 newDfunName Nothing src_loc -- Local instance decls have a "Nothing"
140 = getModuleRn `thenRn` \ mod_name ->
141 newInstUniq `thenRn` \ inst_uniq ->
143 dfun_occ = VarOcc (_PK_ ("$d" ++ show inst_uniq))
145 newLocallyDefinedGlobalName mod_name dfun_occ
146 (\_ -> Exported) src_loc
148 newDfunName (Just n) src_loc -- Imported ones have "Just n"
149 = getModuleRn `thenRn` \ mod_name ->
150 newGlobalName mod_name (rdrNameOcc n)
153 newLocalNames :: [(RdrName,SrcLoc)] -> RnM s d [Name]
154 newLocalNames rdr_names
155 = getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
158 (us', us1) = splitUniqSupply us
159 uniqs = getUniques n us1
160 locals = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
161 | ((rdr_name,loc), uniq) <- rdr_names `zip` uniqs
164 setNameSupplyRn (us', inst_ns, cache) `thenRn_`
167 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
168 -- during compiler debugging.
169 mkUnboundName :: RdrName -> Name
170 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
172 isUnboundName :: Name -> Bool
173 isUnboundName name = uniqueOf name == unboundKey
177 bindLocatedLocalsRn :: (PprStyle -> Doc) -- Documentation string for error message
178 -> [(RdrName,SrcLoc)]
179 -> ([Name] -> RnMS s a)
181 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
182 = checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
184 getNameEnv `thenRn` \ name_env ->
185 (if opt_WarnNameShadowing
187 mapRn (check_shadow name_env) rdr_names_w_loc
192 newLocalNames rdr_names_w_loc `thenRn` \ names ->
194 new_name_env = addListToFM name_env (map fst rdr_names_w_loc `zip` names)
196 setNameEnv new_name_env (enclosed_scope names)
198 check_shadow name_env (rdr_name,loc)
199 = case lookupFM name_env rdr_name of
200 Nothing -> returnRn ()
201 Just name -> pushSrcLocRn loc $
202 addWarnRn (shadowedNameWarn rdr_name)
204 bindLocalsRn doc_str rdr_names enclosed_scope
205 = getSrcLocRn `thenRn` \ loc ->
206 bindLocatedLocalsRn (\_ -> text doc_str)
207 (rdr_names `zip` repeat loc)
210 bindTyVarsRn doc_str tyvar_names enclosed_scope
211 = getSrcLocRn `thenRn` \ loc ->
213 located_tyvars = [(getTyVarName tv, loc) | tv <- tyvar_names]
215 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
216 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
218 -- Works in any variant of the renamer monad
219 checkDupOrQualNames, checkDupNames :: (PprStyle -> Doc)
220 -> [(RdrName, SrcLoc)]
223 checkDupOrQualNames doc_str rdr_names_w_loc
224 = -- Check for use of qualified names
225 mapRn (qualNameErr doc_str) quals `thenRn_`
226 checkDupNames doc_str rdr_names_w_loc
228 quals = filter (isQual.fst) rdr_names_w_loc
230 checkDupNames doc_str rdr_names_w_loc
231 = -- Check for dupicated names in a binding group
232 mapRn (dupNamesErr doc_str) dups `thenRn_`
235 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `cmp` n2) rdr_names_w_loc
239 %*********************************************************
241 \subsection{Looking up names}
243 %*********************************************************
245 Looking up a name in the RnEnv.
248 lookupRn :: NameEnv -> RdrName -> RnMS s Name
249 lookupRn name_env rdr_name
250 = case lookupFM name_env rdr_name of
253 Just name -> returnRn name
256 Nothing -> getModeRn `thenRn` \ mode ->
258 -- Not found when processing source code; so fail
259 SourceMode -> failWithRn (mkUnboundName rdr_name)
260 (unknownNameErr rdr_name)
262 -- Not found when processing an imported declaration,
263 -- so we create a new name for the purpose
267 Qual mod_name occ -> newGlobalName mod_name occ
269 -- An Unqual is allowed; interface files contain
270 -- unqualified names for locally-defined things, such as
271 -- constructors of a data type.
272 Unqual occ -> getModuleRn `thenRn ` \ mod_name ->
273 newGlobalName mod_name occ
276 lookupBndrRn rdr_name
277 = getNameEnv `thenRn` \ name_env ->
278 lookupRn name_env rdr_name
280 -- Just like lookupRn except that we record the occurrence too
281 -- Perhaps surprisingly, even wired-in names are recorded.
282 -- Why? So that we know which wired-in names are referred to when
283 -- deciding which instance declarations to import.
284 lookupOccRn :: RdrName -> RnMS s Name
286 = getNameEnv `thenRn` \ name_env ->
287 lookupRn name_env rdr_name `thenRn` \ name ->
288 addOccurrenceName name
290 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
291 -- environment. It's used for record field names only.
292 lookupGlobalOccRn :: RdrName -> RnMS s Name
293 lookupGlobalOccRn rdr_name
294 = getGlobalNameEnv `thenRn` \ name_env ->
295 lookupRn name_env rdr_name `thenRn` \ name ->
296 addOccurrenceName name
300 -- lookupImplicitOccRn takes an RdrName representing an *original* name, and
301 -- adds it to the occurrence pool so that it'll be loaded later. This is
302 -- used when language constructs (such as monad comprehensions, overloaded literals,
303 -- or deriving clauses) require some stuff to be loaded that isn't explicitly
304 -- mentioned in the code.
306 -- This doesn't apply in interface mode, where everything is explicit, but
307 -- we don't check for this case: it does no harm to record an "extra" occurrence
308 -- and lookupImplicitOccRn isn't used much in interface mode (it's only the
309 -- Nothing clause of rnDerivs that calls it at all I think).
311 -- For List and Tuple types it's important to get the correct
312 -- isLocallyDefined flag, which is used in turn when deciding
313 -- whether there are any instance decls in this module are "special".
314 -- The name cache should have the correct provenance, though.
316 lookupImplicitOccRn :: RdrName -> RnMS s Name
317 lookupImplicitOccRn (Qual mod occ)
318 = newGlobalName mod occ `thenRn` \ name ->
319 addOccurrenceName name
321 addImplicitOccRn :: Name -> RnMS s Name
322 addImplicitOccRn name = addOccurrenceName name
324 addImplicitOccsRn :: [Name] -> RnMS s ()
325 addImplicitOccsRn names = addOccurrenceNames names
327 listType_RDR = qual (modAndOcc listType_name)
328 tupleType_RDR n = qual (modAndOcc (tupleType_name n))
330 charType_name = getName charTyCon
331 listType_name = getName listTyCon
332 tupleType_name n = getName (tupleTyCon n)
336 lookupFixity :: RdrName -> RnMS s Fixity
337 lookupFixity rdr_name
338 = getFixityEnv `thenRn` \ fixity_env ->
339 returnRn (lookupFixityEnv fixity_env rdr_name)
344 %************************************************************************
346 \subsection{Envt utility functions}
348 %************************************************************************
350 =============== RnEnv ================
352 plusRnEnv (RnEnv n1 f1) (RnEnv n2 f2)
353 = plusNameEnvRn n1 n2 `thenRn` \ n ->
354 plusFixityEnvRn f1 f2 `thenRn` \ f ->
358 =============== NameEnv ================
360 plusNameEnvRn :: NameEnv -> NameEnv -> RnM s d NameEnv
362 = mapRn (addErrRn.nameClashErr) (conflictsFM (/=) n1 n2) `thenRn_`
363 returnRn (n1 `plusFM` n2)
365 addOneToNameEnv :: NameEnv -> RdrName -> Name -> RnM s d NameEnv
366 addOneToNameEnv env rdr_name name
367 = case lookupFM env rdr_name of
368 Nothing -> returnRn (addToFM env rdr_name name)
369 Just name2 -> addErrRn (nameClashErr (rdr_name, (name, name2))) `thenRn_`
372 lookupNameEnv :: NameEnv -> RdrName -> Maybe Name
373 lookupNameEnv = lookupFM
375 delOneFromNameEnv :: NameEnv -> RdrName -> NameEnv
376 delOneFromNameEnv env rdr_name = delFromFM env rdr_name
379 =============== FixityEnv ================
381 plusFixityEnvRn f1 f2
382 = mapRn (addErrRn.fixityClashErr) (conflictsFM bad_fix f1 f2) `thenRn_`
383 returnRn (f1 `plusFM` f2)
385 addOneToFixityEnv env rdr_name fixity = addToFM env rdr_name fixity
387 lookupFixityEnv env rdr_name
388 = case lookupFM env rdr_name of
389 Just (fixity,_) -> fixity
390 Nothing -> Fixity 9 InfixL -- Default case
392 bad_fix :: (Fixity, Provenance) -> (Fixity, Provenance) -> Bool
393 bad_fix (f1,_) (f2,_) = f1 /= f2
395 pprFixityProvenance :: PprStyle -> (Fixity,Provenance) -> Doc
396 pprFixityProvenance sty (fixity, prov) = pprProvenance sty prov
401 =============== Avails ================
403 emptyModuleAvails :: ModuleAvails
404 plusModuleAvails :: ModuleAvails -> ModuleAvails -> ModuleAvails
405 lookupModuleAvails :: ModuleAvails -> Module -> Maybe [AvailInfo]
407 emptyModuleAvails = emptyFM
408 plusModuleAvails = plusFM_C (++)
409 lookupModuleAvails = lookupFM
413 =============== AvailInfo ================
415 plusAvail (Avail n1) (Avail n2) = Avail n1
416 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n1 (nub (ns1 ++ ns2))
417 plusAvail a NotAvailable = a
418 plusAvail NotAvailable a = a
421 plusAvail a1 a2 = panic ("RnEnv.plusAvail " ++ (show (hsep [pprAvail PprDebug a1,pprAvail PprDebug a2])))
424 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
425 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
427 availsToNameSet :: [AvailInfo] -> NameSet
428 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
430 availName :: AvailInfo -> Name
431 availName (Avail n) = n
432 availName (AvailTC n _) = n
434 availNames :: AvailInfo -> [Name]
435 availNames NotAvailable = []
436 availNames (Avail n) = [n]
437 availNames (AvailTC n ns) = ns
439 -- availEntityNames is used to extract the names that can appear on their own in
440 -- an export or import list. For class decls, class methods can appear on their
441 -- own, thus import A( op )
442 -- but constructors cannot; thus
444 -- means import type T from B, not constructor T.
446 availEntityNames :: AvailInfo -> [Name]
447 availEntityNames NotAvailable = []
448 availEntityNames (Avail n) = [n]
449 availEntityNames (AvailTC n ns) = n : filter (isVarOcc . nameOccName) ns
451 filterAvail :: RdrNameIE -- Wanted
452 -> AvailInfo -- Available
453 -> AvailInfo -- Resulting available;
454 -- NotAvailable if wanted stuff isn't there
456 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
457 | sub_names_ok = AvailTC n (filter is_wanted ns)
458 | otherwise = pprTrace "filterAvail" (hsep [ppr PprDebug ie, pprAvail PprDebug avail]) $
461 is_wanted name = nameOccName name `elem` wanted_occs
462 sub_names_ok = all (`elem` avail_occs) wanted_occs
463 avail_occs = map nameOccName ns
464 wanted_occs = map rdrNameOcc (want:wants)
466 filterAvail (IEThingAbs _) (AvailTC n ns)
467 | n `elem` ns = AvailTC n [n]
469 filterAvail (IEThingAbs _) avail@(Avail n) = avail -- Type synonyms
471 filterAvail (IEVar _) avail@(Avail n) = avail
472 filterAvail (IEVar v) avail@(AvailTC n ns) = AvailTC n (filter wanted ns)
474 wanted n = nameOccName n == occ
476 -- The second equation happens if we import a class op, thus
478 -- where op is a class operation
480 filterAvail (IEThingAll _) avail@(AvailTC _ _) = avail
482 filterAvail ie avail = NotAvailable
485 -- In interfaces, pprAvail gets given the OccName of the "host" thing
486 pprAvail PprInterface avail = ppr_avail (pprOccName PprInterface . nameOccName) avail
487 pprAvail sty avail = ppr_avail (ppr sty) avail
489 ppr_avail pp_name NotAvailable = ptext SLIT("NotAvailable")
490 ppr_avail pp_name (AvailTC n ns) = hsep [
492 parens $ hsep $ punctuate comma $
495 ppr_avail pp_name (Avail n) = pp_name n
501 %************************************************************************
503 \subsection{Finite map utilities}
505 %************************************************************************
508 Generally useful function on finite maps to check for overlap.
512 => (b->b->Bool) -- False <=> no conflict; you can pick either
513 -> FiniteMap a b -> FiniteMap a b
515 conflictsFM bad fm1 fm2
516 = filter (\(a,(b1,b2)) -> bad b1 b2)
517 (fmToList (intersectFM_C (\b1 b2 -> (b1,b2)) fm1 fm2))
521 -> FiniteMap a b -> a -> b
523 conflictFM bad fm key elt
524 = case lookupFM fm key of
525 Just elt' | bad elt elt' -> [(key,(elt,elt'))]
530 %************************************************************************
532 \subsection{Envt utility functions}
534 %************************************************************************
538 nameClashErr (rdr_name, (name1,name2)) sty
539 = hang (hsep [ptext SLIT("Conflicting definitions for:"), ppr sty rdr_name])
540 4 (vcat [pprNameProvenance sty name1,
541 pprNameProvenance sty name2])
543 fixityClashErr (rdr_name, (fp1,fp2)) sty
544 = hang (hsep [ptext SLIT("Conflicting fixities for:"), ppr sty rdr_name])
545 4 (vcat [pprFixityProvenance sty fp1,
546 pprFixityProvenance sty fp2])
548 shadowedNameWarn shadow sty
549 = hcat [ptext SLIT("This binding for"),
551 ptext SLIT("shadows an existing binding")]
553 unknownNameErr name sty
554 = sep [text flavour, ptext SLIT("not in scope:"), ppr sty name]
556 flavour = occNameFlavour (rdrNameOcc name)
558 qualNameErr descriptor (name,loc)
560 addErrRn (\sty -> hsep [ ptext SLIT("Invalid use of qualified name"),
565 dupNamesErr descriptor ((name,loc) : dup_things)
567 addErrRn (\sty -> hsep [ptext SLIT("Conflicting definitions for"),
569 ptext SLIT("in"), descriptor sty])