2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[RnEnv]{Environment manipulation for the renamer monad}
7 module RnEnv where -- Export everything
9 #include "HsVersions.h"
11 import CmdLineOpts ( opt_WarnNameShadowing, opt_WarnUnusedMatches,
12 opt_WarnUnusedBinds, opt_WarnUnusedImports )
14 import RdrHsSyn ( RdrName(..), RdrNameIE,
15 rdrNameOcc, ieOcc, isQual, qual
17 import HsTypes ( getTyVarName, replaceTyVarName )
18 import BasicTypes ( Fixity(..), FixityDirection(..), IfaceFlavour(..), pprModule )
20 import Name ( Name, OccName(..), Provenance(..), ExportFlag(..), NamedThing(..),
21 occNameString, occNameFlavour, getSrcLoc,
22 NameSet, emptyNameSet, addListToNameSet, nameSetToList,
23 mkLocalName, mkGlobalName, modAndOcc,
24 nameOccName, setNameProvenance, isVarOcc, getNameProvenance,
25 pprProvenance, pprOccName, pprModule, pprNameProvenance,
28 import TyCon ( TyCon )
29 import TysWiredIn ( tupleTyCon, listTyCon, charTyCon, intTyCon )
31 import Unique ( Unique, Uniquable(..), unboundKey )
32 import UniqFM ( listToUFM, plusUFM_C )
33 import Maybes ( maybeToBool )
35 import SrcLoc ( SrcLoc, noSrcLoc )
37 import Util ( removeDups )
43 %*********************************************************
45 \subsection{Making new names}
47 %*********************************************************
50 newImportedGlobalName :: Module -> OccName
53 newImportedGlobalName mod occ hif
54 = -- First check the cache
55 getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
58 prov = NonLocalDef noSrcLoc hif False
60 case lookupFM cache key of
62 -- A hit in the cache!
63 -- If it has no provenance at the moment then set its provenance
64 -- so that it has the right HiFlag component.
66 -- for known-key things. For example, GHCmain.lhs imports as SOURCE
67 -- Main; but Main.main is a known-key thing.)
68 -- Don't fiddle with the provenance if it already has one
69 Just name -> case getNameProvenance name of
71 new_name = setNameProvenance name prov
72 new_cache = addToFM cache key new_name
74 setNameSupplyRn (us, inst_ns, new_cache) `thenRn_`
76 other -> returnRn name
78 Nothing -> -- Miss in the cache!
79 -- Build a new original name, and put it in the cache
81 (us', us1) = splitUniqSupply us
83 name = mkGlobalName uniq mod occ prov
84 new_cache = addToFM cache key name
86 setNameSupplyRn (us', inst_ns, new_cache) `thenRn_`
91 pprC ((mod,occ),name) = pprModule mod <> text "." <> pprOccName occ <+> text "--->"
94 pprTrace "ng" (vcat [text "newGlobalName miss" <+> pprModule mod <+> pprOccName occ,
95 brackets (sep (map pprC (fmToList cache))),
101 newLocallyDefinedGlobalName :: Module -> OccName
102 -> (Name -> ExportFlag) -> SrcLoc
104 newLocallyDefinedGlobalName mod occ rec_exp_fn loc
105 = -- First check the cache
106 getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
110 case lookupFM cache key of
112 -- A hit in the cache!
113 -- Overwrite whatever provenance is in the cache already;
114 -- this updates WiredIn things and known-key things,
115 -- which are there from the start, to LocalDef.
117 new_name = setNameProvenance name (LocalDef loc (rec_exp_fn new_name))
118 new_cache = addToFM cache key new_name
120 setNameSupplyRn (us, inst_ns, new_cache) `thenRn_`
123 -- Miss in the cache!
124 -- Build a new original name, and put it in the cache
126 provenance = LocalDef loc (rec_exp_fn new_name)
127 (us', us1) = splitUniqSupply us
129 new_name = mkGlobalName uniq mod occ provenance
130 new_cache = addToFM cache key new_name
132 setNameSupplyRn (us', inst_ns, new_cache) `thenRn_`
136 -- newDfunName is a variant, specially for dfuns.
137 -- When renaming derived definitions we are in *interface* mode (because we can trip
138 -- over original names), but we still want to make the Dfun locally-defined.
139 -- So we can't use whether or not we're in source mode to decide the locally-defined question.
140 newDfunName :: Maybe RdrName -> SrcLoc -> RnMS s Name
141 newDfunName Nothing src_loc -- Local instance decls have a "Nothing"
142 = getModuleRn `thenRn` \ mod_name ->
143 newInstUniq `thenRn` \ inst_uniq ->
145 dfun_occ = VarOcc (_PK_ ("$d" ++ show inst_uniq))
147 newLocallyDefinedGlobalName mod_name dfun_occ
148 (\_ -> Exported) src_loc
150 newDfunName (Just n) src_loc -- Imported ones have "Just n"
151 = getModuleRn `thenRn` \ mod_name ->
152 newImportedGlobalName mod_name (rdrNameOcc n) HiFile {- Correct? -}
155 newLocalNames :: [(RdrName,SrcLoc)] -> RnM s d [Name]
156 newLocalNames rdr_names
157 = getNameSupplyRn `thenRn` \ (us, inst_ns, cache) ->
160 (us', us1) = splitUniqSupply us
161 uniqs = getUniques n us1
162 locals = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
163 | ((rdr_name,loc), uniq) <- rdr_names `zip` uniqs
166 setNameSupplyRn (us', inst_ns, cache) `thenRn_`
169 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
170 -- during compiler debugging.
171 mkUnboundName :: RdrName -> Name
172 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
174 isUnboundName :: Name -> Bool
175 isUnboundName name = uniqueOf name == unboundKey
179 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
180 -> [(RdrName,SrcLoc)]
181 -> ([Name] -> RnMS s a)
183 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
184 = checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
186 getLocalNameEnv `thenRn` \ name_env ->
187 (if opt_WarnNameShadowing
189 mapRn (check_shadow name_env) rdr_names_w_loc
194 newLocalNames rdr_names_w_loc `thenRn` \ names ->
196 new_name_env = addListToFM name_env (map fst rdr_names_w_loc `zip` names)
198 setLocalNameEnv new_name_env (enclosed_scope names)
200 check_shadow name_env (rdr_name,loc)
201 = case lookupFM name_env rdr_name of
202 Nothing -> returnRn ()
203 Just name -> pushSrcLocRn loc $
204 addWarnRn (shadowedNameWarn rdr_name)
206 bindLocalsRn doc_str rdr_names enclosed_scope
207 = getSrcLocRn `thenRn` \ loc ->
208 bindLocatedLocalsRn (text doc_str)
209 (rdr_names `zip` repeat loc)
212 bindTyVarsRn doc_str tyvar_names enclosed_scope
213 = getSrcLocRn `thenRn` \ loc ->
215 located_tyvars = [(getTyVarName tv, loc) | tv <- tyvar_names]
217 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
218 enclosed_scope (zipWith replaceTyVarName tyvar_names names)
220 -- Works in any variant of the renamer monad
221 checkDupOrQualNames, checkDupNames :: SDoc
222 -> [(RdrName, SrcLoc)]
225 checkDupOrQualNames doc_str rdr_names_w_loc
226 = -- Check for use of qualified names
227 mapRn (qualNameErr doc_str) quals `thenRn_`
228 checkDupNames doc_str rdr_names_w_loc
230 quals = filter (isQual.fst) rdr_names_w_loc
232 checkDupNames doc_str rdr_names_w_loc
233 = -- Check for dupicated names in a binding group
234 mapRn (dupNamesErr doc_str) dups `thenRn_`
237 (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
241 ifaceFlavour name = case getNameProvenance name of
242 NonLocalDef _ hif _ -> hif
243 other -> HiFile -- Shouldn't happen
247 %*********************************************************
249 \subsection{Looking up names}
251 %*********************************************************
253 Looking up a name in the RnEnv.
257 -> Maybe Name -- Result of environment lookup
260 lookupRn rdr_name (Just name)
261 = -- Found the name in the envt
262 returnRn name -- In interface mode the only things in
263 -- the environment are things in local (nested) scopes
265 lookupRn rdr_name Nothing
266 = -- We didn't find the name in the environment
267 getModeRn `thenRn` \ mode ->
269 SourceMode -> failWithRn (mkUnboundName rdr_name)
270 (unknownNameErr rdr_name) ;
271 -- Souurce mode; lookup failure is an error
276 ----------------------------------------------------
277 -- OK, so we're in interface mode
278 -- An Unqual is allowed; interface files contain
279 -- unqualified names for locally-defined things, such as
280 -- constructors of a data type.
281 -- So, qualify the unqualified name with the
282 -- module of the interface file, and try again
284 Unqual occ -> getModuleRn `thenRn` \ mod ->
285 newImportedGlobalName mod occ HiFile
286 Qual mod occ hif -> newImportedGlobalName mod occ hif
290 lookupBndrRn rdr_name
291 = lookupNameRn rdr_name `thenRn` \ maybe_name ->
292 lookupRn rdr_name maybe_name `thenRn` \ name ->
294 if isLocalName name then
298 ----------------------------------------------------
299 -- OK, so we're at the binding site of a top-level defn
300 -- Check to see whether its an imported decl
301 getModeRn `thenRn` \ mode ->
303 SourceMode -> returnRn name ;
305 InterfaceMode _ print_unqual_fn ->
307 ----------------------------------------------------
308 -- OK, the binding site of an *imported* defn
309 -- so we can make the provenance more informative
310 getSrcLocRn `thenRn` \ src_loc ->
312 name' = case getNameProvenance name of
313 NonLocalDef _ hif _ -> setNameProvenance name
314 (NonLocalDef src_loc hif (print_unqual_fn name'))
320 -- Just like lookupRn except that we record the occurrence too
321 -- Perhaps surprisingly, even wired-in names are recorded.
322 -- Why? So that we know which wired-in names are referred to when
323 -- deciding which instance declarations to import.
324 lookupOccRn :: RdrName -> RnMS s Name
326 = lookupNameRn rdr_name `thenRn` \ maybe_name ->
327 lookupRn rdr_name maybe_name `thenRn` \ name ->
329 name' = mungePrintUnqual rdr_name name
331 addOccurrenceName name'
333 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
334 -- environment only. It's used for record field names only.
335 lookupGlobalOccRn :: RdrName -> RnMS s Name
336 lookupGlobalOccRn rdr_name
337 = lookupGlobalNameRn rdr_name `thenRn` \ maybe_name ->
338 lookupRn rdr_name maybe_name `thenRn` \ name ->
340 name' = mungePrintUnqual rdr_name name
342 addOccurrenceName name'
344 -- mungePrintUnqual is used to make *imported* *occurrences* print unqualified
345 -- if they were mentioned unqualified in the source code.
346 -- This improves error messages from the type checker.
347 -- NB: the binding site is treated differently; see lookupBndrRn
348 -- After the type checker all occurrences are replaced by the one
349 -- at the binding site.
350 mungePrintUnqual (Qual _ _ _) name = name
351 mungePrintUnqual (Unqual _) name = case new_prov of
353 Just prov' -> setNameProvenance name prov'
355 new_prov = case getNameProvenance name of
356 NonLocalDef loc hif False -> Just (NonLocalDef loc hif True)
359 -- lookupImplicitOccRn takes an RdrName representing an *original* name, and
360 -- adds it to the occurrence pool so that it'll be loaded later. This is
361 -- used when language constructs (such as monad comprehensions, overloaded literals,
362 -- or deriving clauses) require some stuff to be loaded that isn't explicitly
363 -- mentioned in the code.
365 -- This doesn't apply in interface mode, where everything is explicit, but
366 -- we don't check for this case: it does no harm to record an "extra" occurrence
367 -- and lookupImplicitOccRn isn't used much in interface mode (it's only the
368 -- Nothing clause of rnDerivs that calls it at all I think).
369 -- [Jan 98: this comment is wrong: rnHsType uses it quite a bit.]
371 -- For List and Tuple types it's important to get the correct
372 -- isLocallyDefined flag, which is used in turn when deciding
373 -- whether there are any instance decls in this module are "special".
374 -- The name cache should have the correct provenance, though.
376 lookupImplicitOccRn :: RdrName -> RnMS s Name
377 lookupImplicitOccRn (Qual mod occ hif)
378 = newImportedGlobalName mod occ hif `thenRn` \ name ->
379 addOccurrenceName name
381 addImplicitOccRn :: Name -> RnMS s Name
382 addImplicitOccRn name = addOccurrenceName name
384 addImplicitOccsRn :: [Name] -> RnMS s ()
385 addImplicitOccsRn names = addOccurrenceNames names
387 listType_RDR = qual (modAndOcc listType_name)
388 tupleType_RDR n = qual (modAndOcc (tupleType_name n))
390 charType_name = getName charTyCon
391 listType_name = getName listTyCon
392 tupleType_name n = getName (tupleTyCon n)
396 lookupFixity :: RdrName -> RnMS s Fixity
397 lookupFixity rdr_name
398 = getFixityEnv `thenRn` \ fixity_env ->
399 returnRn (lookupFixityEnv fixity_env rdr_name)
402 mkImportFn returns a function that takes a Name and tells whether
403 its unqualified name is in scope. This is put as a boolean flag in
404 the Name's provenance to guide whether or not to print the name qualified
408 mkImportFn :: RnEnv -> Name -> Bool
409 mkImportFn (RnEnv env _)
412 lookup name = case lookupFM env (Unqual (nameOccName name)) of
413 Just (name', _) -> name == name'
417 %************************************************************************
419 \subsection{Envt utility functions}
421 %************************************************************************
423 =============== RnEnv ================
425 plusRnEnv (RnEnv n1 f1) (RnEnv n2 f2)
426 = plusGlobalNameEnvRn n1 n2 `thenRn` \ n ->
427 plusFixityEnvRn f1 f2 `thenRn` \ f ->
432 =============== NameEnv ================
434 plusGlobalNameEnvRn :: GlobalNameEnv -> GlobalNameEnv -> RnM s d GlobalNameEnv
435 plusGlobalNameEnvRn env1 env2
436 = mapRn (addErrRn.nameClashErr) (conflictsFM conflicting_name env1 env2) `thenRn_`
437 returnRn (env1 `plusFM` env2)
439 addOneToGlobalNameEnv :: GlobalNameEnv -> RdrName -> (Name, HowInScope) -> RnM s d GlobalNameEnv
440 addOneToGlobalNameEnv env rdr_name name
441 = case lookupFM env rdr_name of
442 Just name2 | conflicting_name name name2
443 -> addErrRn (nameClashErr (rdr_name, (name, name2))) `thenRn_`
446 other -> returnRn (addToFM env rdr_name name)
448 delOneFromGlobalNameEnv :: GlobalNameEnv -> RdrName -> GlobalNameEnv
449 delOneFromGlobalNameEnv env rdr_name = delFromFM env rdr_name
451 conflicting_name :: (Name, HowInScope) -> (Name, HowInScope) -> Bool
452 conflicting_name (n1, FromLocalDefn _) (n2, FromLocalDefn _) = True
453 conflicting_name (n1,h1) (n2,h2) = n1 /= n2
454 -- We complain of a conflict if one RdrName maps to two different Names,
455 -- OR if one RdrName maps to the same *locally-defined* Name. The latter
456 -- case is to catch two separate, local definitions of the same thing.
458 -- If a module imports itself then there might be a local defn and an imported
459 -- defn of the same name; in this case the names will compare as equal, but
460 -- will still have different HowInScope fields
462 lookupNameEnv :: NameEnv -> RdrName -> Maybe Name
463 lookupNameEnv = lookupFM
466 =============== FixityEnv ================
468 plusFixityEnvRn f1 f2
469 = mapRn (addErrRn.fixityClashErr) (conflictsFM bad_fix f1 f2) `thenRn_`
470 returnRn (f1 `plusFM` f2)
472 addOneToFixityEnv env rdr_name fixity = addToFM env rdr_name fixity
474 lookupFixityEnv env rdr_name
475 = case lookupFM env rdr_name of
476 Just (fixity,_) -> fixity
477 Nothing -> Fixity 9 InfixL -- Default case
479 bad_fix :: (Fixity, HowInScope) -> (Fixity, HowInScope) -> Bool
480 bad_fix (f1,_) (f2,_) = f1 /= f2
482 pprFixityProvenance :: (Fixity, HowInScope) -> SDoc
483 pprFixityProvenance (fixity, how_in_scope) = ppr how_in_scope
488 =============== ExportAvails ================
490 mkExportAvails :: Module -> Bool -> GlobalNameEnv -> [AvailInfo] -> ExportAvails
491 mkExportAvails mod_name unqual_imp name_env avails
492 = (mod_avail_env, entity_avail_env)
494 mod_avail_env = unitFM mod_name unqual_avails
496 -- unqual_avails is the Avails that are visible in *unqualfied* form
497 -- (1.4 Report, Section 5.1.1)
499 -- import T hiding( f )
500 -- we delete f from avails
502 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
503 | otherwise = [prune avail | avail <- avails]
505 prune (Avail n) | unqual_in_scope n = Avail n
506 prune (Avail n) | otherwise = NotAvailable
507 prune (AvailTC n ns) = AvailTC n (filter unqual_in_scope ns)
509 unqual_in_scope n = Unqual (nameOccName n) `elemFM` name_env
511 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
512 name <- availEntityNames avail]
514 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
515 plusExportAvails (m1, e1) (m2, e2)
516 = (plusFM_C (++) m1 m2, plusUFM_C plusAvail e1 e2)
520 =============== AvailInfo ================
522 plusAvail (Avail n1) (Avail n2) = Avail n1
523 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n1 (nub (ns1 ++ ns2))
524 plusAvail a NotAvailable = a
525 plusAvail NotAvailable a = a
528 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [pprAvail a1,pprAvail a2])
531 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
532 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
534 availsToNameSet :: [AvailInfo] -> NameSet
535 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
537 availName :: AvailInfo -> Name
538 availName (Avail n) = n
539 availName (AvailTC n _) = n
541 availNames :: AvailInfo -> [Name]
542 availNames NotAvailable = []
543 availNames (Avail n) = [n]
544 availNames (AvailTC n ns) = ns
546 -- availEntityNames is used to extract the names that can appear on their own in
547 -- an export or import list. For class decls, class methods can appear on their
548 -- own, thus import A( op )
549 -- but constructors cannot; thus
551 -- means import type T from B, not constructor T.
553 availEntityNames :: AvailInfo -> [Name]
554 availEntityNames NotAvailable = []
555 availEntityNames (Avail n) = [n]
556 availEntityNames (AvailTC n ns) = n : filter (isVarOcc . nameOccName) ns
558 filterAvail :: RdrNameIE -- Wanted
559 -> AvailInfo -- Available
560 -> AvailInfo -- Resulting available;
561 -- NotAvailable if wanted stuff isn't there
563 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
564 | sub_names_ok = AvailTC n (filter is_wanted ns)
565 | otherwise = pprTrace "filterAvail" (hsep [ppr ie, pprAvail avail]) $
568 is_wanted name = nameOccName name `elem` wanted_occs
569 sub_names_ok = all (`elem` avail_occs) wanted_occs
570 avail_occs = map nameOccName ns
571 wanted_occs = map rdrNameOcc (want:wants)
573 filterAvail (IEThingAbs _) (AvailTC n ns) = ASSERT( n `elem` ns )
576 filterAvail (IEThingAbs _) avail@(Avail n) = avail -- Type synonyms
578 filterAvail (IEVar _) avail@(Avail n) = avail
579 filterAvail (IEVar v) avail@(AvailTC n ns) = AvailTC n (filter wanted ns)
581 wanted n = nameOccName n == occ
583 -- The second equation happens if we import a class op, thus
585 -- where op is a class operation
587 filterAvail (IEThingAll _) avail@(AvailTC _ _) = avail
589 filterAvail ie avail = NotAvailable
592 -- In interfaces, pprAvail gets given the OccName of the "host" thing
593 pprAvail avail = getPprStyle $ \ sty ->
594 if ifaceStyle sty then
595 ppr_avail (pprOccName . nameOccName) avail
599 ppr_avail pp_name NotAvailable = ptext SLIT("NotAvailable")
600 ppr_avail pp_name (AvailTC n ns) = hsep [
602 parens $ hsep $ punctuate comma $
605 ppr_avail pp_name (Avail n) = pp_name n
611 %************************************************************************
613 \subsection{Finite map utilities}
615 %************************************************************************
618 Generally useful function on finite maps to check for overlap.
622 => (b->b->Bool) -- False <=> no conflict; you can pick either
623 -> FiniteMap a b -> FiniteMap a b
625 conflictsFM bad fm1 fm2
626 = filter (\(a,(b1,b2)) -> bad b1 b2)
627 (fmToList (intersectFM_C (\b1 b2 -> (b1,b2)) fm1 fm2))
631 -> FiniteMap a b -> a -> b
633 conflictFM bad fm key elt
634 = case lookupFM fm key of
635 Just elt' | bad elt elt' -> Just (key,(elt,elt'))
640 %************************************************************************
642 \subsection{Envt utility functions}
644 %************************************************************************
648 warnUnusedBinds, warnUnusedMatches, warnUnusedImports :: NameSet -> RnM s d ()
650 warnUnusedBinds names
651 | opt_WarnUnusedBinds = warnUnusedNames names
652 | otherwise = returnRn ()
654 warnUnusedMatches names
655 | opt_WarnUnusedMatches = warnUnusedNames names
656 | otherwise = returnRn ()
658 warnUnusedImports names
659 | opt_WarnUnusedImports = warnUnusedNames names
660 | otherwise = returnRn ()
662 warnUnusedNames :: NameSet -> RnM s d ()
663 warnUnusedNames names
664 = mapRn warn (nameSetToList names) `thenRn_`
667 warn name = pushSrcLocRn (getSrcLoc name) $
668 addWarnRn (unusedNameWarn name)
670 unusedNameWarn name = quotes (ppr name) <+> ptext SLIT("is bound but not used")
672 nameClashErr (rdr_name, ((_,how_in_scope1), (_, how_in_scope2)))
673 = hang (hsep [ptext SLIT("Conflicting definitions for"), quotes (ppr rdr_name)])
674 4 (vcat [ppr how_in_scope1,
677 fixityClashErr (rdr_name, ((_,how_in_scope1), (_, how_in_scope2)))
678 = hang (hsep [ptext SLIT("Conflicting fixities for"), quotes (ppr rdr_name)])
679 4 (vcat [ppr how_in_scope1,
682 shadowedNameWarn shadow
683 = hcat [ptext SLIT("This binding for"),
685 ptext SLIT("shadows an existing binding")]
688 = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
690 flavour = occNameFlavour (rdrNameOcc name)
692 qualNameErr descriptor (name,loc)
694 addErrRn (hsep [ ptext SLIT("Invalid use of qualified name"),
699 dupNamesErr descriptor ((name,loc) : dup_things)
701 addErrRn (hsep [ptext SLIT("Conflicting definitions for"),
703 ptext SLIT("in"), descriptor])