2 % (c) The University of Glasgow, 2000
4 \section[HscTypes]{Types for the per-module compiler}
8 -- * Sessions and compilation state
9 Session(..), HscEnv(..), hscEPS,
10 FinderCache, FindResult(..), ModLocationCache,
11 Target(..), TargetId(..), pprTarget, pprTargetId,
14 ModDetails(..), emptyModDetails,
15 ModGuts(..), CgGuts(..), ModImports(..), ForeignStubs(..),
17 ModSummary(..), showModMsg, isBootSummary,
18 msHsFilePath, msHiFilePath, msObjFilePath,
20 HscSource(..), isHsBoot, hscSourceString, -- Re-exported from DriverPhases
22 HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
23 hptInstances, hptRules,
25 ExternalPackageState(..), EpsStats(..), addEpsInStats,
26 PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
27 lookupIfaceByModule, emptyModIface,
29 InteractiveContext(..), emptyInteractiveContext,
30 icPrintUnqual, mkPrintUnqualified,
32 ModIface(..), mkIfaceDepCache, mkIfaceVerCache, mkIfaceFixCache,
33 emptyIfaceDepCache, mkIfaceFamInstsCache, mkDetailsFamInstCache,
35 Deprecs(..), IfaceDeprecs,
37 FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
41 TyThing(..), tyThingClass, tyThingTyCon, tyThingDataCon, tyThingId,
42 TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
43 extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
44 typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
47 WhetherHasOrphans, IsBootInterface, Usage(..),
48 Dependencies(..), noDependencies,
49 NameCache(..), OrigNameCache, OrigIParamCache,
50 Avails, availsToNameSet, availName, availNames,
51 GenAvailInfo(..), AvailInfo, RdrAvailInfo,
54 Deprecations, DeprecTxt, lookupDeprec, plusDeprecs,
56 PackageInstEnv, PackageRuleBase,
59 Linkable(..), isObjectLinkable,
60 Unlinked(..), CompiledByteCode,
61 isObject, nameOfObject, isInterpretable, byteCodeOfObject
64 #include "HsVersions.h"
67 import ByteCodeAsm ( CompiledByteCode )
70 import RdrName ( GlobalRdrEnv, emptyGlobalRdrEnv,
71 LocalRdrEnv, emptyLocalRdrEnv, GlobalRdrElt(..),
72 unQualOK, ImpDeclSpec(..), Provenance(..),
73 ImportSpec(..), lookupGlobalRdrEnv )
74 import Name ( Name, NamedThing, getName, nameOccName, nameModule )
77 import OccName ( OccName, OccEnv, lookupOccEnv, mkOccEnv, emptyOccEnv,
80 import InstEnv ( InstEnv, Instance )
81 import FamInstEnv ( FamInst, extractFamInsts )
82 import Rules ( RuleBase )
83 import CoreSyn ( CoreBind )
85 import Type ( TyThing(..) )
87 import Class ( Class, classSelIds, classATs, classTyCon )
88 import TyCon ( TyCon, tyConSelIds, tyConDataCons, isNewTyCon,
89 newTyConCo_maybe, tyConFamilyCoercion_maybe )
90 import DataCon ( DataCon, dataConImplicitIds )
91 import PrelNames ( gHC_PRIM )
92 import Packages ( PackageId )
93 import DynFlags ( DynFlags(..), isOneShot, HscTarget (..) )
94 import DriverPhases ( HscSource(..), isHsBoot, hscSourceString, Phase )
95 import BasicTypes ( Version, initialVersion, IPName,
96 Fixity, defaultFixity, DeprecTxt )
98 import IfaceSyn ( IfaceInst, IfaceFamInst, IfaceRule,
99 IfaceDecl(ifName), extractIfFamInsts )
101 import FiniteMap ( FiniteMap )
102 import CoreSyn ( CoreRule )
103 import Maybes ( orElse, expectJust )
105 import SrcLoc ( SrcSpan, Located )
106 import UniqFM ( lookupUFM, eltsUFM, emptyUFM )
107 import UniqSupply ( UniqSupply )
108 import FastString ( FastString )
110 import DATA_IOREF ( IORef, readIORef )
111 import StringBuffer ( StringBuffer )
112 import Maybe ( catMaybes )
113 import Time ( ClockTime )
117 %************************************************************************
119 \subsection{Compilation environment}
121 %************************************************************************
125 -- | The Session is a handle to the complete state of a compilation
126 -- session. A compilation session consists of a set of modules
127 -- constituting the current program or library, the context for
128 -- interactive evaluation, and various caches.
129 newtype Session = Session (IORef HscEnv)
132 HscEnv is like Session, except that some of the fields are immutable.
133 An HscEnv is used to compile a single module from plain Haskell source
134 code (after preprocessing) to either C, assembly or C--. Things like
135 the module graph don't change during a single compilation.
137 Historical note: "hsc" used to be the name of the compiler binary,
138 when there was a separate driver and compiler. To compile a single
139 module, the driver would invoke hsc on the source code... so nowadays
140 we think of hsc as the layer of the compiler that deals with compiling
146 hsc_dflags :: DynFlags,
147 -- The dynamic flag settings
149 hsc_targets :: [Target],
150 -- The targets (or roots) of the current session
152 hsc_mod_graph :: ModuleGraph,
153 -- The module graph of the current session
155 hsc_IC :: InteractiveContext,
156 -- The context for evaluating interactive statements
158 hsc_HPT :: HomePackageTable,
159 -- The home package table describes already-compiled
160 -- home-packge modules, *excluding* the module we
161 -- are compiling right now.
162 -- (In one-shot mode the current module is the only
163 -- home-package module, so hsc_HPT is empty. All other
164 -- modules count as "external-package" modules.
165 -- However, even in GHCi mode, hi-boot interfaces are
166 -- demand-loadeded into the external-package table.)
168 -- hsc_HPT is not mutable because we only demand-load
169 -- external packages; the home package is eagerly
170 -- loaded, module by module, by the compilation manager.
172 -- The HPT may contain modules compiled earlier by --make
173 -- but not actually below the current module in the dependency
174 -- graph. (This changes a previous invariant: changed Jan 05.)
176 hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
177 hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
178 -- These are side-effected by compiling to reflect
179 -- sucking in interface files. They cache the state of
180 -- external interface files, in effect.
182 hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
183 hsc_MLC :: {-# UNPACK #-} !(IORef ModLocationCache),
184 -- The finder's cache. This caches the location of modules,
185 -- so we don't have to search the filesystem multiple times.
187 hsc_global_rdr_env :: GlobalRdrEnv,
188 hsc_global_type_env :: TypeEnv
191 hscEPS :: HscEnv -> IO ExternalPackageState
192 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
194 -- | A compilation target.
196 -- A target may be supplied with the actual text of the
197 -- module. If so, use this instead of the file contents (this
198 -- is for use in an IDE where the file hasn't been saved by
200 data Target = Target TargetId (Maybe (StringBuffer,ClockTime))
203 = TargetModule ModuleName
204 -- ^ A module name: search for the file
205 | TargetFile FilePath (Maybe Phase)
206 -- ^ A filename: preprocess & parse it to find the module name.
207 -- If specified, the Phase indicates how to compile this file
208 -- (which phase to start from). Nothing indicates the starting phase
209 -- should be determined from the suffix of the filename.
212 pprTarget :: Target -> SDoc
213 pprTarget (Target id _) = pprTargetId id
215 pprTargetId (TargetModule m) = ppr m
216 pprTargetId (TargetFile f _) = text f
218 type HomePackageTable = ModuleNameEnv HomeModInfo
219 -- Domain = modules in the home package
220 -- "home" package name cached here for convenience
221 type PackageIfaceTable = ModuleEnv ModIface
222 -- Domain = modules in the imported packages
224 emptyHomePackageTable = emptyUFM
225 emptyPackageIfaceTable = emptyModuleEnv
228 = HomeModInfo { hm_iface :: !ModIface,
229 hm_details :: !ModDetails,
230 hm_linkable :: !(Maybe Linkable) }
231 -- hm_linkable might be Nothing if:
232 -- a) this is an .hs-boot module
233 -- b) temporarily during compilation if we pruned away
234 -- the old linkable because it was out of date.
235 -- after a complete compilation (GHC.load), all hm_linkable
236 -- fields in the HPT will be Just.
238 -- When re-linking a module (hscNoRecomp), we construct
239 -- the HomModInfo by building a new ModDetails from the
240 -- old ModIface (only).
242 -- | Find the 'ModIface' for a 'Module'
249 lookupIfaceByModule dflags hpt pit mod
250 -- in one-shot, we don't use the HPT
251 | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg
252 = fmap hm_iface (lookupUFM hpt (moduleName mod))
254 = lookupModuleEnv pit mod
255 where this_pkg = thisPackage dflags
260 hptInstances :: HscEnv -> (ModuleName -> Bool) -> [Instance]
261 -- Find all the instance declarations that are in modules imported
262 -- by this one, directly or indirectly, and are in the Home Package Table
263 -- This ensures that we don't see instances from modules --make compiled
264 -- before this one, but which are not below this one
265 hptInstances hsc_env want_this_module
267 | mod_info <- eltsUFM (hsc_HPT hsc_env)
268 , want_this_module (moduleName (mi_module (hm_iface mod_info)))
269 , ispec <- md_insts (hm_details mod_info) ]
271 hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
272 -- Get rules from modules "below" this one (in the dependency sense)
273 -- C.f Inst.hptInstances
274 hptRules hsc_env deps
275 | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
278 hpt = hsc_HPT hsc_env
281 | -- Find each non-hi-boot module below me
284 -- unsavoury: when compiling the base package with --make, we
285 -- sometimes try to look up RULES for GHC.Prim. GHC.Prim won't
286 -- be in the HPT, because we never compile it; it's in the EPT
287 -- instead. ToDo: clean up, and remove this slightly bogus
289 , mod /= moduleName gHC_PRIM
291 -- Look it up in the HPT
292 , let mod_info = case lookupUFM hpt mod of
293 Nothing -> pprPanic "hptRules" (ppr mod <+> ppr deps)
297 , rule <- md_rules (hm_details mod_info) ]
300 %************************************************************************
302 \subsection{The Finder cache}
304 %************************************************************************
307 -- | The 'FinderCache' maps home module names to the result of
308 -- searching for that module. It records the results of searching for
309 -- modules along the search path. On @:load@, we flush the entire
310 -- contents of this cache.
312 -- Although the @FinderCache@ range is 'FindResult' for convenience ,
313 -- in fact it will only ever contain 'Found' or 'NotFound' entries.
315 type FinderCache = ModuleNameEnv FindResult
317 -- | The result of searching for an imported module.
319 = Found ModLocation Module
320 -- the module was found
321 | NoPackage PackageId
322 -- the requested package was not found
323 | FoundMultiple [PackageId]
324 -- *error*: both in multiple packages
325 | PackageHidden PackageId
326 -- for an explicit source import: the package containing the module is
328 | ModuleHidden PackageId
329 -- for an explicit source import: the package containing the module is
330 -- exposed, but the module itself is hidden.
331 | NotFound [FilePath] (Maybe PackageId)
332 -- the module was not found, the specified places were searched
333 | NotFoundInPackage PackageId
334 -- the module was not found in this package
336 -- | Cache that remembers where we found a particular module. Contains both
337 -- home modules and package modules. On @:load@, only home modules are
338 -- purged from this cache.
339 type ModLocationCache = ModuleEnv ModLocation
342 %************************************************************************
344 \subsection{Symbol tables and Module details}
346 %************************************************************************
348 A @ModIface@ plus a @ModDetails@ summarises everything we know
349 about a compiled module. The @ModIface@ is the stuff *before* linking,
350 and can be written out to an interface file. (The @ModDetails@ is after
351 linking; it is the "linked" form of the mi_decls field.)
353 When we *read* an interface file, we also construct a @ModIface@ from it,
354 except that the mi_decls part is empty; when reading we consolidate
355 the declarations into a single indexed map in the @PersistentRenamerState@.
360 mi_module :: !Module,
361 mi_mod_vers :: !Version, -- Module version: changes when anything changes
363 mi_orphan :: !WhetherHasOrphans, -- Whether this module has orphans
364 mi_boot :: !IsBootInterface, -- Read from an hi-boot file?
366 mi_deps :: Dependencies,
367 -- This is consulted for directly-imported modules,
368 -- but not for anything else (hence lazy)
370 -- Usages; kept sorted so that it's easy to decide
371 -- whether to write a new iface file (changing usages
372 -- doesn't affect the version of this module)
373 mi_usages :: [Usage],
374 -- NOT STRICT! we read this field lazily from the interface file
375 -- It is *only* consulted by the recompilation checker
378 -- Kept sorted by (mod,occ), to make version comparisons easier
379 mi_exports :: ![IfaceExport],
380 mi_exp_vers :: !Version, -- Version number of export list
383 mi_fixities :: [(OccName,Fixity)],
384 -- NOT STRICT! we read this field lazily from the interface file
387 mi_deprecs :: IfaceDeprecs,
388 -- NOT STRICT! we read this field lazily from the interface file
390 -- Type, class and variable declarations
391 -- The version of an Id changes if its fixity or deprecations change
392 -- (as well as its type of course)
393 -- Ditto data constructors, class operations, except that
394 -- the version of the parent class/tycon changes
395 mi_decls :: [(Version,IfaceDecl)], -- Sorted
397 mi_globals :: !(Maybe GlobalRdrEnv),
398 -- Binds all the things defined at the top level in
399 -- the *original source* code for this module. which
400 -- is NOT the same as mi_exports, nor mi_decls (which
401 -- may contains declarations for things not actually
402 -- defined by the user). Used for GHCi and for inspecting
403 -- the contents of modules via the GHC API only.
405 -- (We need the source file to figure out the
406 -- top-level environment, if we didn't compile this module
407 -- from source then this field contains Nothing).
409 -- Strictly speaking this field should live in the
410 -- HomeModInfo, but that leads to more plumbing.
412 -- Instance declarations and rules
413 mi_insts :: [IfaceInst], -- Sorted
414 mi_fam_insts :: [(IfaceFamInst, IfaceDecl)], -- Cached value
415 -- ...from mi_decls (not in iface file)
416 mi_rules :: [IfaceRule], -- Sorted
417 mi_rule_vers :: !Version, -- Version number for rules and
418 -- instances combined
420 -- Cached environments for easy lookup
421 -- These are computed (lazily) from other fields
422 -- and are not put into the interface file
423 mi_dep_fn :: Name -> Maybe DeprecTxt, -- Cached lookup for mi_deprecs
424 mi_fix_fn :: OccName -> Fixity, -- Cached lookup for mi_fixities
425 mi_ver_fn :: OccName -> Maybe Version -- Cached lookup for mi_decls
426 -- The Nothing in mi_ver_fn means that the thing
427 -- isn't in decls. It's useful to know that when
428 -- seeing if we are up to date wrt the old interface
431 -- Pre-compute the set of type instances from the declaration list.
432 mkIfaceFamInstsCache :: [IfaceDecl] -> [(IfaceFamInst, IfaceDecl)]
433 mkIfaceFamInstsCache = extractIfFamInsts
435 -- Should be able to construct ModDetails from mi_decls in ModIface
438 -- The next three fields are created by the typechecker
439 md_exports :: NameSet,
440 md_types :: !TypeEnv,
441 md_fam_insts :: ![FamInst], -- Cached value extracted from md_types
442 md_insts :: ![Instance], -- Dfun-ids for the instances in this
445 md_rules :: ![CoreRule] -- Domain may include Ids from other
450 emptyModDetails = ModDetails { md_types = emptyTypeEnv,
451 md_exports = emptyNameSet,
456 -- Pre-compute the set of type instances from the type environment.
457 mkDetailsFamInstCache :: TypeEnv -> [FamInst]
458 mkDetailsFamInstCache = extractFamInsts . typeEnvElts
460 -- A ModGuts is carried through the compiler, accumulating stuff as it goes
461 -- There is only one ModGuts at any time, the one for the module
462 -- being compiled right now. Once it is compiled, a ModIface and
463 -- ModDetails are extracted and the ModGuts is dicarded.
467 mg_module :: !Module,
468 mg_boot :: IsBootInterface, -- Whether it's an hs-boot module
469 mg_exports :: !NameSet, -- What it exports
470 mg_deps :: !Dependencies, -- What is below it, directly or otherwise
471 mg_dir_imps :: ![Module], -- Directly-imported modules; used to
472 -- generate initialisation code
473 mg_usages :: ![Usage], -- Version info for what it needed
475 mg_rdr_env :: !GlobalRdrEnv, -- Top-level lexical environment
476 mg_fix_env :: !FixityEnv, -- Fixity env, for things declared in this module
477 mg_deprecs :: !Deprecations, -- Deprecations declared in the module
479 mg_types :: !TypeEnv,
480 mg_insts :: ![Instance], -- Instances
481 mg_rules :: ![CoreRule], -- Rules from this module
482 mg_binds :: ![CoreBind], -- Bindings for this module
483 mg_foreign :: !ForeignStubs
486 -- The ModGuts takes on several slightly different forms:
488 -- After simplification, the following fields change slightly:
489 -- mg_rules Orphan rules only (local ones now attached to binds)
490 -- mg_binds With rules attached
493 ---------------------------------------------------------
494 -- The Tidy pass forks the information about this module:
495 -- * one lot goes to interface file generation (ModIface)
496 -- and later compilations (ModDetails)
497 -- * the other lot goes to code generation (CgGuts)
500 cg_module :: !Module,
502 cg_tycons :: [TyCon],
503 -- Algebraic data types (including ones that started
504 -- life as classes); generate constructors and info
505 -- tables Includes newtypes, just for the benefit of
508 cg_binds :: [CoreBind],
509 -- The tidied main bindings, including
510 -- previously-implicit bindings for record and class
511 -- selectors, and data construtor wrappers. But *not*
512 -- data constructor workers; reason: we we regard them
513 -- as part of the code-gen of tycons
515 cg_dir_imps :: ![Module],
516 -- Directly-imported modules; used to generate
517 -- initialisation code
519 cg_foreign :: !ForeignStubs,
520 cg_dep_pkgs :: ![PackageId] -- Used to generate #includes for C code gen
523 -----------------------------------
526 imp_direct :: ![(Module,Bool)], -- Explicitly-imported modules
527 -- Boolean is true if we imported the whole
528 -- module (apart, perhaps, from hiding some)
529 imp_pkg_mods :: !ModuleSet, -- Non-home-package modules on which we depend,
530 -- directly or indirectly
531 imp_home_names :: !NameSet -- Home package things on which we depend,
532 -- directly or indirectly
535 -----------------------------------
536 data ForeignStubs = NoStubs
538 SDoc -- Header file prototypes for
539 -- "foreign exported" functions
540 SDoc -- C stubs to use when calling
541 -- "foreign exported" functions
542 [FastString] -- Headers that need to be included
543 -- into C code generated for this module
544 [Id] -- Foreign-exported binders
545 -- we have to generate code to register these
550 emptyModIface :: Module -> ModIface
552 = ModIface { mi_module = mod,
553 mi_mod_vers = initialVersion,
556 mi_deps = noDependencies,
559 mi_exp_vers = initialVersion,
561 mi_deprecs = NoDeprecs,
566 mi_globals = Nothing,
567 mi_rule_vers = initialVersion,
568 mi_dep_fn = emptyIfaceDepCache,
569 mi_fix_fn = emptyIfaceFixCache,
570 mi_ver_fn = emptyIfaceVerCache
575 %************************************************************************
577 \subsection{The interactive context}
579 %************************************************************************
582 data InteractiveContext
583 = InteractiveContext {
584 ic_toplev_scope :: [Module], -- Include the "top-level" scope of
587 ic_exports :: [Module], -- Include just the exports of these
590 ic_rn_gbl_env :: GlobalRdrEnv, -- The cached GlobalRdrEnv, built from
591 -- ic_toplev_scope and ic_exports
593 ic_rn_local_env :: LocalRdrEnv, -- Lexical context for variables bound
594 -- during interaction
596 ic_type_env :: TypeEnv -- Ditto for types
599 emptyInteractiveContext
600 = InteractiveContext { ic_toplev_scope = [],
602 ic_rn_gbl_env = emptyGlobalRdrEnv,
603 ic_rn_local_env = emptyLocalRdrEnv,
604 ic_type_env = emptyTypeEnv }
606 icPrintUnqual :: InteractiveContext -> PrintUnqualified
607 icPrintUnqual ictxt = mkPrintUnqualified (ic_rn_gbl_env ictxt)
610 %************************************************************************
612 Building a PrintUnqualified
614 %************************************************************************
617 mkPrintUnqualified :: GlobalRdrEnv -> PrintUnqualified
618 mkPrintUnqualified env = (qual_name, qual_mod)
621 | null gres = Just (moduleName mod)
622 -- it isn't in scope at all, this probably shouldn't happen,
623 -- but we'll qualify it by the original module anyway.
624 | any unQualOK gres = Nothing
625 | (Imported is : _) <- map gre_prov gres, (idecl : _) <- is
626 = Just (is_as (is_decl idecl))
627 | otherwise = panic "mkPrintUnqualified"
629 gres = [ gre | gre <- lookupGlobalRdrEnv env occ,
630 nameModule (gre_name gre) == mod ]
632 qual_mod mod = Nothing -- For now...
636 %************************************************************************
640 %************************************************************************
643 implicitTyThings :: TyThing -> [TyThing]
644 -- If you change this, make sure you change LoadIface.ifaceDeclSubBndrs in sync
646 implicitTyThings (AnId id) = []
648 -- For type constructors, add the data cons (and their extras),
649 -- and the selectors and generic-programming Ids too
651 -- Newtypes don't have a worker Id, so don't generate that?
652 implicitTyThings (ATyCon tc) = implicitCoTyCon tc ++
653 map AnId (tyConSelIds tc) ++
654 concatMap (extras_plus . ADataCon)
657 -- For classes, add the class TyCon too (and its extras)
658 -- and the class selector Ids and the associated types (they don't
659 -- have extras as these are only the family decls)
660 implicitTyThings (AClass cl) = map AnId (classSelIds cl) ++
661 map ATyCon (classATs cl) ++
662 extras_plus (ATyCon (classTyCon cl))
664 -- For data cons add the worker and wrapper (if any)
665 implicitTyThings (ADataCon dc) = map AnId (dataConImplicitIds dc)
667 -- For newtypes and indexed data types, add the implicit coercion tycon
669 = map ATyCon . catMaybes $ [newTyConCo_maybe tc,
670 tyConFamilyCoercion_maybe tc]
672 extras_plus thing = thing : implicitTyThings thing
674 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
675 extendTypeEnvWithIds env ids
676 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
679 %************************************************************************
683 %************************************************************************
686 type TypeEnv = NameEnv TyThing
688 emptyTypeEnv :: TypeEnv
689 typeEnvElts :: TypeEnv -> [TyThing]
690 typeEnvClasses :: TypeEnv -> [Class]
691 typeEnvTyCons :: TypeEnv -> [TyCon]
692 typeEnvIds :: TypeEnv -> [Id]
693 typeEnvDataCons :: TypeEnv -> [DataCon]
694 lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
696 emptyTypeEnv = emptyNameEnv
697 typeEnvElts env = nameEnvElts env
698 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
699 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
700 typeEnvIds env = [id | AnId id <- typeEnvElts env]
701 typeEnvDataCons env = [dc | ADataCon dc <- typeEnvElts env]
703 mkTypeEnv :: [TyThing] -> TypeEnv
704 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
706 lookupTypeEnv = lookupNameEnv
708 -- Extend the type environment
709 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
710 extendTypeEnv env thing = extendNameEnv env (getName thing) thing
712 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
713 extendTypeEnvList env things = foldl extendTypeEnv env things
717 lookupType :: DynFlags
723 lookupType dflags hpt pte name
724 -- in one-shot, we don't use the HPT
725 | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg
726 = do hm <- lookupUFM hpt (moduleName mod) -- Maybe monad
727 lookupNameEnv (md_types (hm_details hm)) name
729 = lookupNameEnv pte name
730 where mod = nameModule name
731 this_pkg = thisPackage dflags
735 tyThingTyCon (ATyCon tc) = tc
736 tyThingTyCon other = pprPanic "tyThingTyCon" (ppr other)
738 tyThingClass (AClass cls) = cls
739 tyThingClass other = pprPanic "tyThingClass" (ppr other)
741 tyThingDataCon (ADataCon dc) = dc
742 tyThingDataCon other = pprPanic "tyThingDataCon" (ppr other)
744 tyThingId (AnId id) = id
745 tyThingId other = pprPanic "tyThingId" (ppr other)
748 %************************************************************************
750 \subsection{Auxiliary types}
752 %************************************************************************
754 These types are defined here because they are mentioned in ModDetails,
755 but they are mostly elaborated elsewhere
758 mkIfaceVerCache :: [(Version,IfaceDecl)] -> OccName -> Maybe Version
759 mkIfaceVerCache pairs
760 = \occ -> lookupOccEnv env occ
762 env = foldl add emptyOccEnv pairs
763 add env (v,d) = extendOccEnv env (ifName d) v
765 emptyIfaceVerCache :: OccName -> Maybe Version
766 emptyIfaceVerCache occ = Nothing
768 ------------------ Deprecations -------------------------
771 | DeprecAll DeprecTxt -- Whole module deprecated
772 | DeprecSome a -- Some specific things deprecated
775 type IfaceDeprecs = Deprecs [(OccName,DeprecTxt)]
776 type Deprecations = Deprecs (NameEnv (OccName,DeprecTxt))
777 -- Keep the OccName so we can flatten the NameEnv to
778 -- get an IfaceDeprecs from a Deprecations
779 -- Only an OccName is needed, because a deprecation always
780 -- applies to things defined in the module in which the
781 -- deprecation appears.
783 mkIfaceDepCache:: IfaceDeprecs -> Name -> Maybe DeprecTxt
784 mkIfaceDepCache NoDeprecs = \n -> Nothing
785 mkIfaceDepCache (DeprecAll t) = \n -> Just t
786 mkIfaceDepCache (DeprecSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
788 emptyIfaceDepCache :: Name -> Maybe DeprecTxt
789 emptyIfaceDepCache n = Nothing
791 lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
792 lookupDeprec NoDeprecs name = Nothing
793 lookupDeprec (DeprecAll txt) name = Just txt
794 lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
795 Just (_, txt) -> Just txt
798 plusDeprecs :: Deprecations -> Deprecations -> Deprecations
799 plusDeprecs d NoDeprecs = d
800 plusDeprecs NoDeprecs d = d
801 plusDeprecs d (DeprecAll t) = DeprecAll t
802 plusDeprecs (DeprecAll t) d = DeprecAll t
803 plusDeprecs (DeprecSome v1) (DeprecSome v2) = DeprecSome (v1 `plusNameEnv` v2)
808 type Avails = [AvailInfo]
809 type AvailInfo = GenAvailInfo Name
810 type RdrAvailInfo = GenAvailInfo OccName
812 data GenAvailInfo name = Avail name -- An ordinary identifier
813 | AvailTC name -- The name of the type or class
814 [name] -- The available pieces of type/class.
815 -- NB: If the type or class is itself
816 -- to be in scope, it must be in this list.
817 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
819 -- Equality used when deciding if the interface has changed
821 type IfaceExport = (Module, [GenAvailInfo OccName])
823 availsToNameSet :: [AvailInfo] -> NameSet
824 availsToNameSet avails = foldl add emptyNameSet avails
826 add set avail = addListToNameSet set (availNames avail)
828 availName :: GenAvailInfo name -> name
829 availName (Avail n) = n
830 availName (AvailTC n _) = n
832 availNames :: GenAvailInfo name -> [name]
833 availNames (Avail n) = [n]
834 availNames (AvailTC n ns) = ns
836 instance Outputable n => Outputable (GenAvailInfo n) where
839 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
840 pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
842 ns' -> braces (hsep (punctuate comma (map ppr ns')))
844 pprAvail (Avail n) = ppr n
848 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
849 mkIfaceFixCache pairs
850 = \n -> lookupOccEnv env n `orElse` defaultFixity
854 emptyIfaceFixCache :: OccName -> Fixity
855 emptyIfaceFixCache n = defaultFixity
857 -- This fixity environment is for source code only
858 type FixityEnv = NameEnv FixItem
860 -- We keep the OccName in the range so that we can generate an interface from it
861 data FixItem = FixItem OccName Fixity SrcSpan
863 instance Outputable FixItem where
864 ppr (FixItem occ fix loc) = ppr fix <+> ppr occ <+> parens (ppr loc)
866 emptyFixityEnv :: FixityEnv
867 emptyFixityEnv = emptyNameEnv
869 lookupFixity :: FixityEnv -> Name -> Fixity
870 lookupFixity env n = case lookupNameEnv env n of
871 Just (FixItem _ fix _) -> fix
872 Nothing -> defaultFixity
876 %************************************************************************
878 \subsection{WhatsImported}
880 %************************************************************************
883 type WhetherHasOrphans = Bool
885 -- * an instance decl in a module other than the defn module for
886 -- one of the tycons or classes in the instance head
887 -- * a transformation rule in a module other than the one defining
888 -- the function in the head of the rule.
890 type IsBootInterface = Bool
892 -- Dependency info about modules and packages below this one
893 -- in the import hierarchy. See TcRnTypes.ImportAvails for details.
895 -- Invariant: the dependencies of a module M never includes M
896 -- Invariant: the lists are unordered, with no duplicates
898 = Deps { dep_mods :: [(ModuleName,IsBootInterface)], -- Home-package module dependencies
899 dep_pkgs :: [PackageId], -- External package dependencies
900 dep_orphs :: [Module] } -- Orphan modules (whether home or external pkg)
902 -- Equality used only for old/new comparison in MkIface.addVersionInfo
904 noDependencies :: Dependencies
905 noDependencies = Deps [] [] []
908 = Usage { usg_name :: ModuleName, -- Name of the module
909 usg_mod :: Version, -- Module version
910 usg_entities :: [(OccName,Version)], -- Sorted by occurrence name
911 usg_exports :: Maybe Version, -- Export-list version, if we depend on it
912 usg_rules :: Version -- Orphan-rules version (for non-orphan
913 -- modules this will always be initialVersion)
915 -- This type doesn't let you say "I imported f but none of the rules in
916 -- the module". If you use anything in the module you get its rule version
917 -- So if the rules change, you'll recompile, even if you don't use them.
918 -- This is easy to implement, and it's safer: you might not have used the rules last
919 -- time round, but if someone has added a new rule you might need it this time
921 -- The export list field is (Just v) if we depend on the export list:
922 -- i.e. we imported the module directly, whether or not we
923 -- enumerated the things we imported, or just imported everything
924 -- We need to recompile if M's exports change, because
925 -- if the import was import M, we might now have a name clash in the
927 -- if the import was import M(x) M might no longer export x
928 -- The only way we don't depend on the export list is if we have
930 -- And of course, for modules that aren't imported directly we don't
931 -- depend on their export lists
935 %************************************************************************
937 The External Package State
939 %************************************************************************
942 type PackageTypeEnv = TypeEnv
943 type PackageRuleBase = RuleBase
944 type PackageInstEnv = InstEnv
946 data ExternalPackageState
948 eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
949 -- In OneShot mode (only), home-package modules
950 -- accumulate in the external package state, and are
951 -- sucked in lazily. For these home-pkg modules
952 -- (only) we need to record which are boot modules.
953 -- We set this field after loading all the
954 -- explicitly-imported interfaces, but before doing
957 -- The ModuleName part is not necessary, but it's useful for
958 -- debug prints, and it's convenient because this field comes
959 -- direct from TcRnTypes.ImportAvails.imp_dep_mods
961 eps_PIT :: !PackageIfaceTable,
962 -- The ModuleIFaces for modules in external packages
963 -- whose interfaces we have opened
964 -- The declarations in these interface files are held in
965 -- eps_decls, eps_inst_env, eps_rules (below), not in the
966 -- mi_decls fields of the iPIT.
967 -- What _is_ in the iPIT is:
974 eps_PTE :: !PackageTypeEnv, -- Domain = external-package modules
976 eps_inst_env :: !PackageInstEnv, -- The total InstEnv accumulated from
977 -- all the external-package modules
978 eps_rule_base :: !PackageRuleBase, -- Ditto RuleEnv
980 eps_stats :: !EpsStats
983 -- "In" means read from iface files
984 -- "Out" means actually sucked in and type-checked
985 data EpsStats = EpsStats { n_ifaces_in
986 , n_decls_in, n_decls_out
987 , n_rules_in, n_rules_out
988 , n_insts_in, n_insts_out :: !Int }
990 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
991 -- Add stats for one newly-read interface
992 addEpsInStats stats n_decls n_insts n_rules
993 = stats { n_ifaces_in = n_ifaces_in stats + 1
994 , n_decls_in = n_decls_in stats + n_decls
995 , n_insts_in = n_insts_in stats + n_insts
996 , n_rules_in = n_rules_in stats + n_rules }
999 The NameCache makes sure that there is just one Unique assigned for
1000 each original name; i.e. (module-name, occ-name) pair. The Name is
1001 always stored as a Global, and has the SrcLoc of its binding location.
1002 Actually that's not quite right. When we first encounter the original
1003 name, we might not be at its binding site (e.g. we are reading an
1004 interface file); so we give it 'noSrcLoc' then. Later, when we find
1005 its binding site, we fix it up.
1009 = NameCache { nsUniqs :: UniqSupply,
1010 -- Supply of uniques
1011 nsNames :: OrigNameCache,
1012 -- Ensures that one original name gets one unique
1013 nsIPs :: OrigIParamCache
1014 -- Ensures that one implicit parameter name gets one unique
1017 type OrigNameCache = ModuleEnv (OccEnv Name)
1018 type OrigIParamCache = FiniteMap (IPName OccName) (IPName Name)
1023 %************************************************************************
1025 The module graph and ModSummary type
1026 A ModSummary is a node in the compilation manager's
1027 dependency graph, and it's also passed to hscMain
1029 %************************************************************************
1031 A ModuleGraph contains all the nodes from the home package (only).
1032 There will be a node for each source module, plus a node for each hi-boot
1036 type ModuleGraph = [ModSummary] -- The module graph,
1037 -- NOT NECESSARILY IN TOPOLOGICAL ORDER
1039 emptyMG :: ModuleGraph
1042 -- The nodes of the module graph are
1043 -- EITHER a regular Haskell source module
1044 -- OR a hi-boot source module
1048 ms_mod :: Module, -- Identity of the module
1049 ms_hsc_src :: HscSource, -- Source is Haskell, hs-boot, external core
1050 ms_location :: ModLocation, -- Location
1051 ms_hs_date :: ClockTime, -- Timestamp of source file
1052 ms_obj_date :: Maybe ClockTime, -- Timestamp of object, maybe
1053 ms_srcimps :: [Located ModuleName], -- Source imports
1054 ms_imps :: [Located ModuleName], -- Non-source imports
1055 ms_hspp_file :: FilePath, -- Filename of preprocessed source.
1056 ms_hspp_opts :: DynFlags, -- Cached flags from OPTIONS, INCLUDE
1057 -- and LANGUAGE pragmas.
1058 ms_hspp_buf :: Maybe StringBuffer -- The actual preprocessed source, maybe.
1061 -- The ModLocation contains both the original source filename and the
1062 -- filename of the cleaned-up source file after all preprocessing has been
1063 -- done. The point is that the summariser will have to cpp/unlit/whatever
1064 -- all files anyway, and there's no point in doing this twice -- just
1065 -- park the result in a temp file, put the name of it in the location,
1066 -- and let @compile@ read from that file on the way back up.
1068 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
1069 -- the ms_hs_date and imports can, of course, change
1071 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
1072 msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
1073 msHiFilePath ms = ml_hi_file (ms_location ms)
1074 msObjFilePath ms = ml_obj_file (ms_location ms)
1076 isBootSummary :: ModSummary -> Bool
1077 isBootSummary ms = isHsBoot (ms_hsc_src ms)
1079 instance Outputable ModSummary where
1081 = sep [text "ModSummary {",
1082 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1083 text "ms_mod =" <+> ppr (ms_mod ms)
1084 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
1085 text "ms_imps =" <+> ppr (ms_imps ms),
1086 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1090 showModMsg :: HscTarget -> Bool -> ModSummary -> String
1091 showModMsg target recomp mod_summary
1092 = showSDoc (hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
1093 char '(', text (msHsFilePath mod_summary) <> comma,
1095 HscInterpreted | recomp
1096 -> text "interpreted"
1097 HscNothing -> text "nothing"
1098 _other -> text (msObjFilePath mod_summary),
1101 mod = moduleName (ms_mod mod_summary)
1102 mod_str = showSDoc (ppr mod) ++ hscSourceString (ms_hsc_src mod_summary)
1106 %************************************************************************
1108 \subsection{Linkable stuff}
1110 %************************************************************************
1112 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
1113 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
1116 data Linkable = LM {
1117 linkableTime :: ClockTime, -- Time at which this linkable was built
1118 -- (i.e. when the bytecodes were produced,
1119 -- or the mod date on the files)
1120 linkableModule :: Module, -- Should be Module, but see below
1121 linkableUnlinked :: [Unlinked]
1124 isObjectLinkable :: Linkable -> Bool
1125 isObjectLinkable l = not (null unlinked) && all isObject unlinked
1126 where unlinked = linkableUnlinked l
1127 -- A linkable with no Unlinked's is treated as a BCO. We can
1128 -- generate a linkable with no Unlinked's as a result of
1129 -- compiling a module in HscNothing mode, and this choice
1130 -- happens to work well with checkStability in module GHC.
1132 instance Outputable Linkable where
1133 ppr (LM when_made mod unlinkeds)
1134 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
1135 $$ nest 3 (ppr unlinkeds)
1137 -------------------------------------------
1142 | BCOs CompiledByteCode
1145 data CompiledByteCode = NoByteCode
1148 instance Outputable Unlinked where
1149 ppr (DotO path) = text "DotO" <+> text path
1150 ppr (DotA path) = text "DotA" <+> text path
1151 ppr (DotDLL path) = text "DotDLL" <+> text path
1153 ppr (BCOs bcos) = text "BCOs" <+> ppr bcos
1155 ppr (BCOs bcos) = text "No byte code"
1158 isObject (DotO _) = True
1159 isObject (DotA _) = True
1160 isObject (DotDLL _) = True
1163 isInterpretable = not . isObject
1165 nameOfObject (DotO fn) = fn
1166 nameOfObject (DotA fn) = fn
1167 nameOfObject (DotDLL fn) = fn
1168 nameOfObject other = pprPanic "nameOfObject" (ppr other)
1170 byteCodeOfObject (BCOs bc) = bc
1171 byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)