2 % (c) The University of Glasgow, 2000
4 \section[HscTypes]{Types for the per-module compiler}
12 ModDetails(..), ModIface(..),
13 HomeSymbolTable, emptySymbolTable,
15 HomeIfaceTable, PackageIfaceTable, emptyIfaceTable,
16 lookupIface, lookupIfaceByModName,
19 InteractiveContext(..),
21 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
23 VersionInfo(..), initialVersionInfo, lookupVersion,
25 TyThing(..), isTyClThing, implicitTyThingIds,
27 TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
28 extendTypeEnvList, extendTypeEnvWithIds,
29 typeEnvClasses, typeEnvTyCons, typeEnvIds,
31 ImportedModuleInfo, WhetherHasOrphans, ImportVersion, WhatsImported(..),
32 PersistentRenamerState(..), IsBootInterface, DeclsMap,
33 IfaceInsts, IfaceRules, GatedDecl, GatedDecls, IsExported,
34 NameSupply(..), OrigNameCache, OrigIParamCache,
35 Avails, AvailEnv, GenAvailInfo(..), AvailInfo, RdrAvailInfo,
36 PersistentCompilerState(..),
38 Deprecations(..), lookupDeprec,
40 InstEnv, ClsInstEnv, DFunId,
41 PackageInstEnv, PackageRuleBase,
43 GlobalRdrEnv, GlobalRdrElt(..), pprGlobalRdrEnv,
44 LocalRdrEnv, extendLocalRdrEnv,
48 Provenance(..), ImportReason(..),
49 pprNameProvenance, hasBetterProv
53 #include "HsVersions.h"
55 import RdrName ( RdrNameEnv, addListToRdrEnv, emptyRdrEnv, mkRdrUnqual, rdrEnvToList )
56 import Name ( Name, NamedThing, getName, nameOccName, nameModule, nameSrcLoc )
58 import OccName ( OccName )
59 import Module ( Module, ModuleName, ModuleEnv,
60 lookupModuleEnv, lookupModuleEnvByName, emptyModuleEnv
62 import InstEnv ( InstEnv, ClsInstEnv, DFunId )
63 import Rules ( RuleBase )
64 import CoreSyn ( CoreBind )
66 import Class ( Class, classSelIds )
67 import TyCon ( TyCon, tyConGenIds, tyConSelIds, tyConDataConsIfAvailable )
68 import DataCon ( dataConId, dataConWrapId )
70 import BasicTypes ( Version, initialVersion, Fixity )
72 import HsSyn ( DeprecTxt, tyClDeclName, ifaceRuleDeclName )
73 import RdrHsSyn ( RdrNameInstDecl, RdrNameRuleDecl, RdrNameTyClDecl )
74 import RnHsSyn ( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
76 import CoreSyn ( IdCoreRule )
78 import FiniteMap ( FiniteMap )
80 import Maybes ( seqMaybe, orElse )
82 import SrcLoc ( SrcLoc, isGoodSrcLoc )
83 import Util ( thenCmp, sortLt )
84 import UniqSupply ( UniqSupply )
87 %************************************************************************
89 \subsection{Which mode we're in
91 %************************************************************************
94 data GhciMode = Batch | Interactive | OneShot
99 %************************************************************************
101 \subsection{Module locations}
103 %************************************************************************
108 ml_hs_file :: Maybe FilePath,
109 ml_hspp_file :: Maybe FilePath, -- path of preprocessed source
110 ml_hi_file :: FilePath,
111 ml_obj_file :: Maybe FilePath
115 instance Outputable ModuleLocation where
119 For a module in another package, the hs_file and obj_file
120 components of ModuleLocation are undefined.
122 The locations specified by a ModuleLocation may or may not
123 correspond to actual files yet: for example, even if the object
124 file doesn't exist, the ModuleLocation still contains the path to
125 where the object file will reside if/when it is created.
128 %************************************************************************
130 \subsection{Symbol tables and Module details}
132 %************************************************************************
134 A @ModIface@ plus a @ModDetails@ summarises everything we know
135 about a compiled module. The @ModIface@ is the stuff *before* linking,
136 and can be written out to an interface file. The @ModDetails@ is after
137 linking; it is the "linked" form of the mi_decls field.
142 mi_module :: Module, -- Complete with package info
143 mi_version :: VersionInfo, -- Module version number
144 mi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
145 mi_boot :: IsBootInterface, -- Whether this interface was read from an hi-boot file
147 mi_usages :: [ImportVersion Name], -- Usages; kept sorted so that it's easy
148 -- to decide whether to write a new iface file
149 -- (changing usages doesn't affect the version of
152 mi_exports :: [(ModuleName,Avails)], -- What it exports
153 -- Kept sorted by (mod,occ),
154 -- to make version comparisons easier
156 mi_globals :: GlobalRdrEnv, -- Its top level environment
158 mi_fixities :: NameEnv Fixity, -- Fixities
159 mi_deprecs :: Deprecations, -- Deprecations
161 mi_decls :: IfaceDecls -- The RnDecls form of ModDetails
164 data IfaceDecls = IfaceDecls { dcl_tycl :: [RenamedTyClDecl], -- Sorted
165 dcl_rules :: [RenamedRuleDecl], -- Sorted
166 dcl_insts :: [RenamedInstDecl] } -- Unsorted
168 mkIfaceDecls :: [RenamedTyClDecl] -> [RenamedRuleDecl] -> [RenamedInstDecl] -> IfaceDecls
169 mkIfaceDecls tycls rules insts
170 = IfaceDecls { dcl_tycl = sortLt lt_tycl tycls,
171 dcl_rules = sortLt lt_rule rules,
174 d1 `lt_tycl` d2 = tyClDeclName d1 < tyClDeclName d2
175 r1 `lt_rule` r2 = ifaceRuleDeclName r1 < ifaceRuleDeclName r2
178 -- typechecker should only look at this, not ModIface
179 -- Should be able to construct ModDetails from mi_decls in ModIface
182 -- The next three fields are created by the typechecker
184 md_insts :: [DFunId], -- Dfun-ids for the instances in this module
185 md_rules :: [IdCoreRule], -- Domain may include Ids from other modules
186 md_binds :: [CoreBind]
189 -- The ModDetails takes on several slightly different forms:
191 -- After typecheck + desugar
192 -- md_types Contains TyCons, Classes, and hasNoBinding Ids
193 -- md_insts All instances from this module (incl derived ones)
194 -- md_rules All rules from this module
195 -- md_binds Desugared bindings
197 -- After simplification
198 -- md_types Same as after typecheck
200 -- md_rules Orphan rules only (local ones now attached to binds)
201 -- md_binds With rules attached
204 -- md_types Now contains Ids as well, replete with final IdInfo
205 -- The Ids are only the ones that are visible from
206 -- importing modules. Without -O that means only
207 -- exported Ids, but with -O importing modules may
208 -- see ids mentioned in unfoldings of exported Ids
210 -- md_insts Same DFunIds as before, but with final IdInfo,
211 -- and the unique might have changed; remember that
212 -- CoreTidy links up the uniques of old and new versions
214 -- md_rules All rules for exported things, substituted with final Ids
218 -- Passed back to compilation manager
219 -- Just as after CoreTidy, but with md_binds nuked
224 emptyModIface :: Module -> ModIface
226 = ModIface { mi_module = mod,
227 mi_version = initialVersionInfo,
232 mi_fixities = emptyNameEnv,
233 mi_globals = emptyRdrEnv,
234 mi_deprecs = NoDeprecs,
235 mi_decls = panic "emptyModIface: decls"
239 Symbol tables map modules to ModDetails:
242 type SymbolTable = ModuleEnv ModDetails
243 type IfaceTable = ModuleEnv ModIface
245 type HomeIfaceTable = IfaceTable
246 type PackageIfaceTable = IfaceTable
248 type HomeSymbolTable = SymbolTable -- Domain = modules in the home package
250 emptySymbolTable :: SymbolTable
251 emptySymbolTable = emptyModuleEnv
253 emptyIfaceTable :: IfaceTable
254 emptyIfaceTable = emptyModuleEnv
257 Simple lookups in the symbol table.
260 lookupIface :: HomeIfaceTable -> PackageIfaceTable -> Name -> Maybe ModIface
261 -- We often have two IfaceTables, and want to do a lookup
262 lookupIface hit pit name
263 = lookupModuleEnv hit mod `seqMaybe` lookupModuleEnv pit mod
265 mod = nameModule name
267 lookupIfaceByModName :: HomeIfaceTable -> PackageIfaceTable -> ModuleName -> Maybe ModIface
268 -- We often have two IfaceTables, and want to do a lookup
269 lookupIfaceByModName hit pit mod
270 = lookupModuleEnvByName hit mod `seqMaybe` lookupModuleEnvByName pit mod
274 %************************************************************************
276 \subsection{The interactive context}
278 %************************************************************************
281 data InteractiveContext
282 = InteractiveContext {
283 ic_module :: Module, -- The current module in which
284 -- the user is sitting
286 ic_rn_env :: LocalRdrEnv, -- Lexical context for variables bound
287 -- during interaction
289 ic_type_env :: TypeEnv -- Ditto for types
294 %************************************************************************
296 \subsection{Type environment stuff}
298 %************************************************************************
301 data TyThing = AnId Id
305 isTyClThing :: TyThing -> Bool
306 isTyClThing (ATyCon _) = True
307 isTyClThing (AClass _) = True
308 isTyClThing (AnId _) = False
310 instance NamedThing TyThing where
311 getName (AnId id) = getName id
312 getName (ATyCon tc) = getName tc
313 getName (AClass cl) = getName cl
315 instance Outputable TyThing where
316 ppr (AnId id) = ptext SLIT("AnId") <+> ppr id
317 ppr (ATyCon tc) = ptext SLIT("ATyCon") <+> ppr tc
318 ppr (AClass cl) = ptext SLIT("AClass") <+> ppr cl
320 typeEnvClasses env = [cl | AClass cl <- nameEnvElts env]
321 typeEnvTyCons env = [tc | ATyCon tc <- nameEnvElts env]
322 typeEnvIds env = [id | AnId id <- nameEnvElts env]
324 implicitTyThingIds :: [TyThing] -> [Id]
325 -- Add the implicit data cons and selectors etc
326 implicitTyThingIds things
327 = concat (map go things)
330 go (AClass cl) = classSelIds cl
331 go (ATyCon tc) = tyConGenIds tc ++
333 [ n | dc <- tyConDataConsIfAvailable tc,
334 n <- [dataConId dc, dataConWrapId dc] ]
335 -- Synonyms return empty list of constructors and selectors
340 type TypeEnv = NameEnv TyThing
342 emptyTypeEnv = emptyNameEnv
344 mkTypeEnv :: [TyThing] -> TypeEnv
345 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
347 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
348 extendTypeEnvList env things
349 = extendNameEnvList env [(getName thing, thing) | thing <- things]
351 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
352 extendTypeEnvWithIds env ids
353 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
357 lookupType :: HomeSymbolTable -> PackageTypeEnv -> Name -> Maybe TyThing
358 lookupType hst pte name
359 = case lookupModuleEnv hst (nameModule name) of
360 Just details -> lookupNameEnv (md_types details) name
361 Nothing -> lookupNameEnv pte name
364 %************************************************************************
366 \subsection{Auxiliary types}
368 %************************************************************************
370 These types are defined here because they are mentioned in ModDetails,
371 but they are mostly elaborated elsewhere
376 vers_module :: Version, -- Changes when anything changes
377 vers_exports :: Version, -- Changes when export list changes
378 vers_rules :: Version, -- Changes when any rule changes
379 vers_decls :: NameEnv Version
380 -- Versions for "big" names only (not data constructors, class ops)
381 -- The version of an Id changes if its fixity changes
382 -- Ditto data constructors, class operations, except that the version of
383 -- the parent class/tycon changes
385 -- If a name isn't in the map, it means 'initialVersion'
388 initialVersionInfo :: VersionInfo
389 initialVersionInfo = VersionInfo { vers_module = initialVersion,
390 vers_exports = initialVersion,
391 vers_rules = initialVersion,
392 vers_decls = emptyNameEnv
395 lookupVersion :: NameEnv Version -> Name -> Version
396 lookupVersion env name = lookupNameEnv env name `orElse` initialVersion
398 data Deprecations = NoDeprecs
399 | DeprecAll DeprecTxt -- Whole module deprecated
400 | DeprecSome (NameEnv (Name,DeprecTxt)) -- Some things deprecated
402 -- We keep the Name in the range, so we can print them out
404 lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
405 lookupDeprec NoDeprecs name = Nothing
406 lookupDeprec (DeprecAll txt) name = Just txt
407 lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
408 Just (_, txt) -> Just txt
411 instance Eq Deprecations where
412 -- Used when checking whether we need write a new interface
413 NoDeprecs == NoDeprecs = True
414 (DeprecAll t1) == (DeprecAll t2) = t1 == t2
415 (DeprecSome e1) == (DeprecSome e2) = nameEnvElts e1 == nameEnvElts e2
421 type Avails = [AvailInfo]
422 type AvailInfo = GenAvailInfo Name
423 type RdrAvailInfo = GenAvailInfo OccName
425 data GenAvailInfo name = Avail name -- An ordinary identifier
426 | AvailTC name -- The name of the type or class
427 [name] -- The available pieces of type/class.
428 -- NB: If the type or class is itself
429 -- to be in scope, it must be in this list.
430 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
432 -- Equality used when deciding if the interface has changed
434 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
436 instance Outputable n => Outputable (GenAvailInfo n) where
439 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
440 pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
442 ns' -> braces (hsep (punctuate comma (map ppr ns')))
444 pprAvail (Avail n) = ppr n
448 %************************************************************************
450 \subsection{ModIface}
452 %************************************************************************
455 type WhetherHasOrphans = Bool
457 -- * an instance decl in a module other than the defn module for
458 -- one of the tycons or classes in the instance head
459 -- * a transformation rule in a module other than the one defining
460 -- the function in the head of the rule.
462 type IsBootInterface = Bool
464 type ImportVersion name = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
466 data WhatsImported name = NothingAtAll -- The module is below us in the
467 -- hierarchy, but we import nothing
469 | Everything Version -- Used for modules from other packages;
470 -- we record only the module's version number
473 Version -- Module version
474 (Maybe Version) -- Export-list version, if we depend on it
475 [(name,Version)] -- List guaranteed non-empty
476 Version -- Rules version
479 -- 'Specifically' doesn't let you say "I imported f but none of the rules in
480 -- the module". If you use anything in the module you get its rule version
481 -- So if the rules change, you'll recompile, even if you don't use them.
482 -- This is easy to implement, and it's safer: you might not have used the rules last
483 -- time round, but if someone has added a new rule you might need it this time
485 -- The export list field is (Just v) if we depend on the export list:
486 -- we imported the module without saying exactly what we imported
487 -- We need to recompile if the module exports changes, because we might
488 -- now have a name clash in the importing module.
490 type IsExported = Name -> Bool -- True for names that are exported from this module
494 %************************************************************************
496 \subsection{The persistent compiler state}
498 %************************************************************************
501 data PersistentCompilerState
503 pcs_PIT :: PackageIfaceTable, -- Domain = non-home-package modules
504 -- the mi_decls component is empty
506 pcs_PTE :: PackageTypeEnv, -- Domain = non-home-package modules
507 -- except that the InstEnv components is empty
509 pcs_insts :: PackageInstEnv, -- The total InstEnv accumulated from all
510 -- the non-home-package modules
512 pcs_rules :: PackageRuleBase, -- Ditto RuleEnv
514 pcs_PRS :: PersistentRenamerState
518 The @PersistentRenamerState@ persists across successive calls to the
522 * A name supply, which deals with allocating unique names to
523 (Module,OccName) original names,
525 * An accumulated TypeEnv from all the modules in imported packages
527 * An accumulated InstEnv from all the modules in imported packages
528 The point is that we don't want to keep recreating it whenever
529 we compile a new module. The InstEnv component of pcPST is empty.
530 (This means we might "see" instances that we shouldn't "really" see;
531 but the Haskell Report is vague on what is meant to be visible,
532 so we just take the easy road here.)
536 * A "holding pen" for declarations that have been read out of
537 interface files but not yet sucked in, renamed, and typechecked
540 type PackageTypeEnv = TypeEnv
541 type PackageRuleBase = RuleBase
542 type PackageInstEnv = InstEnv
544 data PersistentRenamerState
545 = PRS { prsOrig :: NameSupply,
546 prsImpMods :: ImportedModuleInfo,
547 prsDecls :: DeclsMap,
548 prsInsts :: IfaceInsts,
549 prsRules :: IfaceRules
553 The NameSupply makes sure that there is just one Unique assigned for
554 each original name; i.e. (module-name, occ-name) pair. The Name is
555 always stored as a Global, and has the SrcLoc of its binding location.
556 Actually that's not quite right. When we first encounter the original
557 name, we might not be at its binding site (e.g. we are reading an
558 interface file); so we give it 'noSrcLoc' then. Later, when we find
559 its binding site, we fix it up.
561 Exactly the same is true of the Module stored in the Name. When we first
562 encounter the occurrence, we may not know the details of the module, so
563 we just store junk. Then when we find the binding site, we fix it up.
567 = NameSupply { nsUniqs :: UniqSupply,
569 nsNames :: OrigNameCache,
570 -- Ensures that one original name gets one unique
571 nsIPs :: OrigIParamCache
572 -- Ensures that one implicit parameter name gets one unique
575 type OrigNameCache = FiniteMap (ModuleName,OccName) Name
576 type OrigIParamCache = FiniteMap OccName Name
579 @ImportedModuleInfo@ contains info ONLY about modules that have not yet
580 been loaded into the iPIT. These modules are mentioned in interfaces we've
581 already read, so we know a tiny bit about them, but we havn't yet looked
582 at the interface file for the module itself. It needs to persist across
583 invocations of the renamer, at least from Rename.checkOldIface to Rename.renameSource.
584 And there's no harm in it persisting across multiple compilations.
587 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
590 A DeclsMap contains a binding for each Name in the declaration
591 including the constructors of a type decl etc. The Bool is True just
595 type DeclsMap = (NameEnv (AvailInfo, Bool, (Module, RdrNameTyClDecl)), Int)
596 -- The Int says how many have been sucked in
598 type IfaceInsts = GatedDecls RdrNameInstDecl
599 type IfaceRules = GatedDecls RdrNameRuleDecl
601 type GatedDecls d = (Bag (GatedDecl d), Int) -- The Int says how many have been sucked in
602 type GatedDecl d = ([Name], (Module, d))
606 %************************************************************************
608 \subsection{Provenance and export info}
610 %************************************************************************
612 A LocalRdrEnv is used for local bindings (let, where, lambda, case)
615 type LocalRdrEnv = RdrNameEnv Name
617 extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
618 extendLocalRdrEnv env names
619 = addListToRdrEnv env [(mkRdrUnqual (nameOccName n), n) | n <- names]
622 The GlobalRdrEnv gives maps RdrNames to Names. There is a separate
623 one for each module, corresponding to that module's top-level scope.
626 type GlobalRdrEnv = RdrNameEnv [GlobalRdrElt]
627 -- The list is because there may be name clashes
628 -- These only get reported on lookup, not on construction
630 data GlobalRdrElt = GRE Name Provenance (Maybe DeprecTxt)
631 -- The Maybe DeprecTxt tells whether this name is deprecated
634 = vcat (map pp (rdrEnvToList env))
636 pp (rn, nps) = ppr rn <> colon <+>
637 vcat [ppr n <+> pprNameProvenance n p | (GRE n p _) <- nps]
640 The "provenance" of something says how it came to be in scope.
644 = LocalDef -- Defined locally
646 | NonLocalDef -- Defined non-locally
649 -- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
650 instance Eq Provenance where
651 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
653 instance Eq ImportReason where
654 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
656 instance Ord Provenance where
657 compare LocalDef LocalDef = EQ
658 compare LocalDef (NonLocalDef _) = LT
659 compare (NonLocalDef _) LocalDef = GT
661 compare (NonLocalDef reason1) (NonLocalDef reason2)
662 = compare reason1 reason2
664 instance Ord ImportReason where
665 compare ImplicitImport ImplicitImport = EQ
666 compare ImplicitImport (UserImport _ _ _) = LT
667 compare (UserImport _ _ _) ImplicitImport = GT
668 compare (UserImport m1 loc1 _) (UserImport m2 loc2 _)
669 = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)
673 = UserImport Module SrcLoc Bool -- Imported from module M on line L
674 -- Note the M may well not be the defining module
676 -- The Bool is true iff the thing was named *explicitly* in the import spec,
677 -- rather than being imported as part of a group; e.g.
680 -- Here, everything imported by B, and the constructors of T
681 -- are not named explicitly; only T is named explicitly.
682 -- This info is used when warning of unused names.
684 | ImplicitImport -- Imported implicitly for some other reason
688 hasBetterProv :: Provenance -> Provenance -> Bool
690 -- a local thing over an imported thing
691 -- a user-imported thing over a non-user-imported thing
692 -- an explicitly-imported thing over an implicitly imported thing
693 hasBetterProv LocalDef _ = True
694 hasBetterProv (NonLocalDef (UserImport _ _ _ )) (NonLocalDef ImplicitImport) = True
695 hasBetterProv _ _ = False
697 pprNameProvenance :: Name -> Provenance -> SDoc
698 pprNameProvenance name LocalDef = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
699 pprNameProvenance name (NonLocalDef why) = sep [ppr_reason why,
700 nest 2 (ppr_defn (nameSrcLoc name))]
702 ppr_reason ImplicitImport = ptext SLIT("implicitly imported")
703 ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
705 ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("at") <+> ppr loc)