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