Breakpoint code instrumentation
[ghc-hetmet.git] / compiler / main / HscTypes.lhs
1 %
2 % (c) The University of Glasgow, 2006
3 %
4 \section[HscTypes]{Types for the per-module compiler}
5
6 \begin{code}
7 module HscTypes ( 
8         -- * Sessions and compilation state
9         Session(..), HscEnv(..), hscEPS,
10         FinderCache, FindResult(..), ModLocationCache,
11         Target(..), TargetId(..), pprTarget, pprTargetId,
12         ModuleGraph, emptyMG,
13
14         ModDetails(..), emptyModDetails,
15         ModGuts(..), CgGuts(..), ModImports(..), ForeignStubs(..),
16
17         ModSummary(..), showModMsg, isBootSummary,
18         msHsFilePath, msHiFilePath, msObjFilePath, 
19
20         HscSource(..), isHsBoot, hscSourceString,       -- Re-exported from DriverPhases
21         
22         HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
23         hptInstances, hptRules,
24
25         ExternalPackageState(..), EpsStats(..), addEpsInStats,
26         PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
27         lookupIfaceByModule, emptyModIface,
28
29         InteractiveContext(..), emptyInteractiveContext, 
30         icPrintUnqual, mkPrintUnqualified,
31
32         ModIface(..), mkIfaceDepCache, mkIfaceVerCache, mkIfaceFixCache,
33         emptyIfaceDepCache,
34
35         Deprecs(..), IfaceDeprecs,
36
37         FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
38
39         implicitTyThings, isImplicitTyThing,
40
41         TyThing(..), tyThingClass, tyThingTyCon, tyThingDataCon, tyThingId,
42         TypeEnv, lookupType, mkTypeEnv, emptyTypeEnv,
43         extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv,
44         typeEnvElts, typeEnvClasses, typeEnvTyCons, typeEnvIds,
45         typeEnvDataCons,
46
47         WhetherHasOrphans, IsBootInterface, Usage(..), 
48         Dependencies(..), noDependencies,
49         NameCache(..), OrigNameCache, OrigIParamCache,
50         Avails, availsToNameSet, availsToNameEnv, availName, availNames,
51         GenAvailInfo(..), AvailInfo, RdrAvailInfo, 
52         IfaceExport,
53
54         Deprecations, DeprecTxt, plusDeprecs,
55
56         PackageInstEnv, PackageRuleBase,
57
58         -- Linker stuff
59         Linkable(..), isObjectLinkable,
60         Unlinked(..), CompiledByteCode,
61         isObject, nameOfObject, isInterpretable, byteCodeOfObject,
62         HpcInfo, noHpcInfo
63     ) where
64
65 #include "HsVersions.h"
66
67 import Breakpoints      ( SiteNumber, Coord, noDbgSites )
68 #ifdef GHCI
69 import ByteCodeAsm      ( CompiledByteCode )
70 #endif
71
72 import RdrName          ( GlobalRdrEnv, emptyGlobalRdrEnv,
73                           LocalRdrEnv, emptyLocalRdrEnv, GlobalRdrElt(..), 
74                           unQualOK, ImpDeclSpec(..), Provenance(..),
75                           ImportSpec(..), lookupGlobalRdrEnv )
76 import Name             ( Name, NamedThing, getName, nameOccName, nameModule )
77 import NameEnv
78 import NameSet  
79 import OccName          ( OccName, OccEnv, lookupOccEnv, mkOccEnv, emptyOccEnv, 
80                           extendOccEnv )
81 import Module
82 import InstEnv          ( InstEnv, Instance )
83 import FamInstEnv       ( FamInstEnv, FamInst )
84 import Rules            ( RuleBase )
85 import CoreSyn          ( CoreBind )
86 import Id               ( Id, isImplicitId )
87 import Type             ( TyThing(..) )
88
89 import Class            ( Class, classSelIds, classATs, classTyCon )
90 import TyCon
91 import DataCon          ( DataCon, dataConImplicitIds )
92 import PrelNames        ( gHC_PRIM )
93 import Packages         ( PackageId )
94 import DynFlags         ( DynFlags(..), isOneShot, HscTarget (..) )
95 import DriverPhases     ( HscSource(..), isHsBoot, hscSourceString, Phase )
96 import BasicTypes       ( Version, initialVersion, IPName, 
97                           Fixity, defaultFixity, DeprecTxt )
98 import IfaceSyn
99 import FiniteMap        ( FiniteMap )
100 import CoreSyn          ( CoreRule )
101 import Maybes           ( orElse, expectJust, catMaybes, seqMaybe )
102 import Outputable
103 import SrcLoc           ( SrcSpan, Located )
104 import UniqFM           ( lookupUFM, eltsUFM, emptyUFM )
105 import UniqSupply       ( UniqSupply )
106 import FastString       ( FastString )
107
108 import StringBuffer     ( StringBuffer )
109
110 import System.Time      ( ClockTime )
111 import Data.IORef       ( IORef, readIORef )
112 \end{code}
113
114
115 %************************************************************************
116 %*                                                                      *
117 \subsection{Compilation environment}
118 %*                                                                      *
119 %************************************************************************
120
121
122 \begin{code}
123 -- | The Session is a handle to the complete state of a compilation
124 -- session.  A compilation session consists of a set of modules
125 -- constituting the current program or library, the context for
126 -- interactive evaluation, and various caches.
127 newtype Session = Session (IORef HscEnv)
128 \end{code}
129
130 HscEnv is like Session, except that some of the fields are immutable.
131 An HscEnv is used to compile a single module from plain Haskell source
132 code (after preprocessing) to either C, assembly or C--.  Things like
133 the module graph don't change during a single compilation.
134
135 Historical note: "hsc" used to be the name of the compiler binary,
136 when there was a separate driver and compiler.  To compile a single
137 module, the driver would invoke hsc on the source code... so nowadays
138 we think of hsc as the layer of the compiler that deals with compiling
139 a single module.
140
141 \begin{code}
142 data HscEnv 
143   = HscEnv { 
144         hsc_dflags :: DynFlags,
145                 -- The dynamic flag settings
146
147         hsc_targets :: [Target],
148                 -- The targets (or roots) of the current session
149
150         hsc_mod_graph :: ModuleGraph,
151                 -- The module graph of the current session
152
153         hsc_IC :: InteractiveContext,
154                 -- The context for evaluating interactive statements
155
156         hsc_HPT    :: HomePackageTable,
157                 -- The home package table describes already-compiled
158                 -- home-packge modules, *excluding* the module we 
159                 -- are compiling right now.
160                 -- (In one-shot mode the current module is the only
161                 --  home-package module, so hsc_HPT is empty.  All other
162                 --  modules count as "external-package" modules.
163                 --  However, even in GHCi mode, hi-boot interfaces are
164                 --  demand-loadeded into the external-package table.)
165                 --
166                 -- hsc_HPT is not mutable because we only demand-load 
167                 -- external packages; the home package is eagerly 
168                 -- loaded, module by module, by the compilation manager.
169                 --      
170                 -- The HPT may contain modules compiled earlier by --make
171                 -- but not actually below the current module in the dependency
172                 -- graph.  (This changes a previous invariant: changed Jan 05.)
173         
174         hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
175         hsc_NC  :: {-# UNPACK #-} !(IORef NameCache),
176                 -- These are side-effected by compiling to reflect
177                 -- sucking in interface files.  They cache the state of
178                 -- external interface files, in effect.
179
180         hsc_FC   :: {-# UNPACK #-} !(IORef FinderCache),
181         hsc_MLC  :: {-# UNPACK #-} !(IORef ModLocationCache),
182                 -- The finder's cache.  This caches the location of modules,
183                 -- so we don't have to search the filesystem multiple times.
184
185         hsc_global_rdr_env :: GlobalRdrEnv,
186         hsc_global_type_env :: TypeEnv
187  }
188
189 hscEPS :: HscEnv -> IO ExternalPackageState
190 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
191
192 -- | A compilation target.
193 --
194 -- A target may be supplied with the actual text of the
195 -- module.  If so, use this instead of the file contents (this
196 -- is for use in an IDE where the file hasn't been saved by
197 -- the user yet).
198 data Target = Target TargetId (Maybe (StringBuffer,ClockTime))
199
200 data TargetId
201   = TargetModule ModuleName
202         -- ^ A module name: search for the file
203   | TargetFile FilePath (Maybe Phase)
204         -- ^ A filename: preprocess & parse it to find the module name.
205         -- If specified, the Phase indicates how to compile this file
206         -- (which phase to start from).  Nothing indicates the starting phase
207         -- should be determined from the suffix of the filename.
208   deriving Eq
209
210 pprTarget :: Target -> SDoc
211 pprTarget (Target id _) = pprTargetId id
212
213 instance Outputable Target where
214     ppr = pprTarget
215
216 pprTargetId (TargetModule m) = ppr m
217 pprTargetId (TargetFile f _) = text f
218
219 instance Outputable TargetId where
220     ppr = pprTargetId
221
222 type HomePackageTable  = ModuleNameEnv HomeModInfo
223         -- Domain = modules in the home package
224         -- "home" package name cached here for convenience
225 type PackageIfaceTable = ModuleEnv ModIface
226         -- Domain = modules in the imported packages
227
228 emptyHomePackageTable  = emptyUFM
229 emptyPackageIfaceTable = emptyModuleEnv
230
231 data HomeModInfo 
232   = HomeModInfo { hm_iface    :: !ModIface,
233                   hm_details  :: !ModDetails,
234                   hm_linkable :: !(Maybe Linkable) }
235                 -- hm_linkable might be Nothing if:
236                 --   a) this is an .hs-boot module
237                 --   b) temporarily during compilation if we pruned away
238                 --      the old linkable because it was out of date.
239                 -- after a complete compilation (GHC.load), all hm_linkable
240                 -- fields in the HPT will be Just.
241                 --
242                 -- When re-linking a module (hscNoRecomp), we construct
243                 -- the HomModInfo by building a new ModDetails from the
244                 -- old ModIface (only).
245
246 -- | Find the 'ModIface' for a 'Module'
247 lookupIfaceByModule
248         :: DynFlags
249         -> HomePackageTable
250         -> PackageIfaceTable
251         -> Module
252         -> Maybe ModIface
253 lookupIfaceByModule dflags hpt pit mod
254   | modulePackageId mod == thisPackage dflags
255   =     -- The module comes from the home package, so look first
256         -- in the HPT.  If it's not from the home package it's wrong to look
257         -- in the HPT, because the HPT is indexed by *ModuleName* not Module
258     fmap hm_iface (lookupUFM hpt (moduleName mod)) 
259     `seqMaybe` lookupModuleEnv pit mod
260
261   | otherwise = lookupModuleEnv pit mod         -- Look in PIT only 
262
263 -- If the module does come from the home package, why do we look in the PIT as well?
264 -- (a) In OneShot mode, even home-package modules accumulate in the PIT
265 -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
266 --     module is in the PIT, namely GHC.Prim when compiling the base package.
267 -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a packake
268 -- of its own, but it doesn't seem worth the bother.
269 \end{code}
270
271
272 \begin{code}
273 hptInstances :: HscEnv -> (ModuleName -> Bool) -> [Instance]
274 -- Find all the instance declarations that are in modules imported 
275 -- by this one, directly or indirectly, and are in the Home Package Table
276 -- This ensures that we don't see instances from modules --make compiled 
277 -- before this one, but which are not below this one
278 hptInstances hsc_env want_this_module
279   = [ ispec 
280     | mod_info <- eltsUFM (hsc_HPT hsc_env)
281     , want_this_module (moduleName (mi_module (hm_iface mod_info)))
282     , ispec <- md_insts (hm_details mod_info) ]
283
284 hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
285 -- Get rules from modules "below" this one (in the dependency sense)
286 -- C.f Inst.hptInstances
287 hptRules hsc_env deps
288   | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
289   | otherwise
290   = let 
291         hpt = hsc_HPT hsc_env
292     in
293     [ rule
294     |   -- Find each non-hi-boot module below me
295       (mod, False) <- deps
296
297         -- unsavoury: when compiling the base package with --make, we
298         -- sometimes try to look up RULES for GHC.Prim.  GHC.Prim won't
299         -- be in the HPT, because we never compile it; it's in the EPT
300         -- instead.  ToDo: clean up, and remove this slightly bogus
301         -- filter:
302     , mod /= moduleName gHC_PRIM
303
304         -- Look it up in the HPT
305     , let rules = case lookupUFM hpt mod of
306                     Just info -> md_rules (hm_details info)
307                     Nothing -> pprTrace "WARNING in hptRules" msg [] 
308           msg = vcat [ptext SLIT("missing module") <+> ppr mod,
309                       ptext SLIT("Probable cause: out-of-date interface files")]
310                         -- This really shouldn't happen, but see Trac #962
311
312         -- And get its dfuns
313     , rule <- rules ]
314 \end{code}
315
316 %************************************************************************
317 %*                                                                      *
318 \subsection{The Finder cache}
319 %*                                                                      *
320 %************************************************************************
321
322 \begin{code}
323 -- | The 'FinderCache' maps home module names to the result of
324 -- searching for that module.  It records the results of searching for
325 -- modules along the search path.  On @:load@, we flush the entire
326 -- contents of this cache.
327 --
328 -- Although the @FinderCache@ range is 'FindResult' for convenience ,
329 -- in fact it will only ever contain 'Found' or 'NotFound' entries.
330 --
331 type FinderCache = ModuleNameEnv FindResult
332
333 -- | The result of searching for an imported module.
334 data FindResult
335   = Found ModLocation Module
336         -- the module was found
337   | NoPackage PackageId
338         -- the requested package was not found
339   | FoundMultiple [PackageId]
340         -- *error*: both in multiple packages
341   | PackageHidden PackageId
342         -- for an explicit source import: the package containing the module is
343         -- not exposed.
344   | ModuleHidden  PackageId
345         -- for an explicit source import: the package containing the module is
346         -- exposed, but the module itself is hidden.
347   | NotFound [FilePath] (Maybe PackageId)
348         -- the module was not found, the specified places were searched
349   | NotFoundInPackage PackageId
350         -- the module was not found in this package
351
352 -- | Cache that remembers where we found a particular module.  Contains both
353 -- home modules and package modules.  On @:load@, only home modules are
354 -- purged from this cache.
355 type ModLocationCache = ModuleEnv ModLocation
356 \end{code}
357
358 %************************************************************************
359 %*                                                                      *
360 \subsection{Symbol tables and Module details}
361 %*                                                                      *
362 %************************************************************************
363
364 A @ModIface@ plus a @ModDetails@ summarises everything we know 
365 about a compiled module.  The @ModIface@ is the stuff *before* linking,
366 and can be written out to an interface file.  (The @ModDetails@ is after 
367 linking; it is the "linked" form of the mi_decls field.)
368
369 When we *read* an interface file, we also construct a @ModIface@ from it,
370 except that the mi_decls part is empty; when reading we consolidate
371 the declarations into a single indexed map in the @PersistentRenamerState@.
372
373 \begin{code}
374 data ModIface 
375    = ModIface {
376         mi_module   :: !Module,
377         mi_mod_vers :: !Version,            -- Module version: changes when anything changes
378
379         mi_orphan   :: !WhetherHasOrphans,  -- Whether this module has orphans
380         mi_finsts   :: !WhetherHasFamInst,  -- Whether module has family insts
381         mi_boot     :: !IsBootInterface,    -- Read from an hi-boot file?
382
383         mi_deps     :: Dependencies,
384                 -- This is consulted for directly-imported modules,
385                 -- but not for anything else (hence lazy)
386
387                 -- Usages; kept sorted so that it's easy to decide
388                 -- whether to write a new iface file (changing usages
389                 -- doesn't affect the version of this module)
390         mi_usages   :: [Usage],
391                 -- NOT STRICT!  we read this field lazily from the interface file
392                 -- It is *only* consulted by the recompilation checker
393
394                 -- Exports
395                 -- Kept sorted by (mod,occ), to make version comparisons easier
396         mi_exports  :: ![IfaceExport],
397         mi_exp_vers :: !Version,        -- Version number of export list
398
399                 -- Fixities
400         mi_fixities :: [(OccName,Fixity)],
401                 -- NOT STRICT!  we read this field lazily from the interface file
402
403                 -- Deprecations
404         mi_deprecs  :: IfaceDeprecs,
405                 -- NOT STRICT!  we read this field lazily from the interface file
406
407                 -- Type, class and variable declarations
408                 -- The version of an Id changes if its fixity or deprecations change
409                 --      (as well as its type of course)
410                 -- Ditto data constructors, class operations, except that 
411                 -- the version of the parent class/tycon changes
412         mi_decls :: [(Version,IfaceDecl)],      -- Sorted
413
414         mi_globals  :: !(Maybe GlobalRdrEnv),
415                 -- Binds all the things defined at the top level in
416                 -- the *original source* code for this module. which
417                 -- is NOT the same as mi_exports, nor mi_decls (which
418                 -- may contains declarations for things not actually
419                 -- defined by the user).  Used for GHCi and for inspecting
420                 -- the contents of modules via the GHC API only.
421                 --
422                 -- (We need the source file to figure out the
423                 -- top-level environment, if we didn't compile this module
424                 -- from source then this field contains Nothing).
425                 --
426                 -- Strictly speaking this field should live in the
427                 -- HomeModInfo, but that leads to more plumbing.
428
429                 -- Instance declarations and rules
430         mi_insts     :: [IfaceInst],                    -- Sorted
431         mi_fam_insts :: [IfaceFamInst],                 -- Sorted
432         mi_rules     :: [IfaceRule],                    -- Sorted
433         mi_rule_vers :: !Version,       -- Version number for rules and 
434                                         -- instances (for classes and families)
435                                         -- combined
436
437                 -- Cached environments for easy lookup
438                 -- These are computed (lazily) from other fields
439                 -- and are not put into the interface file
440         mi_dep_fn  :: Name -> Maybe DeprecTxt,  -- Cached lookup for mi_deprecs
441         mi_fix_fn  :: OccName -> Fixity,        -- Cached lookup for mi_fixities
442         mi_ver_fn  :: OccName -> Maybe (OccName, Version)
443                         -- Cached lookup for mi_decls
444                         -- The Nothing in mi_ver_fn means that the thing
445                         -- isn't in decls. It's useful to know that when
446                         -- seeing if we are up to date wrt the old interface
447                         -- The 'OccName' is the parent of the name, if it has one.
448      }
449
450 -- Should be able to construct ModDetails from mi_decls in ModIface
451 data ModDetails
452    = ModDetails {
453         -- The next two fields are created by the typechecker
454         md_exports   :: [AvailInfo],
455         md_types     :: !TypeEnv,
456         md_insts     :: ![Instance],    -- Dfun-ids for the instances in this module
457         md_fam_insts :: ![FamInst],
458         md_rules     :: ![CoreRule],    -- Domain may include Ids from other modules
459         md_dbg_sites     :: ![(SiteNumber, Coord)]     -- Breakpoint sites inserted by the renamer
460      }
461
462 emptyModDetails = ModDetails { md_types = emptyTypeEnv,
463                                md_exports = [],
464                                md_insts     = [],
465                                md_rules     = [],
466                                md_fam_insts = [],
467                                md_dbg_sites = noDbgSites}
468
469 -- A ModGuts is carried through the compiler, accumulating stuff as it goes
470 -- There is only one ModGuts at any time, the one for the module
471 -- being compiled right now.  Once it is compiled, a ModIface and 
472 -- ModDetails are extracted and the ModGuts is dicarded.
473
474 data ModGuts
475   = ModGuts {
476         mg_module    :: !Module,
477         mg_boot      :: IsBootInterface, -- Whether it's an hs-boot module
478         mg_exports   :: ![AvailInfo],    -- What it exports
479         mg_deps      :: !Dependencies,   -- What is below it, directly or
480                                          --   otherwise 
481         mg_dir_imps  :: ![Module],       -- Directly-imported modules; used to
482                                          --     generate initialisation code
483         mg_usages    :: ![Usage],        -- Version info for what it needed
484
485         mg_rdr_env   :: !GlobalRdrEnv,   -- Top-level lexical environment
486         mg_fix_env   :: !FixityEnv,      -- Fixity env, for things declared in
487                                          --   this module 
488         mg_deprecs   :: !Deprecations,   -- Deprecations declared in the module
489
490         mg_types     :: !TypeEnv,
491         mg_insts     :: ![Instance],     -- Instances 
492         mg_fam_insts :: ![FamInst],      -- Instances 
493         mg_rules     :: ![CoreRule],     -- Rules from this module
494         mg_binds     :: ![CoreBind],     -- Bindings for this module
495         mg_foreign   :: !ForeignStubs,
496         mg_hpc_info  :: !HpcInfo,        -- info about coverage tick boxes
497         mg_dbg_sites :: ![(SiteNumber, Coord)]     -- Bkpts inserted by the renamer
498     }
499
500 -- The ModGuts takes on several slightly different forms:
501 --
502 -- After simplification, the following fields change slightly:
503 --      mg_rules        Orphan rules only (local ones now attached to binds)
504 --      mg_binds        With rules attached
505
506
507 ---------------------------------------------------------
508 -- The Tidy pass forks the information about this module: 
509 --      * one lot goes to interface file generation (ModIface)
510 --        and later compilations (ModDetails)
511 --      * the other lot goes to code generation (CgGuts)
512 data CgGuts 
513   = CgGuts {
514         cg_module   :: !Module,
515
516         cg_tycons   :: [TyCon],
517                 -- Algebraic data types (including ones that started
518                 -- life as classes); generate constructors and info
519                 -- tables Includes newtypes, just for the benefit of
520                 -- External Core
521
522         cg_binds    :: [CoreBind],
523                 -- The tidied main bindings, including
524                 -- previously-implicit bindings for record and class
525                 -- selectors, and data construtor wrappers.  But *not*
526                 -- data constructor workers; reason: we we regard them
527                 -- as part of the code-gen of tycons
528
529         cg_dir_imps :: ![Module],
530                 -- Directly-imported modules; used to generate
531                 -- initialisation code
532
533         cg_foreign  :: !ForeignStubs,   
534         cg_dep_pkgs :: ![PackageId],    -- Used to generate #includes for C code gen
535         cg_hpc_info :: !HpcInfo         -- info about coverage tick boxes
536     }
537
538 -----------------------------------
539 data ModImports
540   = ModImports {
541         imp_direct     :: ![(Module,Bool)],     -- Explicitly-imported modules
542                                                 -- Boolean is true if we imported the whole
543                                                 --      module (apart, perhaps, from hiding some)
544         imp_pkg_mods   :: !ModuleSet,           -- Non-home-package modules on which we depend,
545                                                 --      directly or indirectly
546         imp_home_names :: !NameSet              -- Home package things on which we depend,
547                                                 --      directly or indirectly
548     }
549
550 -----------------------------------
551 data ForeignStubs = NoStubs
552                   | ForeignStubs
553                         SDoc            -- Header file prototypes for
554                                         --      "foreign exported" functions
555                         SDoc            -- C stubs to use when calling
556                                         --      "foreign exported" functions
557                         [FastString]    -- Headers that need to be included
558                                         --      into C code generated for this module
559                         [Id]            -- Foreign-exported binders
560                                         --      we have to generate code to register these
561
562 \end{code}
563
564 \begin{code}
565 emptyModIface :: Module -> ModIface
566 emptyModIface mod
567   = ModIface { mi_module   = mod,
568                mi_mod_vers = initialVersion,
569                mi_orphan   = False,
570                mi_finsts   = False,
571                mi_boot     = False,
572                mi_deps     = noDependencies,
573                mi_usages   = [],
574                mi_exports  = [],
575                mi_exp_vers = initialVersion,
576                mi_fixities = [],
577                mi_deprecs  = NoDeprecs,
578                mi_insts     = [],
579                mi_fam_insts = [],
580                mi_rules     = [],
581                mi_decls     = [],
582                mi_globals   = Nothing,
583                mi_rule_vers = initialVersion,
584                mi_dep_fn = emptyIfaceDepCache,
585                mi_fix_fn = emptyIfaceFixCache,
586                mi_ver_fn = emptyIfaceVerCache
587     }           
588 \end{code}
589
590
591 %************************************************************************
592 %*                                                                      *
593 \subsection{The interactive context}
594 %*                                                                      *
595 %************************************************************************
596
597 \begin{code}
598 data InteractiveContext 
599   = InteractiveContext { 
600         ic_toplev_scope :: [Module],    -- Include the "top-level" scope of
601                                         -- these modules
602
603         ic_exports :: [Module],         -- Include just the exports of these
604                                         -- modules
605
606         ic_rn_gbl_env :: GlobalRdrEnv,  -- The cached GlobalRdrEnv, built from
607                                         -- ic_toplev_scope and ic_exports
608
609         ic_rn_local_env :: LocalRdrEnv, -- Lexical context for variables bound
610                                         -- during interaction
611
612         ic_type_env :: TypeEnv          -- Ditto for types
613     }
614
615 emptyInteractiveContext
616   = InteractiveContext { ic_toplev_scope = [],
617                          ic_exports = [],
618                          ic_rn_gbl_env = emptyGlobalRdrEnv,
619                          ic_rn_local_env = emptyLocalRdrEnv,
620                          ic_type_env = emptyTypeEnv }
621
622 icPrintUnqual :: InteractiveContext -> PrintUnqualified
623 icPrintUnqual ictxt = mkPrintUnqualified (ic_rn_gbl_env ictxt)
624 \end{code}
625
626 %************************************************************************
627 %*                                                                      *
628         Building a PrintUnqualified             
629 %*                                                                      *
630 %************************************************************************
631
632 \begin{code}
633 mkPrintUnqualified :: GlobalRdrEnv -> PrintUnqualified
634 mkPrintUnqualified env = (qual_name, qual_mod)
635   where
636   qual_name mod occ
637         | null gres = Just (moduleName mod)
638                 -- it isn't in scope at all, this probably shouldn't happen,
639                 -- but we'll qualify it by the original module anyway.
640         | any unQualOK gres = Nothing
641         | (Imported is : _) <- map gre_prov gres, (idecl : _) <- is
642           = Just (is_as (is_decl idecl))
643         | otherwise = panic "mkPrintUnqualified" 
644       where
645         gres  = [ gre | gre <- lookupGlobalRdrEnv env occ,
646                         nameModule (gre_name gre) == mod ]
647
648   qual_mod mod = Nothing       -- For now...
649 \end{code}
650
651
652 %************************************************************************
653 %*                                                                      *
654                 TyThing
655 %*                                                                      *
656 %************************************************************************
657
658 \begin{code}
659 implicitTyThings :: TyThing -> [TyThing]
660 -- If you change this, make sure you change LoadIface.ifaceDeclSubBndrs in sync
661
662 implicitTyThings (AnId id)   = []
663
664         -- For type constructors, add the data cons (and their extras),
665         -- and the selectors and generic-programming Ids too
666         --
667         -- Newtypes don't have a worker Id, so don't generate that?
668 implicitTyThings (ATyCon tc) = implicitCoTyCon tc ++
669                                map AnId (tyConSelIds tc) ++ 
670                                concatMap (extras_plus . ADataCon) 
671                                          (tyConDataCons tc)
672                      
673         -- For classes, add the class TyCon too (and its extras)
674         -- and the class selector Ids and the associated types (they don't
675         -- have extras as these are only the family decls)
676 implicitTyThings (AClass cl) = map AnId (classSelIds cl) ++
677                                map ATyCon (classATs cl) ++
678                                extras_plus (ATyCon (classTyCon cl))
679
680         -- For data cons add the worker and wrapper (if any)
681 implicitTyThings (ADataCon dc) = map AnId (dataConImplicitIds dc)
682
683 -- | returns 'True' if there should be no interface-file declaration
684 -- for this thing on its own: either it is built-in, or it is part
685 -- of some other declaration, or it is generated implicitly by some
686 -- other declaration.
687 isImplicitTyThing :: TyThing -> Bool
688 isImplicitTyThing (ADataCon _)  = True
689 isImplicitTyThing (AnId     id) = isImplicitId id
690 isImplicitTyThing (AClass   _)  = False
691 isImplicitTyThing (ATyCon   tc) = isImplicitTyCon tc
692
693         -- For newtypes and indexed data types, add the implicit coercion tycon
694 implicitCoTyCon tc 
695   = map ATyCon . catMaybes $ [newTyConCo_maybe tc, 
696                               tyConFamilyCoercion_maybe tc]
697
698 extras_plus thing = thing : implicitTyThings thing
699
700 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
701 extendTypeEnvWithIds env ids
702   = extendNameEnvList env [(getName id, AnId id) | id <- ids]
703 \end{code}
704
705 %************************************************************************
706 %*                                                                      *
707                 TypeEnv
708 %*                                                                      *
709 %************************************************************************
710
711 \begin{code}
712 type TypeEnv = NameEnv TyThing
713
714 emptyTypeEnv    :: TypeEnv
715 typeEnvElts     :: TypeEnv -> [TyThing]
716 typeEnvClasses  :: TypeEnv -> [Class]
717 typeEnvTyCons   :: TypeEnv -> [TyCon]
718 typeEnvIds      :: TypeEnv -> [Id]
719 typeEnvDataCons :: TypeEnv -> [DataCon]
720 lookupTypeEnv   :: TypeEnv -> Name -> Maybe TyThing
721
722 emptyTypeEnv        = emptyNameEnv
723 typeEnvElts     env = nameEnvElts env
724 typeEnvClasses  env = [cl | AClass cl   <- typeEnvElts env]
725 typeEnvTyCons   env = [tc | ATyCon tc   <- typeEnvElts env] 
726 typeEnvIds      env = [id | AnId id     <- typeEnvElts env] 
727 typeEnvDataCons env = [dc | ADataCon dc <- typeEnvElts env] 
728
729 mkTypeEnv :: [TyThing] -> TypeEnv
730 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
731                 
732 lookupTypeEnv = lookupNameEnv
733
734 -- Extend the type environment
735 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
736 extendTypeEnv env thing = extendNameEnv env (getName thing) thing 
737
738 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
739 extendTypeEnvList env things = foldl extendTypeEnv env things
740 \end{code}
741
742 \begin{code}
743 lookupType :: DynFlags
744            -> HomePackageTable
745            -> PackageTypeEnv
746            -> Name
747            -> Maybe TyThing
748
749 lookupType dflags hpt pte name
750   -- in one-shot, we don't use the HPT
751   | not (isOneShot (ghcMode dflags)) && modulePackageId mod == this_pkg 
752   = do hm <- lookupUFM hpt (moduleName mod) -- Maybe monad
753        lookupNameEnv (md_types (hm_details hm)) name
754   | otherwise
755   = lookupNameEnv pte name
756   where mod = nameModule name
757         this_pkg = thisPackage dflags
758 \end{code}
759
760 \begin{code}
761 tyThingTyCon (ATyCon tc) = tc
762 tyThingTyCon other       = pprPanic "tyThingTyCon" (ppr other)
763
764 tyThingClass (AClass cls) = cls
765 tyThingClass other        = pprPanic "tyThingClass" (ppr other)
766
767 tyThingDataCon (ADataCon dc) = dc
768 tyThingDataCon other         = pprPanic "tyThingDataCon" (ppr other)
769
770 tyThingId (AnId id) = id
771 tyThingId other     = pprPanic "tyThingId" (ppr other)
772 \end{code}
773
774 %************************************************************************
775 %*                                                                      *
776 \subsection{Auxiliary types}
777 %*                                                                      *
778 %************************************************************************
779
780 These types are defined here because they are mentioned in ModDetails,
781 but they are mostly elaborated elsewhere
782
783 \begin{code}
784 mkIfaceVerCache :: [(Version,IfaceDecl)]
785                 -> (OccName -> Maybe (OccName, Version))
786 mkIfaceVerCache pairs 
787   = \occ -> lookupOccEnv env occ
788   where
789     env = foldr add_decl emptyOccEnv pairs
790     add_decl (v,d) env0 = foldr add_imp env1 (ifaceDeclSubBndrs d)
791       where
792           decl_name = ifName d
793           env1 = extendOccEnv env0 decl_name (decl_name, v)
794           add_imp bndr env = extendOccEnv env bndr (decl_name, v)
795
796 emptyIfaceVerCache :: OccName -> Maybe (OccName, Version)
797 emptyIfaceVerCache occ = Nothing
798
799 ------------------ Deprecations -------------------------
800 data Deprecs a
801   = NoDeprecs
802   | DeprecAll DeprecTxt -- Whole module deprecated
803   | DeprecSome a        -- Some specific things deprecated
804   deriving( Eq )
805
806 type IfaceDeprecs = Deprecs [(OccName,DeprecTxt)]
807 type Deprecations = Deprecs (NameEnv (OccName,DeprecTxt))
808         -- Keep the OccName so we can flatten the NameEnv to
809         -- get an IfaceDeprecs from a Deprecations
810         -- Only an OccName is needed, because a deprecation always
811         -- applies to things defined in the module in which the
812         -- deprecation appears.
813
814 mkIfaceDepCache:: IfaceDeprecs -> Name -> Maybe DeprecTxt
815 mkIfaceDepCache NoDeprecs         = \n -> Nothing
816 mkIfaceDepCache (DeprecAll t)     = \n -> Just t
817 mkIfaceDepCache (DeprecSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
818
819 emptyIfaceDepCache :: Name -> Maybe DeprecTxt
820 emptyIfaceDepCache n = Nothing
821
822 plusDeprecs :: Deprecations -> Deprecations -> Deprecations
823 plusDeprecs d NoDeprecs = d
824 plusDeprecs NoDeprecs d = d
825 plusDeprecs d (DeprecAll t) = DeprecAll t
826 plusDeprecs (DeprecAll t) d = DeprecAll t
827 plusDeprecs (DeprecSome v1) (DeprecSome v2) = DeprecSome (v1 `plusNameEnv` v2)
828 \end{code}
829
830
831 \begin{code}
832 type Avails       = [AvailInfo]
833 type AvailInfo    = GenAvailInfo Name
834 type RdrAvailInfo = GenAvailInfo OccName
835
836 data GenAvailInfo name  = Avail name     -- An ordinary identifier
837                         | AvailTC name   -- The name of the type or class
838                                   [name] -- The available pieces of type/class.
839                                          -- NB: If the type or class is itself
840                                          -- to be in scope, it must be in this list.
841                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
842                         deriving( Eq )
843                         -- Equality used when deciding if the interface has changed
844
845 type IfaceExport = (Module, [GenAvailInfo OccName])
846
847 availsToNameSet :: [AvailInfo] -> NameSet
848 availsToNameSet avails = foldr add emptyNameSet avails
849       where add avail set = addListToNameSet set (availNames avail)
850
851 availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
852 availsToNameEnv avails = foldr add emptyNameEnv avails
853      where add avail env = extendNameEnvList env
854                                 (zip (availNames avail) (repeat avail))
855
856 availName :: GenAvailInfo name -> name
857 availName (Avail n)     = n
858 availName (AvailTC n _) = n
859
860 availNames :: GenAvailInfo name -> [name]
861 availNames (Avail n)      = [n]
862 availNames (AvailTC n ns) = ns
863
864 instance Outputable n => Outputable (GenAvailInfo n) where
865    ppr = pprAvail
866
867 pprAvail :: Outputable n => GenAvailInfo n -> SDoc
868 pprAvail (Avail n)      = ppr n
869 pprAvail (AvailTC n ns) = ppr n <> braces (hsep (punctuate comma (map ppr ns)))
870 \end{code}
871
872 \begin{code}
873 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
874 mkIfaceFixCache pairs 
875   = \n -> lookupOccEnv env n `orElse` defaultFixity
876   where
877    env = mkOccEnv pairs
878
879 emptyIfaceFixCache :: OccName -> Fixity
880 emptyIfaceFixCache n = defaultFixity
881
882 -- This fixity environment is for source code only
883 type FixityEnv = NameEnv FixItem
884
885 -- We keep the OccName in the range so that we can generate an interface from it
886 data FixItem = FixItem OccName Fixity SrcSpan
887
888 instance Outputable FixItem where
889   ppr (FixItem occ fix loc) = ppr fix <+> ppr occ <+> parens (ppr loc)
890
891 emptyFixityEnv :: FixityEnv
892 emptyFixityEnv = emptyNameEnv
893
894 lookupFixity :: FixityEnv -> Name -> Fixity
895 lookupFixity env n = case lookupNameEnv env n of
896                         Just (FixItem _ fix _) -> fix
897                         Nothing                -> defaultFixity
898 \end{code}
899
900
901 %************************************************************************
902 %*                                                                      *
903 \subsection{WhatsImported}
904 %*                                                                      *
905 %************************************************************************
906
907 \begin{code}
908 type WhetherHasOrphans   = Bool
909         -- An "orphan" is 
910         --      * an instance decl in a module other than the defn module for 
911         --              one of the tycons or classes in the instance head
912         --      * a transformation rule in a module other than the one defining
913         --              the function in the head of the rule.
914
915 type WhetherHasFamInst = Bool        -- This module defines family instances?
916
917 type IsBootInterface = Bool
918
919 -- Dependency info about modules and packages below this one
920 -- in the import hierarchy.  See TcRnTypes.ImportAvails for details.
921 -- The orphan modules in `dep_orphs' do *not* include family instance orphans,
922 -- as they are anyway included in `dep_finsts'.
923 --
924 -- Invariant: the dependencies of a module M never includes M
925 -- Invariant: the lists are unordered, with no duplicates
926 data Dependencies
927   = Deps { dep_mods   :: [(ModuleName,      -- Home-package module dependencies
928                            IsBootInterface)]
929          , dep_pkgs   :: [PackageId]        -- External package dependencies
930          , dep_orphs  :: [Module]           -- Orphan modules (whether home or
931                                             -- external pkg)
932          , dep_finsts :: [Module]           -- Modules that contain family
933                                             -- instances (whether home or
934                                             -- external pkg)
935          }
936   deriving( Eq )
937         -- Equality used only for old/new comparison in MkIface.addVersionInfo
938
939 noDependencies :: Dependencies
940 noDependencies = Deps [] [] [] []
941           
942 data Usage
943   = Usage { usg_name     :: ModuleName,                 -- Name of the module
944             usg_mod      :: Version,                    -- Module version
945             usg_entities :: [(OccName,Version)],        -- Sorted by occurrence name
946                 -- NB. usages are for parent names only, eg. tycon but not constructors.
947             usg_exports  :: Maybe Version,              -- Export-list version, if we depend on it
948             usg_rules    :: Version                     -- Orphan-rules version (for non-orphan
949                                                         -- modules this will always be initialVersion)
950     }       deriving( Eq )
951         -- This type doesn't let you say "I imported f but none of the rules in
952         -- the module". If you use anything in the module you get its rule version
953         -- So if the rules change, you'll recompile, even if you don't use them.
954         -- This is easy to implement, and it's safer: you might not have used the rules last
955         -- time round, but if someone has added a new rule you might need it this time
956
957         -- The export list field is (Just v) if we depend on the export list:
958         --      i.e. we imported the module directly, whether or not we
959         --           enumerated the things we imported, or just imported everything
960         -- We need to recompile if M's exports change, because 
961         -- if the import was    import M,       we might now have a name clash in the 
962         --                                      importing module.
963         -- if the import was    import M(x)     M might no longer export x
964         -- The only way we don't depend on the export list is if we have
965         --                      import M()
966         -- And of course, for modules that aren't imported directly we don't
967         -- depend on their export lists
968 \end{code}
969
970
971 %************************************************************************
972 %*                                                                      *
973                 The External Package State
974 %*                                                                      *
975 %************************************************************************
976
977 \begin{code}
978 type PackageTypeEnv    = TypeEnv
979 type PackageRuleBase   = RuleBase
980 type PackageInstEnv    = InstEnv
981 type PackageFamInstEnv = FamInstEnv
982
983 data ExternalPackageState
984   = EPS {
985         eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
986                 -- In OneShot mode (only), home-package modules
987                 -- accumulate in the external package state, and are
988                 -- sucked in lazily.  For these home-pkg modules
989                 -- (only) we need to record which are boot modules.
990                 -- We set this field after loading all the
991                 -- explicitly-imported interfaces, but before doing
992                 -- anything else
993                 --
994                 -- The ModuleName part is not necessary, but it's useful for
995                 -- debug prints, and it's convenient because this field comes
996                 -- direct from TcRnTypes.ImportAvails.imp_dep_mods
997
998         eps_PIT :: !PackageIfaceTable,
999                 -- The ModuleIFaces for modules in external packages
1000                 -- whose interfaces we have opened
1001                 -- The declarations in these interface files are held in
1002                 -- eps_decls, eps_inst_env, eps_fam_inst_env, eps_rules
1003                 -- (below), not in the mi_decls fields of the iPIT.  
1004                 -- What _is_ in the iPIT is:
1005                 --      * The Module 
1006                 --      * Version info
1007                 --      * Its exports
1008                 --      * Fixities
1009                 --      * Deprecations
1010
1011         eps_PTE :: !PackageTypeEnv,        -- Domain = external-package modules
1012
1013         eps_inst_env     :: !PackageInstEnv,   -- The total InstEnv accumulated
1014                                                -- from all the external-package
1015                                                -- modules 
1016         eps_fam_inst_env :: !PackageFamInstEnv,-- Ditto FamInstEnv
1017         eps_rule_base    :: !PackageRuleBase,  -- Ditto RuleEnv
1018
1019         eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- identifies family
1020                                                        -- instances of each mod
1021
1022         eps_stats :: !EpsStats
1023   }
1024
1025 -- "In" means read from iface files
1026 -- "Out" means actually sucked in and type-checked
1027 data EpsStats = EpsStats { n_ifaces_in
1028                          , n_decls_in, n_decls_out 
1029                          , n_rules_in, n_rules_out
1030                          , n_insts_in, n_insts_out :: !Int }
1031
1032 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
1033 -- Add stats for one newly-read interface
1034 addEpsInStats stats n_decls n_insts n_rules
1035   = stats { n_ifaces_in = n_ifaces_in stats + 1
1036           , n_decls_in  = n_decls_in stats + n_decls
1037           , n_insts_in  = n_insts_in stats + n_insts
1038           , n_rules_in  = n_rules_in stats + n_rules }
1039 \end{code}
1040
1041 The NameCache makes sure that there is just one Unique assigned for
1042 each original name; i.e. (module-name, occ-name) pair.  The Name is
1043 always stored as a Global, and has the SrcLoc of its binding location.
1044 Actually that's not quite right.  When we first encounter the original
1045 name, we might not be at its binding site (e.g. we are reading an
1046 interface file); so we give it 'noSrcLoc' then.  Later, when we find
1047 its binding site, we fix it up.
1048
1049 \begin{code}
1050 data NameCache
1051  = NameCache {  nsUniqs :: UniqSupply,
1052                 -- Supply of uniques
1053                 nsNames :: OrigNameCache,
1054                 -- Ensures that one original name gets one unique
1055                 nsIPs   :: OrigIParamCache
1056                 -- Ensures that one implicit parameter name gets one unique
1057    }
1058
1059 type OrigNameCache   = ModuleEnv (OccEnv Name)
1060 type OrigIParamCache = FiniteMap (IPName OccName) (IPName Name)
1061 \end{code}
1062
1063
1064
1065 %************************************************************************
1066 %*                                                                      *
1067                 The module graph and ModSummary type
1068         A ModSummary is a node in the compilation manager's
1069         dependency graph, and it's also passed to hscMain
1070 %*                                                                      *
1071 %************************************************************************
1072
1073 A ModuleGraph contains all the nodes from the home package (only).  
1074 There will be a node for each source module, plus a node for each hi-boot
1075 module.
1076
1077 \begin{code}
1078 type ModuleGraph = [ModSummary]  -- The module graph, 
1079                                  -- NOT NECESSARILY IN TOPOLOGICAL ORDER
1080
1081 emptyMG :: ModuleGraph
1082 emptyMG = []
1083
1084 -- The nodes of the module graph are
1085 --      EITHER a regular Haskell source module
1086 --      OR     a hi-boot source module
1087
1088 data ModSummary
1089    = ModSummary {
1090         ms_mod       :: Module,                 -- Identity of the module
1091         ms_hsc_src   :: HscSource,              -- Source is Haskell, hs-boot, external core
1092         ms_location  :: ModLocation,            -- Location
1093         ms_hs_date   :: ClockTime,              -- Timestamp of source file
1094         ms_obj_date  :: Maybe ClockTime,        -- Timestamp of object, maybe
1095         ms_srcimps   :: [Located ModuleName],   -- Source imports
1096         ms_imps      :: [Located ModuleName],   -- Non-source imports
1097         ms_hspp_file :: FilePath,               -- Filename of preprocessed source.
1098         ms_hspp_opts :: DynFlags,               -- Cached flags from OPTIONS, INCLUDE
1099                                                 -- and LANGUAGE pragmas.
1100         ms_hspp_buf  :: Maybe StringBuffer      -- The actual preprocessed source, maybe.
1101      }
1102
1103 -- The ModLocation contains both the original source filename and the
1104 -- filename of the cleaned-up source file after all preprocessing has been
1105 -- done.  The point is that the summariser will have to cpp/unlit/whatever
1106 -- all files anyway, and there's no point in doing this twice -- just 
1107 -- park the result in a temp file, put the name of it in the location,
1108 -- and let @compile@ read from that file on the way back up.
1109
1110 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
1111 -- the ms_hs_date and imports can, of course, change
1112
1113 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
1114 msHsFilePath  ms = expectJust "msHsFilePath" (ml_hs_file  (ms_location ms))
1115 msHiFilePath  ms = ml_hi_file  (ms_location ms)
1116 msObjFilePath ms = ml_obj_file (ms_location ms)
1117
1118 isBootSummary :: ModSummary -> Bool
1119 isBootSummary ms = isHsBoot (ms_hsc_src ms)
1120
1121 instance Outputable ModSummary where
1122    ppr ms
1123       = sep [text "ModSummary {",
1124              nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1125                           text "ms_mod =" <+> ppr (ms_mod ms) 
1126                                 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
1127                           text "ms_imps =" <+> ppr (ms_imps ms),
1128                           text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1129              char '}'
1130             ]
1131
1132 showModMsg :: HscTarget -> Bool -> ModSummary -> String
1133 showModMsg target recomp mod_summary
1134   = showSDoc (hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
1135                     char '(', text (msHsFilePath mod_summary) <> comma,
1136                     case target of
1137                       HscInterpreted | recomp
1138                                  -> text "interpreted"
1139                       HscNothing -> text "nothing"
1140                       _other     -> text (msObjFilePath mod_summary),
1141                     char ')'])
1142  where 
1143     mod     = moduleName (ms_mod mod_summary)
1144     mod_str = showSDoc (ppr mod) ++ hscSourceString (ms_hsc_src mod_summary)
1145 \end{code}
1146
1147
1148 %************************************************************************
1149 %*                                                                      *
1150 \subsection{Hpc Support}
1151 %*                                                                      *
1152 %************************************************************************
1153
1154 \begin{code}
1155 type HpcInfo = Int             -- just the number of ticks in a module
1156
1157 noHpcInfo :: HpcInfo
1158 noHpcInfo = 0                  -- default = 0
1159 \end{code}
1160
1161 %************************************************************************
1162 %*                                                                      *
1163 \subsection{Linkable stuff}
1164 %*                                                                      *
1165 %************************************************************************
1166
1167 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
1168 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
1169
1170 \begin{code}
1171 data Linkable = LM {
1172   linkableTime     :: ClockTime,        -- Time at which this linkable was built
1173                                         -- (i.e. when the bytecodes were produced,
1174                                         --       or the mod date on the files)
1175   linkableModule   :: Module,           -- Should be Module, but see below
1176   linkableUnlinked :: [Unlinked]
1177  }
1178
1179 isObjectLinkable :: Linkable -> Bool
1180 isObjectLinkable l = not (null unlinked) && all isObject unlinked
1181   where unlinked = linkableUnlinked l
1182         -- A linkable with no Unlinked's is treated as a BCO.  We can
1183         -- generate a linkable with no Unlinked's as a result of
1184         -- compiling a module in HscNothing mode, and this choice
1185         -- happens to work well with checkStability in module GHC.
1186
1187 instance Outputable Linkable where
1188    ppr (LM when_made mod unlinkeds)
1189       = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
1190         $$ nest 3 (ppr unlinkeds)
1191
1192 -------------------------------------------
1193 data Unlinked
1194    = DotO FilePath
1195    | DotA FilePath
1196    | DotDLL FilePath
1197    | BCOs CompiledByteCode
1198
1199 #ifndef GHCI
1200 data CompiledByteCode = NoByteCode
1201 #endif
1202
1203 instance Outputable Unlinked where
1204    ppr (DotO path)   = text "DotO" <+> text path
1205    ppr (DotA path)   = text "DotA" <+> text path
1206    ppr (DotDLL path) = text "DotDLL" <+> text path
1207 #ifdef GHCI
1208    ppr (BCOs bcos)   = text "BCOs" <+> ppr bcos
1209 #else
1210    ppr (BCOs bcos)   = text "No byte code"
1211 #endif
1212
1213 isObject (DotO _)   = True
1214 isObject (DotA _)   = True
1215 isObject (DotDLL _) = True
1216 isObject _          = False
1217
1218 isInterpretable = not . isObject
1219
1220 nameOfObject (DotO fn)   = fn
1221 nameOfObject (DotA fn)   = fn
1222 nameOfObject (DotDLL fn) = fn
1223 nameOfObject other       = pprPanic "nameOfObject" (ppr other)
1224
1225 byteCodeOfObject (BCOs bc) = bc
1226 byteCodeOfObject other     = pprPanic "byteCodeOfObject" (ppr other)
1227 \end{code}
1228
1229
1230