2 % (c) The University of Glasgow, 2000
4 \section[HscTypes]{Types for the per-module compiler}
10 ModDetails(..), ModIface(..),
11 HomeSymbolTable, emptySymbolTable,
13 HomeIfaceTable, PackageIfaceTable, emptyIfaceTable,
14 lookupIface, lookupIfaceByModName,
17 InteractiveContext(..),
19 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
21 VersionInfo(..), initialVersionInfo, lookupVersion,
23 TyThing(..), isTyClThing, implicitTyThingIds,
25 TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
26 extendTypeEnvList, extendTypeEnvWithIds,
27 typeEnvClasses, typeEnvTyCons, typeEnvIds,
29 ImportedModuleInfo, WhetherHasOrphans, ImportVersion, WhatsImported(..),
30 PersistentRenamerState(..), IsBootInterface, DeclsMap,
31 IfaceInsts, IfaceRules, GatedDecl, GatedDecls, IsExported,
32 NameSupply(..), OrigNameCache, OrigIParamCache,
33 Avails, AvailEnv, GenAvailInfo(..), AvailInfo, RdrAvailInfo,
34 PersistentCompilerState(..),
36 Deprecations(..), lookupDeprec,
38 InstEnv, ClsInstEnv, DFunId,
39 PackageInstEnv, PackageRuleBase,
41 GlobalRdrEnv, GlobalRdrElt(..), pprGlobalRdrEnv,
42 LocalRdrEnv, extendLocalRdrEnv,
46 Provenance(..), ImportReason(..),
47 pprNameProvenance, hasBetterProv
51 #include "HsVersions.h"
53 import RdrName ( RdrNameEnv, addListToRdrEnv, emptyRdrEnv, mkRdrUnqual, rdrEnvToList )
54 import Name ( Name, NamedThing, getName, nameOccName, nameModule, nameSrcLoc )
56 import OccName ( OccName )
57 import Module ( Module, ModuleName, ModuleEnv,
58 lookupModuleEnv, lookupModuleEnvByName, emptyModuleEnv
60 import InstEnv ( InstEnv, ClsInstEnv, DFunId )
61 import Rules ( RuleBase )
62 import CoreSyn ( CoreBind )
64 import Class ( Class, classSelIds )
65 import TyCon ( TyCon, tyConGenIds, tyConSelIds, tyConDataConsIfAvailable )
66 import DataCon ( dataConId, dataConWrapId )
68 import BasicTypes ( Version, initialVersion, Fixity )
70 import HsSyn ( DeprecTxt, tyClDeclName, ifaceRuleDeclName )
71 import RdrHsSyn ( RdrNameInstDecl, RdrNameRuleDecl, RdrNameTyClDecl )
72 import RnHsSyn ( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
74 import CoreSyn ( IdCoreRule )
76 import FiniteMap ( FiniteMap )
78 import Maybes ( seqMaybe, orElse )
80 import SrcLoc ( SrcLoc, isGoodSrcLoc )
81 import Util ( thenCmp, sortLt )
82 import UniqSupply ( UniqSupply )
85 %************************************************************************
87 \subsection{Module locations}
89 %************************************************************************
94 ml_hs_file :: Maybe FilePath,
95 ml_hspp_file :: Maybe FilePath, -- path of preprocessed source
96 ml_hi_file :: Maybe FilePath,
97 ml_obj_file :: Maybe FilePath
101 instance Outputable ModuleLocation where
105 For a module in another package, the hs_file and obj_file
106 components of ModuleLocation are undefined.
108 The locations specified by a ModuleLocation may or may not
109 correspond to actual files yet: for example, even if the object
110 file doesn't exist, the ModuleLocation still contains the path to
111 where the object file will reside if/when it is created.
114 %************************************************************************
116 \subsection{Symbol tables and Module details}
118 %************************************************************************
120 A @ModIface@ plus a @ModDetails@ summarises everything we know
121 about a compiled module. The @ModIface@ is the stuff *before* linking,
122 and can be written out to an interface file. The @ModDetails@ is after
123 linking; it is the "linked" form of the mi_decls field.
128 mi_module :: Module, -- Complete with package info
129 mi_version :: VersionInfo, -- Module version number
130 mi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
131 mi_boot :: IsBootInterface, -- Whether this interface was read from an hi-boot file
133 mi_usages :: [ImportVersion Name], -- Usages; kept sorted so that it's easy
134 -- to decide whether to write a new iface file
135 -- (changing usages doesn't affect the version of
138 mi_exports :: [(ModuleName,Avails)], -- What it exports
139 -- Kept sorted by (mod,occ),
140 -- to make version comparisons easier
142 mi_globals :: GlobalRdrEnv, -- Its top level environment
144 mi_fixities :: NameEnv Fixity, -- Fixities
145 mi_deprecs :: Deprecations, -- Deprecations
147 mi_decls :: IfaceDecls -- The RnDecls form of ModDetails
150 data IfaceDecls = IfaceDecls { dcl_tycl :: [RenamedTyClDecl], -- Sorted
151 dcl_rules :: [RenamedRuleDecl], -- Sorted
152 dcl_insts :: [RenamedInstDecl] } -- Unsorted
154 mkIfaceDecls :: [RenamedTyClDecl] -> [RenamedRuleDecl] -> [RenamedInstDecl] -> IfaceDecls
155 mkIfaceDecls tycls rules insts
156 = IfaceDecls { dcl_tycl = sortLt lt_tycl tycls,
157 dcl_rules = sortLt lt_rule rules,
160 d1 `lt_tycl` d2 = tyClDeclName d1 < tyClDeclName d2
161 r1 `lt_rule` r2 = ifaceRuleDeclName r1 < ifaceRuleDeclName r2
164 -- typechecker should only look at this, not ModIface
165 -- Should be able to construct ModDetails from mi_decls in ModIface
168 -- The next three fields are created by the typechecker
170 md_insts :: [DFunId], -- Dfun-ids for the instances in this module
171 md_rules :: [IdCoreRule], -- Domain may include Ids from other modules
172 md_binds :: [CoreBind]
175 -- The ModDetails takes on several slightly different forms:
177 -- After typecheck + desugar
178 -- md_types Contains TyCons, Classes, and hasNoBinding Ids
179 -- md_insts All instances from this module (incl derived ones)
180 -- md_rules All rules from this module
181 -- md_binds Desugared bindings
183 -- After simplification
184 -- md_types Same as after typecheck
186 -- md_rules Orphan rules only (local ones now attached to binds)
187 -- md_binds With rules attached
190 -- md_types Now contains Ids as well, replete with final IdInfo
191 -- The Ids are only the ones that are visible from
192 -- importing modules. Without -O that means only
193 -- exported Ids, but with -O importing modules may
194 -- see ids mentioned in unfoldings of exported Ids
196 -- md_insts Same DFunIds as before, but with final IdInfo,
197 -- and the unique might have changed; remember that
198 -- CoreTidy links up the uniques of old and new versions
200 -- md_rules All rules for exported things, substituted with final Ids
204 -- Passed back to compilation manager
205 -- Just as after CoreTidy, but with md_binds nuked
210 emptyModIface :: Module -> ModIface
212 = ModIface { mi_module = mod,
213 mi_version = initialVersionInfo,
218 mi_fixities = emptyNameEnv,
219 mi_globals = emptyRdrEnv,
220 mi_deprecs = NoDeprecs,
221 mi_decls = panic "emptyModIface: decls"
225 Symbol tables map modules to ModDetails:
228 type SymbolTable = ModuleEnv ModDetails
229 type IfaceTable = ModuleEnv ModIface
231 type HomeIfaceTable = IfaceTable
232 type PackageIfaceTable = IfaceTable
234 type HomeSymbolTable = SymbolTable -- Domain = modules in the home package
236 emptySymbolTable :: SymbolTable
237 emptySymbolTable = emptyModuleEnv
239 emptyIfaceTable :: IfaceTable
240 emptyIfaceTable = emptyModuleEnv
243 Simple lookups in the symbol table.
246 lookupIface :: HomeIfaceTable -> PackageIfaceTable -> Name -> Maybe ModIface
247 -- We often have two IfaceTables, and want to do a lookup
248 lookupIface hit pit name
249 = lookupModuleEnv hit mod `seqMaybe` lookupModuleEnv pit mod
251 mod = nameModule name
253 lookupIfaceByModName :: HomeIfaceTable -> PackageIfaceTable -> ModuleName -> Maybe ModIface
254 -- We often have two IfaceTables, and want to do a lookup
255 lookupIfaceByModName hit pit mod
256 = lookupModuleEnvByName hit mod `seqMaybe` lookupModuleEnvByName pit mod
260 %************************************************************************
262 \subsection{The interactive context}
264 %************************************************************************
267 data InteractiveContext
268 = InteractiveContext {
269 ic_module :: Module, -- The current module in which
270 -- the user is sitting
272 ic_rn_env :: LocalRdrEnv, -- Lexical context for variables bound
273 -- during interaction
275 ic_type_env :: TypeEnv -- Ditto for types
280 %************************************************************************
282 \subsection{Type environment stuff}
284 %************************************************************************
287 data TyThing = AnId Id
291 isTyClThing :: TyThing -> Bool
292 isTyClThing (ATyCon _) = True
293 isTyClThing (AClass _) = True
294 isTyClThing (AnId _) = False
296 instance NamedThing TyThing where
297 getName (AnId id) = getName id
298 getName (ATyCon tc) = getName tc
299 getName (AClass cl) = getName cl
301 instance Outputable TyThing where
302 ppr (AnId id) = ptext SLIT("AnId") <+> ppr id
303 ppr (ATyCon tc) = ptext SLIT("ATyCon") <+> ppr tc
304 ppr (AClass cl) = ptext SLIT("AClass") <+> ppr cl
306 typeEnvClasses env = [cl | AClass cl <- nameEnvElts env]
307 typeEnvTyCons env = [tc | ATyCon tc <- nameEnvElts env]
308 typeEnvIds env = [id | AnId id <- nameEnvElts env]
310 implicitTyThingIds :: [TyThing] -> [Id]
311 -- Add the implicit data cons and selectors etc
312 implicitTyThingIds things
313 = concat (map go things)
316 go (AClass cl) = classSelIds cl
317 go (ATyCon tc) = tyConGenIds tc ++
319 [ n | dc <- tyConDataConsIfAvailable tc,
320 n <- [dataConId dc, dataConWrapId dc] ]
321 -- Synonyms return empty list of constructors and selectors
326 type TypeEnv = NameEnv TyThing
328 emptyTypeEnv = emptyNameEnv
330 mkTypeEnv :: [TyThing] -> TypeEnv
331 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
333 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
334 extendTypeEnvList env things
335 = extendNameEnvList env [(getName thing, thing) | thing <- things]
337 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
338 extendTypeEnvWithIds env ids
339 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
343 lookupType :: HomeSymbolTable -> PackageTypeEnv -> Name -> Maybe TyThing
344 lookupType hst pte name
345 = case lookupModuleEnv hst (nameModule name) of
346 Just details -> lookupNameEnv (md_types details) name
347 Nothing -> lookupNameEnv pte name
350 %************************************************************************
352 \subsection{Auxiliary types}
354 %************************************************************************
356 These types are defined here because they are mentioned in ModDetails,
357 but they are mostly elaborated elsewhere
362 vers_module :: Version, -- Changes when anything changes
363 vers_exports :: Version, -- Changes when export list changes
364 vers_rules :: Version, -- Changes when any rule changes
365 vers_decls :: NameEnv Version
366 -- Versions for "big" names only (not data constructors, class ops)
367 -- The version of an Id changes if its fixity changes
368 -- Ditto data constructors, class operations, except that the version of
369 -- the parent class/tycon changes
371 -- If a name isn't in the map, it means 'initialVersion'
374 initialVersionInfo :: VersionInfo
375 initialVersionInfo = VersionInfo { vers_module = initialVersion,
376 vers_exports = initialVersion,
377 vers_rules = initialVersion,
378 vers_decls = emptyNameEnv
381 lookupVersion :: NameEnv Version -> Name -> Version
382 lookupVersion env name = lookupNameEnv env name `orElse` initialVersion
384 data Deprecations = NoDeprecs
385 | DeprecAll DeprecTxt -- Whole module deprecated
386 | DeprecSome (NameEnv (Name,DeprecTxt)) -- Some things deprecated
388 -- We keep the Name in the range, so we can print them out
390 lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
391 lookupDeprec NoDeprecs name = Nothing
392 lookupDeprec (DeprecAll txt) name = Just txt
393 lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
394 Just (_, txt) -> Just txt
397 instance Eq Deprecations where
398 -- Used when checking whether we need write a new interface
399 NoDeprecs == NoDeprecs = True
400 (DeprecAll t1) == (DeprecAll t2) = t1 == t2
401 (DeprecSome e1) == (DeprecSome e2) = nameEnvElts e1 == nameEnvElts e2
407 type Avails = [AvailInfo]
408 type AvailInfo = GenAvailInfo Name
409 type RdrAvailInfo = GenAvailInfo OccName
411 data GenAvailInfo name = Avail name -- An ordinary identifier
412 | AvailTC name -- The name of the type or class
413 [name] -- The available pieces of type/class.
414 -- NB: If the type or class is itself
415 -- to be in scope, it must be in this list.
416 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
418 -- Equality used when deciding if the interface has changed
420 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
422 instance Outputable n => Outputable (GenAvailInfo n) where
425 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
426 pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
428 ns' -> braces (hsep (punctuate comma (map ppr ns')))
430 pprAvail (Avail n) = ppr n
434 %************************************************************************
436 \subsection{ModIface}
438 %************************************************************************
441 type WhetherHasOrphans = Bool
443 -- * an instance decl in a module other than the defn module for
444 -- one of the tycons or classes in the instance head
445 -- * a transformation rule in a module other than the one defining
446 -- the function in the head of the rule.
448 type IsBootInterface = Bool
450 type ImportVersion name = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
452 data WhatsImported name = NothingAtAll -- The module is below us in the
453 -- hierarchy, but we import nothing
455 | Everything Version -- Used for modules from other packages;
456 -- we record only the module's version number
459 Version -- Module version
460 (Maybe Version) -- Export-list version, if we depend on it
461 [(name,Version)] -- List guaranteed non-empty
462 Version -- Rules version
465 -- 'Specifically' doesn't let you say "I imported f but none of the rules in
466 -- the module". If you use anything in the module you get its rule version
467 -- So if the rules change, you'll recompile, even if you don't use them.
468 -- This is easy to implement, and it's safer: you might not have used the rules last
469 -- time round, but if someone has added a new rule you might need it this time
471 -- The export list field is (Just v) if we depend on the export list:
472 -- we imported the module without saying exactly what we imported
473 -- We need to recompile if the module exports changes, because we might
474 -- now have a name clash in the importing module.
476 type IsExported = Name -> Bool -- True for names that are exported from this module
480 %************************************************************************
482 \subsection{The persistent compiler state}
484 %************************************************************************
487 data PersistentCompilerState
489 pcs_PIT :: PackageIfaceTable, -- Domain = non-home-package modules
490 -- the mi_decls component is empty
492 pcs_PTE :: PackageTypeEnv, -- Domain = non-home-package modules
493 -- except that the InstEnv components is empty
495 pcs_insts :: PackageInstEnv, -- The total InstEnv accumulated from all
496 -- the non-home-package modules
498 pcs_rules :: PackageRuleBase, -- Ditto RuleEnv
500 pcs_PRS :: PersistentRenamerState
504 The @PersistentRenamerState@ persists across successive calls to the
508 * A name supply, which deals with allocating unique names to
509 (Module,OccName) original names,
511 * An accumulated TypeEnv from all the modules in imported packages
513 * An accumulated InstEnv from all the modules in imported packages
514 The point is that we don't want to keep recreating it whenever
515 we compile a new module. The InstEnv component of pcPST is empty.
516 (This means we might "see" instances that we shouldn't "really" see;
517 but the Haskell Report is vague on what is meant to be visible,
518 so we just take the easy road here.)
522 * A "holding pen" for declarations that have been read out of
523 interface files but not yet sucked in, renamed, and typechecked
526 type PackageTypeEnv = TypeEnv
527 type PackageRuleBase = RuleBase
528 type PackageInstEnv = InstEnv
530 data PersistentRenamerState
531 = PRS { prsOrig :: NameSupply,
532 prsImpMods :: ImportedModuleInfo,
533 prsDecls :: DeclsMap,
534 prsInsts :: IfaceInsts,
535 prsRules :: IfaceRules
539 The NameSupply makes sure that there is just one Unique assigned for
540 each original name; i.e. (module-name, occ-name) pair. The Name is
541 always stored as a Global, and has the SrcLoc of its binding location.
542 Actually that's not quite right. When we first encounter the original
543 name, we might not be at its binding site (e.g. we are reading an
544 interface file); so we give it 'noSrcLoc' then. Later, when we find
545 its binding site, we fix it up.
547 Exactly the same is true of the Module stored in the Name. When we first
548 encounter the occurrence, we may not know the details of the module, so
549 we just store junk. Then when we find the binding site, we fix it up.
553 = NameSupply { nsUniqs :: UniqSupply,
555 nsNames :: OrigNameCache,
556 -- Ensures that one original name gets one unique
557 nsIPs :: OrigIParamCache
558 -- Ensures that one implicit parameter name gets one unique
561 type OrigNameCache = FiniteMap (ModuleName,OccName) Name
562 type OrigIParamCache = FiniteMap OccName Name
565 @ImportedModuleInfo@ contains info ONLY about modules that have not yet
566 been loaded into the iPIT. These modules are mentioned in interfaces we've
567 already read, so we know a tiny bit about them, but we havn't yet looked
568 at the interface file for the module itself. It needs to persist across
569 invocations of the renamer, at least from Rename.checkOldIface to Rename.renameSource.
570 And there's no harm in it persisting across multiple compilations.
573 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
576 A DeclsMap contains a binding for each Name in the declaration
577 including the constructors of a type decl etc. The Bool is True just
581 type DeclsMap = (NameEnv (AvailInfo, Bool, (Module, RdrNameTyClDecl)), Int)
582 -- The Int says how many have been sucked in
584 type IfaceInsts = GatedDecls RdrNameInstDecl
585 type IfaceRules = GatedDecls RdrNameRuleDecl
587 type GatedDecls d = (Bag (GatedDecl d), Int) -- The Int says how many have been sucked in
588 type GatedDecl d = ([Name], (Module, d))
592 %************************************************************************
594 \subsection{Provenance and export info}
596 %************************************************************************
598 A LocalRdrEnv is used for local bindings (let, where, lambda, case)
601 type LocalRdrEnv = RdrNameEnv Name
603 extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
604 extendLocalRdrEnv env names
605 = addListToRdrEnv env [(mkRdrUnqual (nameOccName n), n) | n <- names]
608 The GlobalRdrEnv gives maps RdrNames to Names. There is a separate
609 one for each module, corresponding to that module's top-level scope.
612 type GlobalRdrEnv = RdrNameEnv [GlobalRdrElt]
613 -- The list is because there may be name clashes
614 -- These only get reported on lookup, not on construction
616 data GlobalRdrElt = GRE Name Provenance (Maybe DeprecTxt)
617 -- The Maybe DeprecTxt tells whether this name is deprecated
620 = vcat (map pp (rdrEnvToList env))
622 pp (rn, nps) = ppr rn <> colon <+>
623 vcat [ppr n <+> pprNameProvenance n p | (GRE n p _) <- nps]
626 The "provenance" of something says how it came to be in scope.
630 = LocalDef -- Defined locally
632 | NonLocalDef -- Defined non-locally
635 -- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
636 instance Eq Provenance where
637 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
639 instance Eq ImportReason where
640 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
642 instance Ord Provenance where
643 compare LocalDef LocalDef = EQ
644 compare LocalDef (NonLocalDef _) = LT
645 compare (NonLocalDef _) LocalDef = GT
647 compare (NonLocalDef reason1) (NonLocalDef reason2)
648 = compare reason1 reason2
650 instance Ord ImportReason where
651 compare ImplicitImport ImplicitImport = EQ
652 compare ImplicitImport (UserImport _ _ _) = LT
653 compare (UserImport _ _ _) ImplicitImport = GT
654 compare (UserImport m1 loc1 _) (UserImport m2 loc2 _)
655 = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)
659 = UserImport Module SrcLoc Bool -- Imported from module M on line L
660 -- Note the M may well not be the defining module
662 -- The Bool is true iff the thing was named *explicitly* in the import spec,
663 -- rather than being imported as part of a group; e.g.
666 -- Here, everything imported by B, and the constructors of T
667 -- are not named explicitly; only T is named explicitly.
668 -- This info is used when warning of unused names.
670 | ImplicitImport -- Imported implicitly for some other reason
674 hasBetterProv :: Provenance -> Provenance -> Bool
676 -- a local thing over an imported thing
677 -- a user-imported thing over a non-user-imported thing
678 -- an explicitly-imported thing over an implicitly imported thing
679 hasBetterProv LocalDef _ = True
680 hasBetterProv (NonLocalDef (UserImport _ _ _ )) (NonLocalDef ImplicitImport) = True
681 hasBetterProv _ _ = False
683 pprNameProvenance :: Name -> Provenance -> SDoc
684 pprNameProvenance name LocalDef = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
685 pprNameProvenance name (NonLocalDef why) = sep [ppr_reason why,
686 nest 2 (ppr_defn (nameSrcLoc name))]
688 ppr_reason ImplicitImport = ptext SLIT("implicitly imported")
689 ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
691 ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("at") <+> ppr loc)