2 % (c) The University of Glasgow, 2000
4 \section[HscTypes]{Types for the per-module compiler}
11 ModDetails(..), ModIface(..),
12 ModGuts(..), ModImports(..), ForeignStubs(..),
13 ParsedIface(..), IfaceDeprecs,
15 HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
17 ExternalPackageState(..),
18 PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
19 lookupIface, lookupIfaceByModName, moduleNameToModule,
22 InteractiveContext(..), emptyInteractiveContext, icPrintUnqual,
24 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
26 VersionInfo(..), initialVersionInfo, lookupVersion,
27 FixityEnv, lookupFixity, collectFixities, emptyFixityEnv,
29 TyThing(..), isTyClThing, implicitTyThingIds,
31 TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
32 extendTypeEnvList, extendTypeEnvWithIds,
33 typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
35 WhetherHasOrphans, IsBootInterface, DeclsMap, Usage(..),
36 Dependencies(..), noDependencies,
37 IfaceInsts, IfaceRules, GatedDecl, GatedDecls, GateFn,
38 NameCache(..), OrigNameCache, OrigIParamCache,
39 Avails, availsToNameSet, availName, availNames,
40 GenAvailInfo(..), AvailInfo, RdrAvailInfo,
41 ExportItem, RdrExportItem,
43 PersistentCompilerState(..),
45 Deprecations(..), lookupDeprec, plusDeprecs,
47 InstEnv, ClsInstEnv, DFunId,
48 PackageInstEnv, PackageRuleBase,
50 GlobalRdrEnv, GlobalRdrElt(..), emptyGlobalRdrEnv, pprGlobalRdrEnv,
51 LocalRdrEnv, extendLocalRdrEnv, isLocalGRE, unQualInScope,
54 Linkable(..), isObjectLinkable,
55 Unlinked(..), CompiledByteCode,
56 isObject, nameOfObject, isInterpretable, byteCodeOfObject,
59 Provenance(..), ImportReason(..),
60 pprNameProvenance, hasBetterProv
64 #include "HsVersions.h"
67 import ByteCodeAsm ( CompiledByteCode )
70 import RdrName ( RdrName, mkRdrUnqual,
71 RdrNameEnv, addListToRdrEnv, foldRdrEnv, isUnqual,
72 rdrEnvToList, emptyRdrEnv )
73 import Name ( Name, NamedThing, getName, nameOccName, nameModule, nameSrcLoc )
76 import OccName ( OccName )
78 import InstEnv ( InstEnv, ClsInstEnv, DFunId )
79 import Rules ( RuleBase )
80 import CoreSyn ( CoreBind )
82 import Class ( Class, classSelIds )
83 import TyCon ( TyCon, isNewTyCon, tyConGenIds, tyConSelIds, tyConDataCons_maybe )
84 import Type ( TyThing(..), isTyClThing )
85 import DataCon ( dataConWorkId, dataConWrapId )
86 import Packages ( PackageName, basePackage )
87 import CmdLineOpts ( DynFlags )
89 import BasicTypes ( Version, initialVersion, IPName,
90 Fixity, FixitySig(..), defaultFixity )
92 import HsSyn ( DeprecTxt, TyClDecl, InstDecl, RuleDecl,
93 tyClDeclName, ifaceRuleDeclName, tyClDeclNames,
95 import RnHsSyn ( RenamedTyClDecl, RenamedRuleDecl, RenamedInstDecl )
97 import CoreSyn ( IdCoreRule )
98 import PrelNames ( isBuiltInSyntaxName )
102 import Maybes ( orElse )
104 import SrcLoc ( SrcLoc, isGoodSrcLoc )
105 import Util ( thenCmp, sortLt )
106 import UniqSupply ( UniqSupply )
107 import Maybe ( fromJust )
108 import FastString ( FastString )
110 import Time ( ClockTime )
114 %************************************************************************
116 \subsection{Compilation environment}
118 %************************************************************************
120 The HscEnv gives the environment in which to compile a chunk of code.
123 data HscEnv = HscEnv { hsc_mode :: GhciMode,
124 hsc_dflags :: DynFlags,
125 hsc_HPT :: HomePackageTable }
128 The GhciMode is self-explanatory:
131 data GhciMode = Batch | Interactive | OneShot
136 type HomePackageTable = ModuleEnv HomeModInfo -- Domain = modules in the home package
137 type PackageIfaceTable = ModuleEnv ModIface -- Domain = modules in the imported packages
139 emptyHomePackageTable = emptyModuleEnv
140 emptyPackageIfaceTable = emptyModuleEnv
142 data HomeModInfo = HomeModInfo { hm_iface :: ModIface,
143 hm_details :: ModDetails,
144 hm_linkable :: Linkable }
147 Simple lookups in the symbol table.
150 lookupIface :: HomePackageTable -> PackageIfaceTable -> Module -> Maybe ModIface
151 -- We often have two IfaceTables, and want to do a lookup
152 lookupIface hpt pit mod
153 = case lookupModuleEnv hpt mod of
154 Just mod_info -> Just (hm_iface mod_info)
155 Nothing -> lookupModuleEnv pit mod
157 lookupIfaceByModName :: HomePackageTable -> PackageIfaceTable -> ModuleName -> Maybe ModIface
158 -- We often have two IfaceTables, and want to do a lookup
159 lookupIfaceByModName hpt pit mod
160 = case lookupModuleEnvByName hpt mod of
161 Just mod_info -> Just (hm_iface mod_info)
162 Nothing -> lookupModuleEnvByName pit mod
166 -- Use instead of Finder.findModule if possible: this way doesn't
167 -- require filesystem operations, and it is guaranteed not to fail
168 -- when the IfaceTables are properly populated (i.e. after the renamer).
169 moduleNameToModule :: HomePackageTable -> PackageIfaceTable -> ModuleName -> Module
170 moduleNameToModule hpt pit mod
171 = mi_module (fromJust (lookupIfaceByModName hpt pit mod))
175 %************************************************************************
177 \subsection{Symbol tables and Module details}
179 %************************************************************************
181 A @ModIface@ plus a @ModDetails@ summarises everything we know
182 about a compiled module. The @ModIface@ is the stuff *before* linking,
183 and can be written out to an interface file. (The @ModDetails@ is after
184 linking; it is the "linked" form of the mi_decls field.)
186 When we *read* an interface file, we also construct a @ModIface@ from it,
187 except that the mi_decls part is empty; when reading we consolidate
188 the declarations into a single indexed map in the @PersistentRenamerState@.
193 mi_module :: !Module,
194 mi_package :: !PackageName, -- Which package the module comes from
195 mi_version :: !VersionInfo, -- Version info for everything in this module
196 mi_orphan :: !WhetherHasOrphans, -- Whether this module has orphans
197 mi_boot :: !IsBootInterface, -- Read from an hi-boot file?
199 mi_deps :: Dependencies,
200 -- This is consulted for directly-imported modules, but
201 -- not for anything else
203 mi_usages :: [Usage Name],
204 -- Usages; kept sorted so that it's easy to decide
205 -- whether to write a new iface file (changing usages
206 -- doesn't affect the version of this module)
207 -- NOT STRICT! we read this field lazily from the interface file
208 -- It is *only* consulted by the recompilation checker
210 mi_exports :: ![ExportItem],
211 -- What it exports Kept sorted by (mod,occ), to make
212 -- version comparisons easier
214 mi_globals :: !(Maybe GlobalRdrEnv),
215 -- Its top level environment or Nothing if we read this
216 -- interface from an interface file. (We need the source
217 -- file to figure out the top-level environment.)
219 mi_fixities :: !FixityEnv, -- Fixities
220 mi_deprecs :: Deprecations, -- Deprecations
221 -- NOT STRICT! we read this field lazilly from the interface file
223 mi_decls :: IfaceDecls -- The RnDecls form of ModDetails
224 -- NOT STRICT! we fill this field with _|_ sometimes
227 -- Should be able to construct ModDetails from mi_decls in ModIface
230 -- The next three fields are created by the typechecker
231 md_types :: !TypeEnv,
232 md_insts :: ![DFunId], -- Dfun-ids for the instances in this module
233 md_rules :: ![IdCoreRule] -- Domain may include Ids from other modules
236 -- A ModGuts is carried through the compiler, accumulating stuff as it goes
237 -- There is only one ModGuts at any time, the one for the module
238 -- being compiled right now. Once it is compiled, a ModIface and
239 -- ModDetails are extracted and the ModGuts is dicarded.
243 mg_module :: !Module,
244 mg_exports :: !Avails, -- What it exports
245 mg_deps :: !Dependencies, -- What is below it, directly or otherwise
246 mg_dir_imps :: ![Module], -- Directly-imported modules; used to
247 -- generate initialisation code
248 mg_usages :: ![Usage Name], -- Version info for what it needed
250 mg_rdr_env :: !GlobalRdrEnv, -- Top-level lexical environment
251 mg_fix_env :: !FixityEnv, -- Fixity env, for things declared in this module
252 mg_deprecs :: !Deprecations, -- Deprecations declared in the module
254 mg_types :: !TypeEnv,
255 mg_insts :: ![DFunId], -- Instances
256 mg_rules :: ![IdCoreRule], -- Rules from this module
257 mg_binds :: ![CoreBind], -- Bindings for this module
258 mg_foreign :: !ForeignStubs
261 -- The ModGuts takes on several slightly different forms:
263 -- After simplification, the following fields change slightly:
264 -- mg_rules Orphan rules only (local ones now attached to binds)
265 -- mg_binds With rules attached
267 -- After CoreTidy, the following fields change slightly:
268 -- mg_types Now contains Ids as well, replete with final IdInfo
269 -- The Ids are only the ones that are visible from
270 -- importing modules. Without -O that means only
271 -- exported Ids, but with -O importing modules may
272 -- see ids mentioned in unfoldings of exported Ids
274 -- mg_insts Same DFunIds as before, but with final IdInfo,
275 -- and the unique might have changed; remember that
276 -- CoreTidy links up the uniques of old and new versions
278 -- mg_rules All rules for exported things, substituted with final Ids
286 imp_direct :: ![(Module,Bool)], -- Explicitly-imported modules
287 -- Boolean is true if we imported the whole
288 -- module (apart, perhaps, from hiding some)
289 imp_pkg_mods :: !ModuleSet, -- Non-home-package modules on which we depend,
290 -- directly or indirectly
291 imp_home_names :: !NameSet -- Home package things on which we depend,
292 -- directly or indirectly
295 data ForeignStubs = NoStubs
297 SDoc -- Header file prototypes for
298 -- "foreign exported" functions
299 SDoc -- C stubs to use when calling
300 -- "foreign exported" functions
301 [FastString] -- Headers that need to be included
302 -- into C code generated for this module
303 [Id] -- Foreign-exported binders
304 -- we have to generate code to register these
307 data IfaceDecls = IfaceDecls { dcl_tycl :: [RenamedTyClDecl], -- Sorted
308 dcl_rules :: [RenamedRuleDecl], -- Sorted
309 dcl_insts :: [RenamedInstDecl] } -- Unsorted
311 mkIfaceDecls :: [RenamedTyClDecl] -> [RenamedRuleDecl] -> [RenamedInstDecl] -> IfaceDecls
312 -- Sort to put them in canonical order for version comparison
313 mkIfaceDecls tycls rules insts
314 = IfaceDecls { dcl_tycl = sortLt lt_tycl tycls,
315 dcl_rules = sortLt lt_rule rules,
316 dcl_insts = sortLt lt_inst insts }
318 d1 `lt_tycl` d2 = tyClDeclName d1 < tyClDeclName d2
319 r1 `lt_rule` r2 = ifaceRuleDeclName r1 < ifaceRuleDeclName r2
320 i1 `lt_inst` i2 = instDeclDFun i1 < instDeclDFun i2
324 emptyModIface :: Module -> ModIface
326 = ModIface { mi_module = mod,
327 mi_package = basePackage, -- XXX fully bogus
328 mi_version = initialVersionInfo,
330 mi_deps = noDependencies,
334 mi_fixities = emptyNameEnv,
335 mi_globals = Nothing,
336 mi_deprecs = NoDeprecs,
337 mi_decls = panic "emptyModIface: decls"
342 %************************************************************************
344 Parsed interface files
346 %************************************************************************
348 A ParsedIface is exactly as read from an interface file.
351 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
352 -- Nothing => NoDeprecs
353 -- Just (Left t) => DeprecAll
354 -- Just (Right p) => DeprecSome
358 pi_mod :: ModuleName,
359 pi_pkg :: PackageName,
360 pi_vers :: Version, -- Module version number
361 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
362 pi_deps :: Dependencies, -- What it depends on
363 pi_usages :: [Usage OccName], -- Usages
364 pi_exports :: (Version, [RdrExportItem]), -- Exports
365 pi_decls :: [(Version, TyClDecl RdrName)], -- Local definitions
366 pi_fixity :: [FixitySig RdrName], -- Local fixity declarations,
367 pi_insts :: [InstDecl RdrName], -- Local instance declarations
368 pi_rules :: (Version, [RuleDecl RdrName]), -- Rules, with their version
369 pi_deprecs :: IfaceDeprecs -- Deprecations
374 %************************************************************************
376 \subsection{The interactive context}
378 %************************************************************************
381 data InteractiveContext
382 = InteractiveContext {
383 ic_toplev_scope :: [Module], -- Include the "top-level" scope of
386 ic_exports :: [Module], -- Include just the exports of these
389 ic_rn_gbl_env :: GlobalRdrEnv, -- The cached GlobalRdrEnv, built from
390 -- ic_toplev_scope and ic_exports
392 ic_rn_local_env :: LocalRdrEnv, -- Lexical context for variables bound
393 -- during interaction
395 ic_type_env :: TypeEnv -- Ditto for types
398 emptyInteractiveContext
399 = InteractiveContext { ic_toplev_scope = [],
401 ic_rn_gbl_env = emptyRdrEnv,
402 ic_rn_local_env = emptyRdrEnv,
403 ic_type_env = emptyTypeEnv }
405 icPrintUnqual :: InteractiveContext -> PrintUnqualified
406 icPrintUnqual ictxt = unQualInScope (ic_rn_gbl_env ictxt)
410 %************************************************************************
412 \subsection{Type environment stuff}
414 %************************************************************************
417 typeEnvElts :: TypeEnv -> [TyThing]
418 typeEnvClasses :: TypeEnv -> [Class]
419 typeEnvTyCons :: TypeEnv -> [TyCon]
420 typeEnvIds :: TypeEnv -> [Id]
422 typeEnvElts env = nameEnvElts env
423 typeEnvClasses env = [cl | AClass cl <- typeEnvElts env]
424 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
425 typeEnvIds env = [id | AnId id <- typeEnvElts env]
427 implicitTyThingIds :: [TyThing] -> [Id]
428 -- Add the implicit data cons and selectors etc
429 implicitTyThingIds things
430 = concat (map go things)
433 go (AClass cl) = classSelIds cl
434 go (ATyCon tc) = tyConGenIds tc ++
436 [ n | dc <- tyConDataCons_maybe tc `orElse` [],
437 n <- implicitConIds tc dc]
438 -- Synonyms return empty list of constructors and selectors
440 implicitConIds tc dc -- Newtypes have a constructor wrapper,
442 | isNewTyCon tc = [dataConWrapId dc]
443 | otherwise = [dataConWorkId dc, dataConWrapId dc]
448 type TypeEnv = NameEnv TyThing
450 emptyTypeEnv = emptyNameEnv
452 mkTypeEnv :: [TyThing] -> TypeEnv
453 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
455 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
456 extendTypeEnvList env things
457 = extendNameEnvList env [(getName thing, thing) | thing <- things]
459 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
460 extendTypeEnvWithIds env ids
461 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
465 lookupType :: HomePackageTable -> PackageTypeEnv -> Name -> Maybe TyThing
466 lookupType hpt pte name
467 = case lookupModuleEnv hpt (nameModule name) of
468 Just details -> lookupNameEnv (md_types (hm_details details)) name
469 Nothing -> lookupNameEnv pte name
472 %************************************************************************
474 \subsection{Auxiliary types}
476 %************************************************************************
478 These types are defined here because they are mentioned in ModDetails,
479 but they are mostly elaborated elsewhere
484 vers_module :: Version, -- Changes when anything changes
485 vers_exports :: Version, -- Changes when export list changes
486 vers_rules :: Version, -- Changes when any rule changes
487 vers_decls :: NameEnv Version
488 -- Versions for "big" names only (not data constructors, class ops)
489 -- The version of an Id changes if its fixity changes
490 -- Ditto data constructors, class operations, except that the version of
491 -- the parent class/tycon changes
493 -- If a name isn't in the map, it means 'initialVersion'
496 initialVersionInfo :: VersionInfo
497 initialVersionInfo = VersionInfo { vers_module = initialVersion,
498 vers_exports = initialVersion,
499 vers_rules = initialVersion,
500 vers_decls = emptyNameEnv
503 lookupVersion :: NameEnv Version -> Name -> Version
504 lookupVersion env name = lookupNameEnv env name `orElse` initialVersion
506 data Deprecations = NoDeprecs
507 | DeprecAll DeprecTxt -- Whole module deprecated
508 | DeprecSome (NameEnv (Name,DeprecTxt)) -- Some things deprecated
510 -- We keep the Name in the range, so we can print them out
512 lookupDeprec :: Deprecations -> Name -> Maybe DeprecTxt
513 lookupDeprec NoDeprecs name = Nothing
514 lookupDeprec (DeprecAll txt) name = Just txt
515 lookupDeprec (DeprecSome env) name = case lookupNameEnv env name of
516 Just (_, txt) -> Just txt
519 plusDeprecs :: Deprecations -> Deprecations -> Deprecations
520 plusDeprecs d NoDeprecs = d
521 plusDeprecs NoDeprecs d = d
522 plusDeprecs d (DeprecAll t) = DeprecAll t
523 plusDeprecs (DeprecAll t) d = DeprecAll t
524 plusDeprecs (DeprecSome v1) (DeprecSome v2) = DeprecSome (v1 `plusNameEnv` v2)
526 instance Eq Deprecations where
527 -- Used when checking whether we need write a new interface
528 NoDeprecs == NoDeprecs = True
529 (DeprecAll t1) == (DeprecAll t2) = t1 == t2
530 (DeprecSome e1) == (DeprecSome e2) = nameEnvElts e1 == nameEnvElts e2
536 type Avails = [AvailInfo]
537 type AvailInfo = GenAvailInfo Name
538 type RdrAvailInfo = GenAvailInfo OccName
540 data GenAvailInfo name = Avail name -- An ordinary identifier
541 | AvailTC name -- The name of the type or class
542 [name] -- The available pieces of type/class.
543 -- NB: If the type or class is itself
544 -- to be in scope, it must be in this list.
545 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
547 -- Equality used when deciding if the interface has changed
549 type RdrExportItem = (ModuleName, [RdrAvailInfo])
550 type ExportItem = (ModuleName, [AvailInfo])
552 availsToNameSet :: [AvailInfo] -> NameSet
553 availsToNameSet avails = foldl add emptyNameSet avails
555 add set avail = addListToNameSet set (availNames avail)
557 availName :: GenAvailInfo name -> name
558 availName (Avail n) = n
559 availName (AvailTC n _) = n
561 availNames :: GenAvailInfo name -> [name]
562 availNames (Avail n) = [n]
563 availNames (AvailTC n ns) = ns
565 instance Outputable n => Outputable (GenAvailInfo n) where
568 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
569 pprAvail (AvailTC n ns) = ppr n <> case {- filter (/= n) -} ns of
571 ns' -> braces (hsep (punctuate comma (map ppr ns')))
573 pprAvail (Avail n) = ppr n
577 type FixityEnv = NameEnv (FixitySig Name)
578 -- We keep the whole fixity sig so that we
579 -- can report line-number info when there is a duplicate
580 -- fixity declaration
582 emptyFixityEnv :: FixityEnv
583 emptyFixityEnv = emptyNameEnv
585 lookupFixity :: FixityEnv -> Name -> Fixity
586 lookupFixity env n = case lookupNameEnv env n of
587 Just (FixitySig _ fix _) -> fix
588 Nothing -> defaultFixity
590 collectFixities :: FixityEnv -> [TyClDecl Name] -> [FixitySig Name]
591 -- Collect fixities for the specified declarations
592 collectFixities env decls
594 | d <- decls, (n,_) <- tyClDeclNames d,
595 Just fix <- [lookupNameEnv env n]
600 %************************************************************************
602 \subsection{WhatsImported}
604 %************************************************************************
607 type WhetherHasOrphans = Bool
609 -- * an instance decl in a module other than the defn module for
610 -- one of the tycons or classes in the instance head
611 -- * a transformation rule in a module other than the one defining
612 -- the function in the head of the rule.
614 type IsBootInterface = Bool
616 -- Dependency info about modules and packages below this one
617 -- in the import hierarchy. See TcRnTypes.ImportAvails for details.
619 -- Invariant: the dependencies of a module M never includes M
621 = Deps { dep_mods :: [(ModuleName,IsBootInterface)], -- Home-package module dependencies
622 dep_pkgs :: [PackageName], -- External package dependencies
623 dep_orphs :: [ModuleName] } -- Orphan modules (whether home or external pkg)
625 noDependencies :: Dependencies
626 noDependencies = Deps [] [] []
629 = Usage { usg_name :: ModuleName, -- Name of the module
630 usg_mod :: Version, -- Module version
631 usg_exports :: Maybe Version, -- Export-list version, if we depend on it
632 usg_entities :: [(name,Version)], -- Sorted by occurrence name
633 usg_rules :: Version -- Rules version
635 -- This type doesn't let you say "I imported f but none of the rules in
636 -- the module". If you use anything in the module you get its rule version
637 -- So if the rules change, you'll recompile, even if you don't use them.
638 -- This is easy to implement, and it's safer: you might not have used the rules last
639 -- time round, but if someone has added a new rule you might need it this time
641 -- The export list field is (Just v) if we depend on the export list:
642 -- i.e. we imported the module without saying exactly what we imported
643 -- We need to recompile if the module exports changes, because we might
644 -- now have a name clash in the importing module.
648 %************************************************************************
650 \subsection{The persistent compiler state}
652 %************************************************************************
654 The @PersistentCompilerState@ persists across successive calls to the
658 data PersistentCompilerState
660 pcs_nc :: !NameCache,
661 pcs_EPS :: !ExternalPackageState
667 type PackageTypeEnv = TypeEnv
668 type PackageRuleBase = RuleBase
669 type PackageInstEnv = InstEnv
671 data ExternalPackageState
673 eps_PIT :: !PackageIfaceTable,
674 -- The ModuleIFaces for modules in external packages
675 -- whose interfaces we have opened
676 -- The declarations in these interface files are held in
677 -- eps_decls, eps_insts, eps_rules (below), not in the
678 -- mi_decls fields of the iPIT.
679 -- What _is_ in the iPIT is:
686 eps_PTE :: !PackageTypeEnv, -- Domain = external-package modules
688 eps_inst_env :: !PackageInstEnv, -- The total InstEnv accumulated from
689 -- all the external-package modules
690 eps_rule_base :: !PackageRuleBase, -- Ditto RuleEnv
693 -- Holding pens for stuff that has been read in from file,
694 -- but not yet slurped into the renamer
695 eps_decls :: !DeclsMap,
696 -- A single, global map of Names to unslurped decls
697 eps_insts :: !IfaceInsts,
698 -- The as-yet un-slurped instance decls; this bag is depleted when we
699 -- slurp an instance decl so that we don't slurp the same one twice.
700 -- Each is 'gated' by the names that must be available before
701 -- this instance decl is needed.
702 eps_rules :: !IfaceRules,
703 -- Similar to instance decls, only for rules
705 eps_inst_gates :: !NameSet -- Gates for instance decls
706 -- The instance gates must accumulate across
707 -- all invocations of the renamer;
708 -- see "the gating story" in RnIfaces.lhs
709 -- These names should all be from other packages;
710 -- for the home package we have all the instance
711 -- declarations anyhow
715 The NameCache makes sure that there is just one Unique assigned for
716 each original name; i.e. (module-name, occ-name) pair. The Name is
717 always stored as a Global, and has the SrcLoc of its binding location.
718 Actually that's not quite right. When we first encounter the original
719 name, we might not be at its binding site (e.g. we are reading an
720 interface file); so we give it 'noSrcLoc' then. Later, when we find
721 its binding site, we fix it up.
723 Exactly the same is true of the Module stored in the Name. When we first
724 encounter the occurrence, we may not know the details of the module, so
725 we just store junk. Then when we find the binding site, we fix it up.
729 = NameCache { nsUniqs :: UniqSupply,
731 nsNames :: OrigNameCache,
732 -- Ensures that one original name gets one unique
733 nsIPs :: OrigIParamCache
734 -- Ensures that one implicit parameter name gets one unique
737 type OrigNameCache = ModuleEnv (Module, OccNameCache)
738 -- Maps a module *name* to a Module,
739 -- plus the OccNameEnv fot that module
740 type OccNameCache = FiniteMap OccName Name
741 -- Maps the OccName to a Name
742 -- A FiniteMap because OccNames have a Namespace/Faststring pair
744 type OrigIParamCache = FiniteMap (IPName RdrName) (IPName Name)
747 A DeclsMap contains a binding for each Name in the declaration
748 including the constructors of a type decl etc. The Bool is True just
752 type DeclsMap = (NameEnv (AvailInfo, Bool, (Module, TyClDecl RdrName)), Int)
753 -- The Int says how many have been sucked in
755 type IfaceInsts = GatedDecls (InstDecl RdrName)
756 type IfaceRules = GatedDecls (RuleDecl RdrName)
758 type GatedDecls d = (Bag (GatedDecl d), Int) -- The Int says how many have been sucked in
759 type GatedDecl d = (GateFn, (Module, d))
760 type GateFn = (Name -> Bool) -> Bool -- Returns True <=> gate is open
761 -- The (Name -> Bool) fn returns True for visible Names
762 -- For example, suppose this is in an interface file
763 -- instance C T where ...
764 -- We want to slurp this decl if both C and T are "visible" in
765 -- the importing module. See "The gating story" in RnIfaces for details.
769 %************************************************************************
771 \subsection{Linkable stuff}
773 %************************************************************************
775 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
776 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
780 linkableTime :: ClockTime, -- Time at which this linkable was built
781 -- (i.e. when the bytecodes were produced,
782 -- or the mod date on the files)
783 linkableModName :: ModuleName, -- Should be Module, but see below
784 linkableUnlinked :: [Unlinked]
787 isObjectLinkable :: Linkable -> Bool
788 isObjectLinkable l = all isObject (linkableUnlinked l)
790 instance Outputable Linkable where
791 ppr (LM when_made mod unlinkeds)
792 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
793 $$ nest 3 (ppr unlinkeds)
795 -------------------------------------------
800 | BCOs CompiledByteCode
803 data CompiledByteCode = NoByteCode
806 instance Outputable Unlinked where
807 ppr (DotO path) = text "DotO" <+> text path
808 ppr (DotA path) = text "DotA" <+> text path
809 ppr (DotDLL path) = text "DotDLL" <+> text path
811 ppr (BCOs bcos) = text "BCOs" <+> ppr bcos
813 ppr (BCOs bcos) = text "No byte code"
816 isObject (DotO _) = True
817 isObject (DotA _) = True
818 isObject (DotDLL _) = True
821 isInterpretable = not . isObject
823 nameOfObject (DotO fn) = fn
824 nameOfObject (DotA fn) = fn
825 nameOfObject (DotDLL fn) = fn
827 byteCodeOfObject (BCOs bc) = bc
831 %************************************************************************
833 \subsection{Provenance and export info}
835 %************************************************************************
837 A LocalRdrEnv is used for local bindings (let, where, lambda, case)
841 type LocalRdrEnv = RdrNameEnv Name
843 extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
844 extendLocalRdrEnv env names
845 = addListToRdrEnv env [(mkRdrUnqual (nameOccName n), n) | n <- names]
848 The GlobalRdrEnv gives maps RdrNames to Names. There is a separate
849 one for each module, corresponding to that module's top-level scope.
852 type GlobalRdrEnv = RdrNameEnv [GlobalRdrElt]
853 -- The list is because there may be name clashes
854 -- These only get reported on lookup, not on construction
856 emptyGlobalRdrEnv = emptyRdrEnv
859 = GRE { gre_name :: Name,
860 gre_parent :: Name, -- Name of the "parent" structure
861 -- * the tycon of a data con
862 -- * the class of a class op
863 -- For others it's just the same as gre_name
864 gre_prov :: Provenance, -- Why it's in scope
865 gre_deprec :: Maybe DeprecTxt -- Whether this name is deprecated
868 instance Outputable GlobalRdrElt where
869 ppr gre = ppr (gre_name gre) <+>
870 parens (hsep [text "parent:" <+> ppr (gre_parent gre) <> comma,
871 pprNameProvenance gre])
873 = vcat (map pp (rdrEnvToList env))
875 pp (rn, gres) = ppr rn <> colon <+>
876 vcat [ ppr (gre_name gre) <+> pprNameProvenance gre
879 isLocalGRE :: GlobalRdrElt -> Bool
880 isLocalGRE (GRE {gre_prov = LocalDef}) = True
881 isLocalGRE other = False
884 @unQualInScope@ returns a function that takes a @Name@ and tells whether
885 its unqualified name is in scope. This is put as a boolean flag in
886 the @Name@'s provenance to guide whether or not to print the name qualified
890 unQualInScope :: GlobalRdrEnv -> Name -> Bool
891 -- True if 'f' is in scope, and has only one binding,
892 -- and the thing it is bound to is the name we are looking for
893 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
895 -- Also checks for built-in syntax, which is always 'in scope'
897 -- This fn is only efficient if the shared
898 -- partial application is used a lot.
900 = \n -> n `elemNameSet` unqual_names || isBuiltInSyntaxName n
902 unqual_names :: NameSet
903 unqual_names = foldRdrEnv add emptyNameSet env
904 add rdr_name [gre] unquals | isUnqual rdr_name = addOneToNameSet unquals (gre_name gre)
905 add _ _ unquals = unquals
908 The "provenance" of something says how it came to be in scope.
912 = LocalDef -- Defined locally
914 | NonLocalDef -- Defined non-locally
917 -- Just used for grouping error messages (in RnEnv.warnUnusedBinds)
918 instance Eq Provenance where
919 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
921 instance Eq ImportReason where
922 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
924 instance Ord Provenance where
925 compare LocalDef LocalDef = EQ
926 compare LocalDef (NonLocalDef _) = LT
927 compare (NonLocalDef _) LocalDef = GT
929 compare (NonLocalDef reason1) (NonLocalDef reason2)
930 = compare reason1 reason2
932 instance Ord ImportReason where
933 compare ImplicitImport ImplicitImport = EQ
934 compare ImplicitImport (UserImport _ _ _) = LT
935 compare (UserImport _ _ _) ImplicitImport = GT
936 compare (UserImport m1 loc1 _) (UserImport m2 loc2 _)
937 = (m1 `compare` m2) `thenCmp` (loc1 `compare` loc2)
941 = UserImport Module SrcLoc Bool -- Imported from module M on line L
942 -- Note the M may well not be the defining module
944 -- The Bool is true iff the thing was named *explicitly* in the import spec,
945 -- rather than being imported as part of a group; e.g.
948 -- Here, everything imported by B, and the constructors of T
949 -- are not named explicitly; only T is named explicitly.
950 -- This info is used when warning of unused names.
952 | ImplicitImport -- Imported implicitly for some other reason
956 hasBetterProv :: Provenance -> Provenance -> Bool
958 -- a local thing over an imported thing
959 -- a user-imported thing over a non-user-imported thing
960 -- an explicitly-imported thing over an implicitly imported thing
961 hasBetterProv LocalDef _ = True
962 hasBetterProv (NonLocalDef (UserImport _ _ _ )) (NonLocalDef ImplicitImport) = True
963 hasBetterProv _ _ = False
965 pprNameProvenance :: GlobalRdrElt -> SDoc
966 pprNameProvenance (GRE {gre_name = name, gre_prov = prov})
968 LocalDef -> ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
969 NonLocalDef why -> sep [ppr_reason why,
970 nest 2 (ppr_defn (nameSrcLoc name))]
972 ppr_reason ImplicitImport = ptext SLIT("implicitly imported")
973 ppr_reason (UserImport mod loc _) = ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
975 ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("defined at") <+> ppr loc)