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