9e049209f88d597bc792d2ee4c5fa392f35d1179
[ghc.git] / compiler / main / HscTypes.hs
1 {-
2 (c) The University of Glasgow, 2006
3
4 \section[HscTypes]{Types for the per-module compiler}
5 -}
6
7 {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
8
9 -- | Types for the per-module compiler
10 module HscTypes (
11 -- * compilation state
12 HscEnv(..), hscEPS,
13 FinderCache, FindResult(..),
14 Target(..), TargetId(..), pprTarget, pprTargetId,
15 ModuleGraph, emptyMG,
16 HscStatus(..),
17 #ifdef GHCI
18 IServ(..),
19 #endif
20
21 -- * Hsc monad
22 Hsc(..), runHsc, runInteractiveHsc,
23
24 -- * Information about modules
25 ModDetails(..), emptyModDetails,
26 ModGuts(..), CgGuts(..), ForeignStubs(..), appendStubC,
27 ImportedMods, ImportedModsVal(..),
28
29 ModSummary(..), ms_imps, ms_mod_name, showModMsg, isBootSummary,
30 msHsFilePath, msHiFilePath, msObjFilePath,
31 SourceModified(..),
32
33 -- * Information about the module being compiled
34 -- (re-exported from DriverPhases)
35 HscSource(..), isHsBootOrSig, hscSourceString,
36
37
38 -- * State relating to modules in this package
39 HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
40 hptInstances, hptRules, hptVectInfo, pprHPT,
41 hptObjs,
42
43 -- * State relating to known packages
44 ExternalPackageState(..), EpsStats(..), addEpsInStats,
45 PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
46 lookupIfaceByModule, emptyModIface, lookupHptByModule,
47
48 PackageInstEnv, PackageFamInstEnv, PackageRuleBase,
49
50 mkSOName, mkHsSOName, soExt,
51
52 -- * Metaprogramming
53 MetaRequest(..),
54 MetaResult, -- data constructors not exported to ensure correct response type
55 metaRequestE, metaRequestP, metaRequestT, metaRequestD, metaRequestAW,
56 MetaHook,
57
58 -- * Annotations
59 prepareAnnotations,
60
61 -- * Interactive context
62 InteractiveContext(..), emptyInteractiveContext,
63 icPrintUnqual, icInScopeTTs, icExtendGblRdrEnv,
64 extendInteractiveContext, extendInteractiveContextWithIds,
65 substInteractiveContext,
66 setInteractivePrintName, icInteractiveModule,
67 InteractiveImport(..), setInteractivePackage,
68 mkPrintUnqualified, pprModulePrefix,
69 mkQualPackage, mkQualModule, pkgQual,
70
71 -- * Interfaces
72 ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
73 emptyIfaceWarnCache, mi_boot,
74
75 -- * Fixity
76 FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
77
78 -- * TyThings and type environments
79 TyThing(..), tyThingAvailInfo,
80 tyThingTyCon, tyThingDataCon,
81 tyThingId, tyThingCoAxiom, tyThingParent_maybe, tyThingsTyCoVars,
82 implicitTyThings, implicitTyConThings, implicitClassThings,
83 isImplicitTyThing,
84
85 TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
86 typeEnvFromEntities, mkTypeEnvWithImplicits,
87 extendTypeEnv, extendTypeEnvList,
88 extendTypeEnvWithIds,
89 lookupTypeEnv,
90 typeEnvElts, typeEnvTyCons, typeEnvIds, typeEnvPatSyns,
91 typeEnvDataCons, typeEnvCoAxioms, typeEnvClasses,
92
93 -- * MonadThings
94 MonadThings(..),
95
96 -- * Information on imports and exports
97 WhetherHasOrphans, IsBootInterface, Usage(..),
98 Dependencies(..), noDependencies,
99 NameCache(..), OrigNameCache, updNameCacheIO,
100 IfaceExport,
101
102 -- * Warnings
103 Warnings(..), WarningTxt(..), plusWarns,
104
105 -- * Linker stuff
106 Linkable(..), isObjectLinkable, linkableObjs,
107 Unlinked(..), CompiledByteCode,
108 isObject, nameOfObject, isInterpretable, byteCodeOfObject,
109
110 -- * Program coverage
111 HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
112
113 -- * Breakpoints
114 ModBreaks (..), emptyModBreaks,
115
116 -- * Vectorisation information
117 VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
118 noIfaceVectInfo, isNoIfaceVectInfo,
119
120 -- * Safe Haskell information
121 IfaceTrustInfo, getSafeMode, setSafeMode, noIfaceTrustInfo,
122 trustInfoToNum, numToTrustInfo, IsSafeImport,
123
124 -- * result of the parser
125 HsParsedModule(..),
126
127 -- * Compilation errors and warnings
128 SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
129 throwOneError, handleSourceError,
130 handleFlagWarnings, printOrThrowWarnings,
131 ) where
132
133 #include "HsVersions.h"
134
135 #ifdef GHCI
136 import ByteCodeTypes
137 import InteractiveEvalTypes ( Resume )
138 import GHCi.Message ( Pipe )
139 import GHCi.RemoteTypes
140 #endif
141
142 import HsSyn
143 import RdrName
144 import Avail
145 import Module
146 import InstEnv ( InstEnv, ClsInst, identicalClsInstHead )
147 import FamInstEnv
148 import CoreSyn ( CoreProgram, RuleBase )
149 import Name
150 import NameEnv
151 import NameSet
152 import VarEnv
153 import VarSet
154 import Var
155 import Id
156 import IdInfo ( IdDetails(..), RecSelParent(..))
157 import Type
158
159 import ApiAnnotation ( ApiAnns )
160 import Annotations ( Annotation, AnnEnv, mkAnnEnv, plusAnnEnv )
161 import Class
162 import TyCon
163 import CoAxiom
164 import ConLike
165 import DataCon
166 import PatSyn
167 import PrelNames ( gHC_PRIM, ioTyConName, printName, mkInteractiveModule
168 , eqTyConName )
169 import TysWiredIn
170 import Packages hiding ( Version(..) )
171 import DynFlags
172 import DriverPhases ( Phase, HscSource(..), isHsBootOrSig, hscSourceString )
173 import BasicTypes
174 import IfaceSyn
175 import CoreSyn ( CoreRule, CoreVect )
176 import Maybes
177 import Outputable
178 import SrcLoc
179 -- import Unique
180 import UniqFM
181 import UniqSupply
182 import FastString
183 import StringBuffer ( StringBuffer )
184 import Fingerprint
185 import MonadUtils
186 import Bag
187 import Binary
188 import ErrUtils
189 import Platform
190 import Util
191 import GHC.Serialized ( Serialized )
192
193 import Foreign
194 import Control.Monad ( guard, liftM, when, ap )
195 import Control.Concurrent
196 import Data.IORef
197 import Data.Time
198 import Data.Typeable ( Typeable )
199 import Exception
200 import System.FilePath
201 import System.Process ( ProcessHandle )
202
203 -- -----------------------------------------------------------------------------
204 -- Compilation state
205 -- -----------------------------------------------------------------------------
206
207 -- | Status of a compilation to hard-code
208 data HscStatus
209 = HscNotGeneratingCode
210 | HscUpToDate
211 | HscUpdateBoot
212 | HscUpdateSig
213 | HscRecomp CgGuts ModSummary
214
215 -- -----------------------------------------------------------------------------
216 -- The Hsc monad: Passing an environment and warning state
217
218 newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
219
220 instance Functor Hsc where
221 fmap = liftM
222
223 instance Applicative Hsc where
224 pure a = Hsc $ \_ w -> return (a, w)
225 (<*>) = ap
226
227 instance Monad Hsc where
228 Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
229 case k a of
230 Hsc k' -> k' e w1
231
232 instance MonadIO Hsc where
233 liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
234
235 instance HasDynFlags Hsc where
236 getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
237
238 runHsc :: HscEnv -> Hsc a -> IO a
239 runHsc hsc_env (Hsc hsc) = do
240 (a, w) <- hsc hsc_env emptyBag
241 printOrThrowWarnings (hsc_dflags hsc_env) w
242 return a
243
244 runInteractiveHsc :: HscEnv -> Hsc a -> IO a
245 -- A variant of runHsc that switches in the DynFlags from the
246 -- InteractiveContext before running the Hsc computation.
247 runInteractiveHsc hsc_env
248 = runHsc (hsc_env { hsc_dflags = interactive_dflags })
249 where
250 interactive_dflags = ic_dflags (hsc_IC hsc_env)
251
252 -- -----------------------------------------------------------------------------
253 -- Source Errors
254
255 -- When the compiler (HscMain) discovers errors, it throws an
256 -- exception in the IO monad.
257
258 mkSrcErr :: ErrorMessages -> SourceError
259 mkSrcErr = SourceError
260
261 srcErrorMessages :: SourceError -> ErrorMessages
262 srcErrorMessages (SourceError msgs) = msgs
263
264 mkApiErr :: DynFlags -> SDoc -> GhcApiError
265 mkApiErr dflags msg = GhcApiError (showSDoc dflags msg)
266
267 throwOneError :: MonadIO m => ErrMsg -> m ab
268 throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
269
270 -- | A source error is an error that is caused by one or more errors in the
271 -- source code. A 'SourceError' is thrown by many functions in the
272 -- compilation pipeline. Inside GHC these errors are merely printed via
273 -- 'log_action', but API clients may treat them differently, for example,
274 -- insert them into a list box. If you want the default behaviour, use the
275 -- idiom:
276 --
277 -- > handleSourceError printExceptionAndWarnings $ do
278 -- > ... api calls that may fail ...
279 --
280 -- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
281 -- This list may be empty if the compiler failed due to @-Werror@
282 -- ('Opt_WarnIsError').
283 --
284 -- See 'printExceptionAndWarnings' for more information on what to take care
285 -- of when writing a custom error handler.
286 newtype SourceError = SourceError ErrorMessages
287 deriving Typeable
288
289 instance Show SourceError where
290 show (SourceError msgs) = unlines . map show . bagToList $ msgs
291
292 instance Exception SourceError
293
294 -- | Perform the given action and call the exception handler if the action
295 -- throws a 'SourceError'. See 'SourceError' for more information.
296 handleSourceError :: (ExceptionMonad m) =>
297 (SourceError -> m a) -- ^ exception handler
298 -> m a -- ^ action to perform
299 -> m a
300 handleSourceError handler act =
301 gcatch act (\(e :: SourceError) -> handler e)
302
303 -- | An error thrown if the GHC API is used in an incorrect fashion.
304 newtype GhcApiError = GhcApiError String
305 deriving Typeable
306
307 instance Show GhcApiError where
308 show (GhcApiError msg) = msg
309
310 instance Exception GhcApiError
311
312 -- | Given a bag of warnings, turn them into an exception if
313 -- -Werror is enabled, or print them out otherwise.
314 printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO ()
315 printOrThrowWarnings dflags warns
316 | gopt Opt_WarnIsError dflags
317 = when (not (isEmptyBag warns)) $ do
318 throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg dflags
319 | otherwise
320 = printBagOfErrors dflags warns
321
322 handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
323 handleFlagWarnings dflags warns
324 = when (wopt Opt_WarnDeprecatedFlags dflags) $ do
325 -- It would be nicer if warns :: [Located MsgDoc], but that
326 -- has circular import problems.
327 let bag = listToBag [ mkPlainWarnMsg dflags loc (text warn)
328 | L loc warn <- warns ]
329
330 printOrThrowWarnings dflags bag
331
332 {-
333 ************************************************************************
334 * *
335 \subsection{HscEnv}
336 * *
337 ************************************************************************
338 -}
339
340 -- | HscEnv is like 'Session', except that some of the fields are immutable.
341 -- An HscEnv is used to compile a single module from plain Haskell source
342 -- code (after preprocessing) to either C, assembly or C--. Things like
343 -- the module graph don't change during a single compilation.
344 --
345 -- Historical note: \"hsc\" used to be the name of the compiler binary,
346 -- when there was a separate driver and compiler. To compile a single
347 -- module, the driver would invoke hsc on the source code... so nowadays
348 -- we think of hsc as the layer of the compiler that deals with compiling
349 -- a single module.
350 data HscEnv
351 = HscEnv {
352 hsc_dflags :: DynFlags,
353 -- ^ The dynamic flag settings
354
355 hsc_targets :: [Target],
356 -- ^ The targets (or roots) of the current session
357
358 hsc_mod_graph :: ModuleGraph,
359 -- ^ The module graph of the current session
360
361 hsc_IC :: InteractiveContext,
362 -- ^ The context for evaluating interactive statements
363
364 hsc_HPT :: HomePackageTable,
365 -- ^ The home package table describes already-compiled
366 -- home-package modules, /excluding/ the module we
367 -- are compiling right now.
368 -- (In one-shot mode the current module is the only
369 -- home-package module, so hsc_HPT is empty. All other
370 -- modules count as \"external-package\" modules.
371 -- However, even in GHCi mode, hi-boot interfaces are
372 -- demand-loaded into the external-package table.)
373 --
374 -- 'hsc_HPT' is not mutable because we only demand-load
375 -- external packages; the home package is eagerly
376 -- loaded, module by module, by the compilation manager.
377 --
378 -- The HPT may contain modules compiled earlier by @--make@
379 -- but not actually below the current module in the dependency
380 -- graph.
381 --
382 -- (This changes a previous invariant: changed Jan 05.)
383
384 hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
385 -- ^ Information about the currently loaded external packages.
386 -- This is mutable because packages will be demand-loaded during
387 -- a compilation run as required.
388
389 hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
390 -- ^ As with 'hsc_EPS', this is side-effected by compiling to
391 -- reflect sucking in interface files. They cache the state of
392 -- external interface files, in effect.
393
394 hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
395 -- ^ The cached result of performing finding in the file system
396
397 hsc_type_env_var :: Maybe (Module, IORef TypeEnv)
398 -- ^ Used for one-shot compilation only, to initialise
399 -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
400 -- 'TcRunTypes.TcGblEnv'
401
402 #ifdef GHCI
403 , hsc_iserv :: MVar (Maybe IServ)
404 -- ^ interactive server process. Created the first
405 -- time it is needed.
406 #endif
407 }
408
409 instance ContainsDynFlags HscEnv where
410 extractDynFlags env = hsc_dflags env
411 replaceDynFlags env dflags = env {hsc_dflags = dflags}
412
413 #ifdef GHCI
414 data IServ = IServ
415 { iservPipe :: Pipe
416 , iservProcess :: ProcessHandle
417 , iservLookupSymbolCache :: IORef (UniqFM (Ptr ()))
418 , iservPendingFrees :: [HValueRef]
419 }
420 #endif
421
422 -- | Retrieve the ExternalPackageState cache.
423 hscEPS :: HscEnv -> IO ExternalPackageState
424 hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
425
426 -- | A compilation target.
427 --
428 -- A target may be supplied with the actual text of the
429 -- module. If so, use this instead of the file contents (this
430 -- is for use in an IDE where the file hasn't been saved by
431 -- the user yet).
432 data Target
433 = Target {
434 targetId :: TargetId, -- ^ module or filename
435 targetAllowObjCode :: Bool, -- ^ object code allowed?
436 targetContents :: Maybe (StringBuffer,UTCTime)
437 -- ^ in-memory text buffer?
438 }
439
440 data TargetId
441 = TargetModule ModuleName
442 -- ^ A module name: search for the file
443 | TargetFile FilePath (Maybe Phase)
444 -- ^ A filename: preprocess & parse it to find the module name.
445 -- If specified, the Phase indicates how to compile this file
446 -- (which phase to start from). Nothing indicates the starting phase
447 -- should be determined from the suffix of the filename.
448 deriving Eq
449
450 pprTarget :: Target -> SDoc
451 pprTarget (Target id obj _) =
452 (if obj then char '*' else empty) <> pprTargetId id
453
454 instance Outputable Target where
455 ppr = pprTarget
456
457 pprTargetId :: TargetId -> SDoc
458 pprTargetId (TargetModule m) = ppr m
459 pprTargetId (TargetFile f _) = text f
460
461 instance Outputable TargetId where
462 ppr = pprTargetId
463
464 {-
465 ************************************************************************
466 * *
467 \subsection{Package and Module Tables}
468 * *
469 ************************************************************************
470 -}
471
472 -- | Helps us find information about modules in the home package
473 type HomePackageTable = ModuleNameEnv HomeModInfo
474 -- Domain = modules in the home package that have been fully compiled
475 -- "home" unit id cached here for convenience
476
477 -- | Helps us find information about modules in the imported packages
478 type PackageIfaceTable = ModuleEnv ModIface
479 -- Domain = modules in the imported packages
480
481 -- | Constructs an empty HomePackageTable
482 emptyHomePackageTable :: HomePackageTable
483 emptyHomePackageTable = emptyUFM
484
485 -- | Constructs an empty PackageIfaceTable
486 emptyPackageIfaceTable :: PackageIfaceTable
487 emptyPackageIfaceTable = emptyModuleEnv
488
489 pprHPT :: HomePackageTable -> SDoc
490 -- A bit aribitrary for now
491 pprHPT hpt
492 = vcat [ hang (ppr (mi_module (hm_iface hm)))
493 2 (ppr (md_types (hm_details hm)))
494 | hm <- eltsUFM hpt ]
495
496 lookupHptByModule :: HomePackageTable -> Module -> Maybe HomeModInfo
497 -- The HPT is indexed by ModuleName, not Module,
498 -- we must check for a hit on the right Module
499 lookupHptByModule hpt mod
500 = case lookupUFM hpt (moduleName mod) of
501 Just hm | mi_module (hm_iface hm) == mod -> Just hm
502 _otherwise -> Nothing
503
504 -- | Information about modules in the package being compiled
505 data HomeModInfo
506 = HomeModInfo {
507 hm_iface :: !ModIface,
508 -- ^ The basic loaded interface file: every loaded module has one of
509 -- these, even if it is imported from another package
510 hm_details :: !ModDetails,
511 -- ^ Extra information that has been created from the 'ModIface' for
512 -- the module, typically during typechecking
513 hm_linkable :: !(Maybe Linkable)
514 -- ^ The actual artifact we would like to link to access things in
515 -- this module.
516 --
517 -- 'hm_linkable' might be Nothing:
518 --
519 -- 1. If this is an .hs-boot module
520 --
521 -- 2. Temporarily during compilation if we pruned away
522 -- the old linkable because it was out of date.
523 --
524 -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
525 -- in the 'HomePackageTable' will be @Just@.
526 --
527 -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
528 -- 'HomeModInfo' by building a new 'ModDetails' from the old
529 -- 'ModIface' (only).
530 }
531
532 -- | Find the 'ModIface' for a 'Module', searching in both the loaded home
533 -- and external package module information
534 lookupIfaceByModule
535 :: DynFlags
536 -> HomePackageTable
537 -> PackageIfaceTable
538 -> Module
539 -> Maybe ModIface
540 lookupIfaceByModule _dflags hpt pit mod
541 = case lookupHptByModule hpt mod of
542 Just hm -> Just (hm_iface hm)
543 Nothing -> lookupModuleEnv pit mod
544
545 -- If the module does come from the home package, why do we look in the PIT as well?
546 -- (a) In OneShot mode, even home-package modules accumulate in the PIT
547 -- (b) Even in Batch (--make) mode, there is *one* case where a home-package
548 -- module is in the PIT, namely GHC.Prim when compiling the base package.
549 -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
550 -- of its own, but it doesn't seem worth the bother.
551
552
553 -- | Find all the instance declarations (of classes and families) from
554 -- the Home Package Table filtered by the provided predicate function.
555 -- Used in @tcRnImports@, to select the instances that are in the
556 -- transitive closure of imports from the currently compiled module.
557 hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([ClsInst], [FamInst])
558 hptInstances hsc_env want_this_module
559 = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
560 guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
561 let details = hm_details mod_info
562 return (md_insts details, md_fam_insts details)
563 in (concat insts, concat famInsts)
564
565 -- | Get the combined VectInfo of all modules in the home package table. In
566 -- contrast to instances and rules, we don't care whether the modules are
567 -- "below" us in the dependency sense. The VectInfo of those modules not "below"
568 -- us does not affect the compilation of the current module.
569 hptVectInfo :: HscEnv -> VectInfo
570 hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
571
572 -- | Get rules from modules "below" this one (in the dependency sense)
573 hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
574 hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
575
576
577 -- | Get annotations from modules "below" this one (in the dependency sense)
578 hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
579 hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
580 hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
581
582 hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
583 hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))
584
585 -- | Get things from modules "below" this one (in the dependency sense)
586 -- C.f Inst.hptInstances
587 hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
588 hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
589 | isOneShot (ghcMode (hsc_dflags hsc_env)) = []
590
591 | otherwise
592 = let hpt = hsc_HPT hsc_env
593 in
594 [ thing
595 | -- Find each non-hi-boot module below me
596 (mod, is_boot_mod) <- deps
597 , include_hi_boot || not is_boot_mod
598
599 -- unsavoury: when compiling the base package with --make, we
600 -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
601 -- be in the HPT, because we never compile it; it's in the EPT
602 -- instead. ToDo: clean up, and remove this slightly bogus filter:
603 , mod /= moduleName gHC_PRIM
604
605 -- Look it up in the HPT
606 , let things = case lookupUFM hpt mod of
607 Just info -> extract info
608 Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
609 msg = vcat [ptext (sLit "missing module") <+> ppr mod,
610 ptext (sLit "Probable cause: out-of-date interface files")]
611 -- This really shouldn't happen, but see Trac #962
612
613 -- And get its dfuns
614 , thing <- things ]
615
616 hptObjs :: HomePackageTable -> [FilePath]
617 hptObjs hpt = concat (map (maybe [] linkableObjs . hm_linkable) (eltsUFM hpt))
618
619 {-
620 ************************************************************************
621 * *
622 \subsection{Metaprogramming}
623 * *
624 ************************************************************************
625 -}
626
627 -- | The supported metaprogramming result types
628 data MetaRequest
629 = MetaE (LHsExpr RdrName -> MetaResult)
630 | MetaP (LPat RdrName -> MetaResult)
631 | MetaT (LHsType RdrName -> MetaResult)
632 | MetaD ([LHsDecl RdrName] -> MetaResult)
633 | MetaAW (Serialized -> MetaResult)
634
635 -- | data constructors not exported to ensure correct result type
636 data MetaResult
637 = MetaResE { unMetaResE :: LHsExpr RdrName }
638 | MetaResP { unMetaResP :: LPat RdrName }
639 | MetaResT { unMetaResT :: LHsType RdrName }
640 | MetaResD { unMetaResD :: [LHsDecl RdrName] }
641 | MetaResAW { unMetaResAW :: Serialized }
642
643 type MetaHook f = MetaRequest -> LHsExpr Id -> f MetaResult
644
645 metaRequestE :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsExpr RdrName)
646 metaRequestE h = fmap unMetaResE . h (MetaE MetaResE)
647
648 metaRequestP :: Functor f => MetaHook f -> LHsExpr Id -> f (LPat RdrName)
649 metaRequestP h = fmap unMetaResP . h (MetaP MetaResP)
650
651 metaRequestT :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsType RdrName)
652 metaRequestT h = fmap unMetaResT . h (MetaT MetaResT)
653
654 metaRequestD :: Functor f => MetaHook f -> LHsExpr Id -> f [LHsDecl RdrName]
655 metaRequestD h = fmap unMetaResD . h (MetaD MetaResD)
656
657 metaRequestAW :: Functor f => MetaHook f -> LHsExpr Id -> f Serialized
658 metaRequestAW h = fmap unMetaResAW . h (MetaAW MetaResAW)
659
660 {-
661 ************************************************************************
662 * *
663 \subsection{Dealing with Annotations}
664 * *
665 ************************************************************************
666 -}
667
668 -- | Deal with gathering annotations in from all possible places
669 -- and combining them into a single 'AnnEnv'
670 prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
671 prepareAnnotations hsc_env mb_guts = do
672 eps <- hscEPS hsc_env
673 let -- Extract annotations from the module being compiled if supplied one
674 mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
675 -- Extract dependencies of the module if we are supplied one,
676 -- otherwise load annotations from all home package table
677 -- entries regardless of dependency ordering.
678 home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
679 other_pkg_anns = eps_ann_env eps
680 ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
681 Just home_pkg_anns,
682 Just other_pkg_anns]
683 return ann_env
684
685 {-
686 ************************************************************************
687 * *
688 \subsection{The Finder cache}
689 * *
690 ************************************************************************
691 -}
692
693 -- | The 'FinderCache' maps modules to the result of
694 -- searching for that module. It records the results of searching for
695 -- modules along the search path. On @:load@, we flush the entire
696 -- contents of this cache.
697 --
698 -- Although the @FinderCache@ range is 'FindResult' for convenience,
699 -- in fact it will only ever contain 'Found' or 'NotFound' entries.
700 --
701 type FinderCache = ModuleEnv FindResult
702
703 -- | The result of searching for an imported module.
704 data FindResult
705 = Found ModLocation Module
706 -- ^ The module was found
707 | NoPackage UnitId
708 -- ^ The requested package was not found
709 | FoundMultiple [(Module, ModuleOrigin)]
710 -- ^ _Error_: both in multiple packages
711
712 -- | Not found
713 | NotFound
714 { fr_paths :: [FilePath] -- Places where I looked
715
716 , fr_pkg :: Maybe UnitId -- Just p => module is in this package's
717 -- manifest, but couldn't find
718 -- the .hi file
719
720 , fr_mods_hidden :: [UnitId] -- Module is in these packages,
721 -- but the *module* is hidden
722
723 , fr_pkgs_hidden :: [UnitId] -- Module is in these packages,
724 -- but the *package* is hidden
725
726 , fr_suggestions :: [ModuleSuggestion] -- Possible mis-spelled modules
727 }
728
729 {-
730 ************************************************************************
731 * *
732 \subsection{Symbol tables and Module details}
733 * *
734 ************************************************************************
735 -}
736
737 -- | A 'ModIface' plus a 'ModDetails' summarises everything we know
738 -- about a compiled module. The 'ModIface' is the stuff *before* linking,
739 -- and can be written out to an interface file. The 'ModDetails is after
740 -- linking and can be completely recovered from just the 'ModIface'.
741 --
742 -- When we read an interface file, we also construct a 'ModIface' from it,
743 -- except that we explicitly make the 'mi_decls' and a few other fields empty;
744 -- as when reading we consolidate the declarations etc. into a number of indexed
745 -- maps and environments in the 'ExternalPackageState'.
746 data ModIface
747 = ModIface {
748 mi_module :: !Module, -- ^ Name of the module we are for
749 mi_sig_of :: !(Maybe Module), -- ^ Are we a sig of another mod?
750 mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
751 mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
752 mi_flag_hash :: !Fingerprint, -- ^ Hash of the important flags
753 -- used when compiling this module
754
755 mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
756 mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
757 mi_hsc_src :: !HscSource, -- ^ Boot? Signature?
758
759 mi_deps :: Dependencies,
760 -- ^ The dependencies of the module. This is
761 -- consulted for directly-imported modules, but not
762 -- for anything else (hence lazy)
763
764 mi_usages :: [Usage],
765 -- ^ Usages; kept sorted so that it's easy to decide
766 -- whether to write a new iface file (changing usages
767 -- doesn't affect the hash of this module)
768 -- NOT STRICT! we read this field lazily from the interface file
769 -- It is *only* consulted by the recompilation checker
770
771 mi_exports :: ![IfaceExport],
772 -- ^ Exports
773 -- Kept sorted by (mod,occ), to make version comparisons easier
774 -- Records the modules that are the declaration points for things
775 -- exported by this module, and the 'OccName's of those things
776
777 mi_exp_hash :: !Fingerprint,
778 -- ^ Hash of export list
779
780 mi_used_th :: !Bool,
781 -- ^ Module required TH splices when it was compiled.
782 -- This disables recompilation avoidance (see #481).
783
784 mi_fixities :: [(OccName,Fixity)],
785 -- ^ Fixities
786 -- NOT STRICT! we read this field lazily from the interface file
787
788 mi_warns :: Warnings,
789 -- ^ Warnings
790 -- NOT STRICT! we read this field lazily from the interface file
791
792 mi_anns :: [IfaceAnnotation],
793 -- ^ Annotations
794 -- NOT STRICT! we read this field lazily from the interface file
795
796
797 mi_decls :: [(Fingerprint,IfaceDecl)],
798 -- ^ Type, class and variable declarations
799 -- The hash of an Id changes if its fixity or deprecations change
800 -- (as well as its type of course)
801 -- Ditto data constructors, class operations, except that
802 -- the hash of the parent class/tycon changes
803
804 mi_globals :: !(Maybe GlobalRdrEnv),
805 -- ^ Binds all the things defined at the top level in
806 -- the /original source/ code for this module. which
807 -- is NOT the same as mi_exports, nor mi_decls (which
808 -- may contains declarations for things not actually
809 -- defined by the user). Used for GHCi and for inspecting
810 -- the contents of modules via the GHC API only.
811 --
812 -- (We need the source file to figure out the
813 -- top-level environment, if we didn't compile this module
814 -- from source then this field contains @Nothing@).
815 --
816 -- Strictly speaking this field should live in the
817 -- 'HomeModInfo', but that leads to more plumbing.
818
819 -- Instance declarations and rules
820 mi_insts :: [IfaceClsInst], -- ^ Sorted class instance
821 mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
822 mi_rules :: [IfaceRule], -- ^ Sorted rules
823 mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules, class and family
824 -- instances, and vectorise pragmas combined
825
826 mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
827
828 -- Cached environments for easy lookup
829 -- These are computed (lazily) from other fields
830 -- and are not put into the interface file
831 mi_warn_fn :: OccName -> Maybe WarningTxt,
832 -- ^ Cached lookup for 'mi_warns'
833 mi_fix_fn :: OccName -> Fixity,
834 -- ^ Cached lookup for 'mi_fixities'
835 mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
836 -- ^ Cached lookup for 'mi_decls'.
837 -- The @Nothing@ in 'mi_hash_fn' means that the thing
838 -- isn't in decls. It's useful to know that when
839 -- seeing if we are up to date wrt. the old interface.
840 -- The 'OccName' is the parent of the name, if it has one.
841
842 mi_hpc :: !AnyHpcUsage,
843 -- ^ True if this program uses Hpc at any point in the program.
844
845 mi_trust :: !IfaceTrustInfo,
846 -- ^ Safe Haskell Trust information for this module.
847
848 mi_trust_pkg :: !Bool
849 -- ^ Do we require the package this module resides in be trusted
850 -- to trust this module? This is used for the situation where a
851 -- module is Safe (so doesn't require the package be trusted
852 -- itself) but imports some trustworthy modules from its own
853 -- package (which does require its own package be trusted).
854 -- See Note [RnNames . Trust Own Package]
855 }
856
857 -- | Old-style accessor for whether or not the ModIface came from an hs-boot
858 -- file.
859 mi_boot :: ModIface -> Bool
860 mi_boot iface = mi_hsc_src iface == HsBootFile
861
862 instance Binary ModIface where
863 put_ bh (ModIface {
864 mi_module = mod,
865 mi_sig_of = sig_of,
866 mi_hsc_src = hsc_src,
867 mi_iface_hash= iface_hash,
868 mi_mod_hash = mod_hash,
869 mi_flag_hash = flag_hash,
870 mi_orphan = orphan,
871 mi_finsts = hasFamInsts,
872 mi_deps = deps,
873 mi_usages = usages,
874 mi_exports = exports,
875 mi_exp_hash = exp_hash,
876 mi_used_th = used_th,
877 mi_fixities = fixities,
878 mi_warns = warns,
879 mi_anns = anns,
880 mi_decls = decls,
881 mi_insts = insts,
882 mi_fam_insts = fam_insts,
883 mi_rules = rules,
884 mi_orphan_hash = orphan_hash,
885 mi_vect_info = vect_info,
886 mi_hpc = hpc_info,
887 mi_trust = trust,
888 mi_trust_pkg = trust_pkg }) = do
889 put_ bh mod
890 put_ bh hsc_src
891 put_ bh iface_hash
892 put_ bh mod_hash
893 put_ bh flag_hash
894 put_ bh orphan
895 put_ bh hasFamInsts
896 lazyPut bh deps
897 lazyPut bh usages
898 put_ bh exports
899 put_ bh exp_hash
900 put_ bh used_th
901 put_ bh fixities
902 lazyPut bh warns
903 lazyPut bh anns
904 put_ bh decls
905 put_ bh insts
906 put_ bh fam_insts
907 lazyPut bh rules
908 put_ bh orphan_hash
909 put_ bh vect_info
910 put_ bh hpc_info
911 put_ bh trust
912 put_ bh trust_pkg
913 put_ bh sig_of
914
915 get bh = do
916 mod_name <- get bh
917 hsc_src <- get bh
918 iface_hash <- get bh
919 mod_hash <- get bh
920 flag_hash <- get bh
921 orphan <- get bh
922 hasFamInsts <- get bh
923 deps <- lazyGet bh
924 usages <- {-# SCC "bin_usages" #-} lazyGet bh
925 exports <- {-# SCC "bin_exports" #-} get bh
926 exp_hash <- get bh
927 used_th <- get bh
928 fixities <- {-# SCC "bin_fixities" #-} get bh
929 warns <- {-# SCC "bin_warns" #-} lazyGet bh
930 anns <- {-# SCC "bin_anns" #-} lazyGet bh
931 decls <- {-# SCC "bin_tycldecls" #-} get bh
932 insts <- {-# SCC "bin_insts" #-} get bh
933 fam_insts <- {-# SCC "bin_fam_insts" #-} get bh
934 rules <- {-# SCC "bin_rules" #-} lazyGet bh
935 orphan_hash <- get bh
936 vect_info <- get bh
937 hpc_info <- get bh
938 trust <- get bh
939 trust_pkg <- get bh
940 sig_of <- get bh
941 return (ModIface {
942 mi_module = mod_name,
943 mi_sig_of = sig_of,
944 mi_hsc_src = hsc_src,
945 mi_iface_hash = iface_hash,
946 mi_mod_hash = mod_hash,
947 mi_flag_hash = flag_hash,
948 mi_orphan = orphan,
949 mi_finsts = hasFamInsts,
950 mi_deps = deps,
951 mi_usages = usages,
952 mi_exports = exports,
953 mi_exp_hash = exp_hash,
954 mi_used_th = used_th,
955 mi_anns = anns,
956 mi_fixities = fixities,
957 mi_warns = warns,
958 mi_decls = decls,
959 mi_globals = Nothing,
960 mi_insts = insts,
961 mi_fam_insts = fam_insts,
962 mi_rules = rules,
963 mi_orphan_hash = orphan_hash,
964 mi_vect_info = vect_info,
965 mi_hpc = hpc_info,
966 mi_trust = trust,
967 mi_trust_pkg = trust_pkg,
968 -- And build the cached values
969 mi_warn_fn = mkIfaceWarnCache warns,
970 mi_fix_fn = mkIfaceFixCache fixities,
971 mi_hash_fn = mkIfaceHashCache decls })
972
973 -- | The original names declared of a certain module that are exported
974 type IfaceExport = AvailInfo
975
976 -- | Constructs an empty ModIface
977 emptyModIface :: Module -> ModIface
978 emptyModIface mod
979 = ModIface { mi_module = mod,
980 mi_sig_of = Nothing,
981 mi_iface_hash = fingerprint0,
982 mi_mod_hash = fingerprint0,
983 mi_flag_hash = fingerprint0,
984 mi_orphan = False,
985 mi_finsts = False,
986 mi_hsc_src = HsSrcFile,
987 mi_deps = noDependencies,
988 mi_usages = [],
989 mi_exports = [],
990 mi_exp_hash = fingerprint0,
991 mi_used_th = False,
992 mi_fixities = [],
993 mi_warns = NoWarnings,
994 mi_anns = [],
995 mi_insts = [],
996 mi_fam_insts = [],
997 mi_rules = [],
998 mi_decls = [],
999 mi_globals = Nothing,
1000 mi_orphan_hash = fingerprint0,
1001 mi_vect_info = noIfaceVectInfo,
1002 mi_warn_fn = emptyIfaceWarnCache,
1003 mi_fix_fn = emptyIfaceFixCache,
1004 mi_hash_fn = emptyIfaceHashCache,
1005 mi_hpc = False,
1006 mi_trust = noIfaceTrustInfo,
1007 mi_trust_pkg = False }
1008
1009
1010 -- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
1011 mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
1012 -> (OccName -> Maybe (OccName, Fingerprint))
1013 mkIfaceHashCache pairs
1014 = \occ -> lookupOccEnv env occ
1015 where
1016 env = foldr add_decl emptyOccEnv pairs
1017 add_decl (v,d) env0 = foldr add env0 (ifaceDeclFingerprints v d)
1018 where
1019 add (occ,hash) env0 = extendOccEnv env0 occ (occ,hash)
1020
1021 emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
1022 emptyIfaceHashCache _occ = Nothing
1023
1024
1025 -- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
1026 -- for home modules only. Information relating to packages will be loaded into
1027 -- global environments in 'ExternalPackageState'.
1028 data ModDetails
1029 = ModDetails {
1030 -- The next two fields are created by the typechecker
1031 md_exports :: [AvailInfo],
1032 md_types :: !TypeEnv, -- ^ Local type environment for this particular module
1033 -- Includes Ids, TyCons, PatSyns
1034 md_insts :: ![ClsInst], -- ^ 'DFunId's for the instances in this module
1035 md_fam_insts :: ![FamInst],
1036 md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
1037 md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
1038 -- they only annotate things also declared in this module
1039 md_vect_info :: !VectInfo -- ^ Module vectorisation information
1040 }
1041
1042 -- | Constructs an empty ModDetails
1043 emptyModDetails :: ModDetails
1044 emptyModDetails
1045 = ModDetails { md_types = emptyTypeEnv,
1046 md_exports = [],
1047 md_insts = [],
1048 md_rules = [],
1049 md_fam_insts = [],
1050 md_anns = [],
1051 md_vect_info = noVectInfo }
1052
1053 -- | Records the modules directly imported by a module for extracting e.g.
1054 -- usage information, and also to give better error message
1055 type ImportedMods = ModuleEnv [ImportedModsVal]
1056 data ImportedModsVal
1057 = ImportedModsVal {
1058 imv_name :: ModuleName, -- ^ The name the module is imported with
1059 imv_span :: SrcSpan, -- ^ the source span of the whole import
1060 imv_is_safe :: IsSafeImport, -- ^ whether this is a safe import
1061 imv_is_hiding :: Bool, -- ^ whether this is an "hiding" import
1062 imv_all_exports :: GlobalRdrEnv, -- ^ all the things the module could provide
1063 imv_qualified :: Bool -- ^ whether this is a qualified import
1064 }
1065
1066 -- | A ModGuts is carried through the compiler, accumulating stuff as it goes
1067 -- There is only one ModGuts at any time, the one for the module
1068 -- being compiled right now. Once it is compiled, a 'ModIface' and
1069 -- 'ModDetails' are extracted and the ModGuts is discarded.
1070 data ModGuts
1071 = ModGuts {
1072 mg_module :: !Module, -- ^ Module being compiled
1073 mg_hsc_src :: HscSource, -- ^ Whether it's an hs-boot module
1074 mg_loc :: SrcSpan, -- ^ For error messages from inner passes
1075 mg_exports :: ![AvailInfo], -- ^ What it exports
1076 mg_deps :: !Dependencies, -- ^ What it depends on, directly or
1077 -- otherwise
1078 mg_usages :: ![Usage], -- ^ What was used? Used for interfaces.
1079
1080 mg_used_th :: !Bool, -- ^ Did we run a TH splice?
1081 mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
1082
1083 -- These fields all describe the things **declared in this module**
1084 mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module.
1085 -- Used for creating interface files.
1086 mg_tcs :: ![TyCon], -- ^ TyCons declared in this module
1087 -- (includes TyCons for classes)
1088 mg_insts :: ![ClsInst], -- ^ Class instances declared in this module
1089 mg_fam_insts :: ![FamInst],
1090 -- ^ Family instances declared in this module
1091 mg_patsyns :: ![PatSyn], -- ^ Pattern synonyms declared in this module
1092 mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
1093 -- See Note [Overall plumbing for rules] in Rules.hs
1094 mg_binds :: !CoreProgram, -- ^ Bindings for this module
1095 mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
1096 mg_warns :: !Warnings, -- ^ Warnings declared in the module
1097 mg_anns :: [Annotation], -- ^ Annotations declared in this module
1098 mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
1099 mg_modBreaks :: !(Maybe ModBreaks), -- ^ Breakpoints for the module
1100 mg_vect_decls:: ![CoreVect], -- ^ Vectorisation declarations in this module
1101 -- (produced by desugarer & consumed by vectoriser)
1102 mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
1103
1104 -- The next two fields are unusual, because they give instance
1105 -- environments for *all* modules in the home package, including
1106 -- this module, rather than for *just* this module.
1107 -- Reason: when looking up an instance we don't want to have to
1108 -- look at each module in the home package in turn
1109 mg_inst_env :: InstEnv, -- ^ Class instance environment for
1110 -- /home-package/ modules (including this
1111 -- one); c.f. 'tcg_inst_env'
1112 mg_fam_inst_env :: FamInstEnv, -- ^ Type-family instance environment for
1113 -- /home-package/ modules (including this
1114 -- one); c.f. 'tcg_fam_inst_env'
1115
1116 mg_safe_haskell :: SafeHaskellMode, -- ^ Safe Haskell mode
1117 mg_trust_pkg :: Bool -- ^ Do we need to trust our
1118 -- own package for Safe Haskell?
1119 -- See Note [RnNames . Trust Own Package]
1120 }
1121
1122 -- The ModGuts takes on several slightly different forms:
1123 --
1124 -- After simplification, the following fields change slightly:
1125 -- mg_rules Orphan rules only (local ones now attached to binds)
1126 -- mg_binds With rules attached
1127
1128 ---------------------------------------------------------
1129 -- The Tidy pass forks the information about this module:
1130 -- * one lot goes to interface file generation (ModIface)
1131 -- and later compilations (ModDetails)
1132 -- * the other lot goes to code generation (CgGuts)
1133
1134 -- | A restricted form of 'ModGuts' for code generation purposes
1135 data CgGuts
1136 = CgGuts {
1137 cg_module :: !Module,
1138 -- ^ Module being compiled
1139
1140 cg_tycons :: [TyCon],
1141 -- ^ Algebraic data types (including ones that started
1142 -- life as classes); generate constructors and info
1143 -- tables. Includes newtypes, just for the benefit of
1144 -- External Core
1145
1146 cg_binds :: CoreProgram,
1147 -- ^ The tidied main bindings, including
1148 -- previously-implicit bindings for record and class
1149 -- selectors, and data constructor wrappers. But *not*
1150 -- data constructor workers; reason: we we regard them
1151 -- as part of the code-gen of tycons
1152
1153 cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
1154 cg_dep_pkgs :: ![UnitId], -- ^ Dependent packages, used to
1155 -- generate #includes for C code gen
1156 cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
1157 cg_modBreaks :: !(Maybe ModBreaks) -- ^ Module breakpoints
1158 }
1159
1160 -----------------------------------
1161 -- | Foreign export stubs
1162 data ForeignStubs
1163 = NoStubs
1164 -- ^ We don't have any stubs
1165 | ForeignStubs SDoc SDoc
1166 -- ^ There are some stubs. Parameters:
1167 --
1168 -- 1) Header file prototypes for
1169 -- "foreign exported" functions
1170 --
1171 -- 2) C stubs to use when calling
1172 -- "foreign exported" functions
1173
1174 appendStubC :: ForeignStubs -> SDoc -> ForeignStubs
1175 appendStubC NoStubs c_code = ForeignStubs empty c_code
1176 appendStubC (ForeignStubs h c) c_code = ForeignStubs h (c $$ c_code)
1177
1178 {-
1179 ************************************************************************
1180 * *
1181 The interactive context
1182 * *
1183 ************************************************************************
1184
1185 Note [The interactive package]
1186 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1187 Type, class, and value declarations at the command prompt are treated
1188 as if they were defined in modules
1189 interactive:Ghci1
1190 interactive:Ghci2
1191 ...etc...
1192 with each bunch of declarations using a new module, all sharing a
1193 common package 'interactive' (see Module.interactiveUnitId, and
1194 PrelNames.mkInteractiveModule).
1195
1196 This scheme deals well with shadowing. For example:
1197
1198 ghci> data T = A
1199 ghci> data T = B
1200 ghci> :i A
1201 data Ghci1.T = A -- Defined at <interactive>:2:10
1202
1203 Here we must display info about constructor A, but its type T has been
1204 shadowed by the second declaration. But it has a respectable
1205 qualified name (Ghci1.T), and its source location says where it was
1206 defined.
1207
1208 So the main invariant continues to hold, that in any session an
1209 original name M.T only refers to one unique thing. (In a previous
1210 iteration both the T's above were called :Interactive.T, albeit with
1211 different uniques, which gave rise to all sorts of trouble.)
1212
1213 The details are a bit tricky though:
1214
1215 * The field ic_mod_index counts which Ghci module we've got up to.
1216 It is incremented when extending ic_tythings
1217
1218 * ic_tythings contains only things from the 'interactive' package.
1219
1220 * Module from the 'interactive' package (Ghci1, Ghci2 etc) never go
1221 in the Home Package Table (HPT). When you say :load, that's when we
1222 extend the HPT.
1223
1224 * The 'thisPackage' field of DynFlags is *not* set to 'interactive'.
1225 It stays as 'main' (or whatever -this-package-key says), and is the
1226 package to which :load'ed modules are added to.
1227
1228 * So how do we arrange that declarations at the command prompt get to
1229 be in the 'interactive' package? Simply by setting the tcg_mod
1230 field of the TcGblEnv to "interactive:Ghci1". This is done by the
1231 call to initTc in initTcInteractive, which in turn get the module
1232 from it 'icInteractiveModule' field of the interactive context.
1233
1234 The 'thisPackage' field stays as 'main' (or whatever -this-package-key says.
1235
1236 * The main trickiness is that the type environment (tcg_type_env) and
1237 fixity envt (tcg_fix_env), now contain entities from all the
1238 interactive-package modules (Ghci1, Ghci2, ...) together, rather
1239 than just a single module as is usually the case. So you can't use
1240 "nameIsLocalOrFrom" to decide whether to look in the TcGblEnv vs
1241 the HPT/PTE. This is a change, but not a problem provided you
1242 know.
1243
1244 * However, the tcg_binds, tcg_sigs, tcg_insts, tcg_fam_insts, etc fields
1245 of the TcGblEnv, which collect "things defined in this module", all
1246 refer to stuff define in a single GHCi command, *not* all the commands
1247 so far.
1248
1249 In contrast, tcg_inst_env, tcg_fam_inst_env, have instances from
1250 all GhciN modules, which makes sense -- they are all "home package"
1251 modules.
1252
1253
1254 Note [Interactively-bound Ids in GHCi]
1255 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1256 The Ids bound by previous Stmts in GHCi are currently
1257 a) GlobalIds, with
1258 b) An External Name, like Ghci4.foo
1259 See Note [The interactive package] above
1260 c) A tidied type
1261
1262 (a) They must be GlobalIds (not LocalIds) otherwise when we come to
1263 compile an expression using these ids later, the byte code
1264 generator will consider the occurrences to be free rather than
1265 global.
1266
1267 (b) Having an External Name is important because of Note
1268 [GlobalRdrEnv shadowing] in RdrName
1269
1270 (c) Their types are tidied. This is important, because :info may ask
1271 to look at them, and :info expects the things it looks up to have
1272 tidy types
1273
1274 Where do interactively-bound Ids come from?
1275
1276 - GHCi REPL Stmts e.g.
1277 ghci> let foo x = x+1
1278 These start with an Internal Name because a Stmt is a local
1279 construct, so the renamer naturally builds an Internal name for
1280 each of its binders. Then in tcRnStmt they are externalised via
1281 TcRnDriver.externaliseAndTidyId, so they get Names like Ghic4.foo.
1282
1283 - Ids bound by the debugger etc have Names constructed by
1284 IfaceEnv.newInteractiveBinder; at the call sites it is followed by
1285 mkVanillaGlobal or mkVanillaGlobalWithInfo. So again, they are
1286 all Global, External.
1287
1288 - TyCons, Classes, and Ids bound by other top-level declarations in
1289 GHCi (eg foreign import, record selectors) also get External
1290 Names, with Ghci9 (or 8, or 7, etc) as the module name.
1291
1292
1293 Note [ic_tythings]
1294 ~~~~~~~~~~~~~~~~~~
1295 The ic_tythings field contains
1296 * The TyThings declared by the user at the command prompt
1297 (eg Ids, TyCons, Classes)
1298
1299 * The user-visible Ids that arise from such things, which
1300 *don't* come from 'implicitTyThings', notably:
1301 - record selectors
1302 - class ops
1303 The implicitTyThings are readily obtained from the TyThings
1304 but record selectors etc are not
1305
1306 It does *not* contain
1307 * DFunIds (they can be gotten from ic_instances)
1308 * CoAxioms (ditto)
1309
1310 See also Note [Interactively-bound Ids in GHCi]
1311
1312 Note [Override identical instances in GHCi]
1313 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1314 If you declare a new instance in GHCi that is identical to a previous one,
1315 we simply override the previous one; we don't regard it as overlapping.
1316 e.g. Prelude> data T = A | B
1317 Prelude> instance Eq T where ...
1318 Prelude> instance Eq T where ... -- This one overrides
1319
1320 It's exactly the same for type-family instances. See Trac #7102
1321 -}
1322
1323 -- | Interactive context, recording information about the state of the
1324 -- context in which statements are executed in a GHC session.
1325 data InteractiveContext
1326 = InteractiveContext {
1327 ic_dflags :: DynFlags,
1328 -- ^ The 'DynFlags' used to evaluate interative expressions
1329 -- and statements.
1330
1331 ic_mod_index :: Int,
1332 -- ^ Each GHCi stmt or declaration brings some new things into
1333 -- scope. We give them names like interactive:Ghci9.T,
1334 -- where the ic_index is the '9'. The ic_mod_index is
1335 -- incremented whenever we add something to ic_tythings
1336 -- See Note [The interactive package]
1337
1338 ic_imports :: [InteractiveImport],
1339 -- ^ The GHCi top-level scope (ic_rn_gbl_env) is extended with
1340 -- these imports
1341 --
1342 -- This field is only stored here so that the client
1343 -- can retrieve it with GHC.getContext. GHC itself doesn't
1344 -- use it, but does reset it to empty sometimes (such
1345 -- as before a GHC.load). The context is set with GHC.setContext.
1346
1347 ic_tythings :: [TyThing],
1348 -- ^ TyThings defined by the user, in reverse order of
1349 -- definition (ie most recent at the front)
1350 -- See Note [ic_tythings]
1351
1352 ic_rn_gbl_env :: GlobalRdrEnv,
1353 -- ^ The cached 'GlobalRdrEnv', built by
1354 -- 'InteractiveEval.setContext' and updated regularly
1355 -- It contains everything in scope at the command line,
1356 -- including everything in ic_tythings
1357
1358 ic_instances :: ([ClsInst], [FamInst]),
1359 -- ^ All instances and family instances created during
1360 -- this session. These are grabbed en masse after each
1361 -- update to be sure that proper overlapping is retained.
1362 -- That is, rather than re-check the overlapping each
1363 -- time we update the context, we just take the results
1364 -- from the instance code that already does that.
1365
1366 ic_fix_env :: FixityEnv,
1367 -- ^ Fixities declared in let statements
1368
1369 ic_default :: Maybe [Type],
1370 -- ^ The current default types, set by a 'default' declaration
1371
1372 #ifdef GHCI
1373 ic_resume :: [Resume],
1374 -- ^ The stack of breakpoint contexts
1375 #endif
1376
1377 ic_monad :: Name,
1378 -- ^ The monad that GHCi is executing in
1379
1380 ic_int_print :: Name,
1381 -- ^ The function that is used for printing results
1382 -- of expressions in ghci and -e mode.
1383
1384 ic_cwd :: Maybe FilePath
1385 -- virtual CWD of the program
1386 }
1387
1388 data InteractiveImport
1389 = IIDecl (ImportDecl RdrName)
1390 -- ^ Bring the exports of a particular module
1391 -- (filtered by an import decl) into scope
1392
1393 | IIModule ModuleName
1394 -- ^ Bring into scope the entire top-level envt of
1395 -- of this module, including the things imported
1396 -- into it.
1397
1398
1399 -- | Constructs an empty InteractiveContext.
1400 emptyInteractiveContext :: DynFlags -> InteractiveContext
1401 emptyInteractiveContext dflags
1402 = InteractiveContext {
1403 ic_dflags = dflags,
1404 ic_imports = [],
1405 ic_rn_gbl_env = emptyGlobalRdrEnv,
1406 ic_mod_index = 1,
1407 ic_tythings = [],
1408 ic_instances = ([],[]),
1409 ic_fix_env = emptyNameEnv,
1410 ic_monad = ioTyConName, -- IO monad by default
1411 ic_int_print = printName, -- System.IO.print by default
1412 ic_default = Nothing,
1413 #ifdef GHCI
1414 ic_resume = [],
1415 #endif
1416 ic_cwd = Nothing }
1417
1418 icInteractiveModule :: InteractiveContext -> Module
1419 icInteractiveModule (InteractiveContext { ic_mod_index = index })
1420 = mkInteractiveModule index
1421
1422 -- | This function returns the list of visible TyThings (useful for
1423 -- e.g. showBindings)
1424 icInScopeTTs :: InteractiveContext -> [TyThing]
1425 icInScopeTTs = ic_tythings
1426
1427 -- | Get the PrintUnqualified function based on the flags and this InteractiveContext
1428 icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified
1429 icPrintUnqual dflags InteractiveContext{ ic_rn_gbl_env = grenv } =
1430 mkPrintUnqualified dflags grenv
1431
1432 -- | extendInteractiveContext is called with new TyThings recently defined to update the
1433 -- InteractiveContext to include them. Ids are easily removed when shadowed,
1434 -- but Classes and TyCons are not. Some work could be done to determine
1435 -- whether they are entirely shadowed, but as you could still have references
1436 -- to them (e.g. instances for classes or values of the type for TyCons), it's
1437 -- not clear whether removing them is even the appropriate behavior.
1438 extendInteractiveContext :: InteractiveContext
1439 -> [TyThing]
1440 -> [ClsInst] -> [FamInst]
1441 -> Maybe [Type]
1442 -> FixityEnv
1443 -> InteractiveContext
1444 extendInteractiveContext ictxt new_tythings new_cls_insts new_fam_insts defaults fix_env
1445 = ictxt { ic_mod_index = ic_mod_index ictxt + 1
1446 -- Always bump this; even instances should create
1447 -- a new mod_index (Trac #9426)
1448 , ic_tythings = new_tythings ++ old_tythings
1449 , ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings
1450 , ic_instances = ( new_cls_insts ++ old_cls_insts
1451 , new_fam_insts ++ old_fam_insts )
1452 , ic_default = defaults
1453 , ic_fix_env = fix_env -- See Note [Fixity declarations in GHCi]
1454 }
1455 where
1456 new_ids = [id | AnId id <- new_tythings]
1457 old_tythings = filterOut (shadowed_by new_ids) (ic_tythings ictxt)
1458
1459 -- Discard old instances that have been fully overrridden
1460 -- See Note [Override identical instances in GHCi]
1461 (cls_insts, fam_insts) = ic_instances ictxt
1462 old_cls_insts = filterOut (\i -> any (identicalClsInstHead i) new_cls_insts) cls_insts
1463 old_fam_insts = filterOut (\i -> any (identicalFamInstHead i) new_fam_insts) fam_insts
1464
1465 extendInteractiveContextWithIds :: InteractiveContext -> [Id] -> InteractiveContext
1466 -- Just a specialised version
1467 extendInteractiveContextWithIds ictxt new_ids
1468 | null new_ids = ictxt
1469 | otherwise = ictxt { ic_mod_index = ic_mod_index ictxt + 1
1470 , ic_tythings = new_tythings ++ old_tythings
1471 , ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings }
1472 where
1473 new_tythings = map AnId new_ids
1474 old_tythings = filterOut (shadowed_by new_ids) (ic_tythings ictxt)
1475
1476 shadowed_by :: [Id] -> TyThing -> Bool
1477 shadowed_by ids = shadowed
1478 where
1479 shadowed id = getOccName id `elemOccSet` new_occs
1480 new_occs = mkOccSet (map getOccName ids)
1481
1482 setInteractivePackage :: HscEnv -> HscEnv
1483 -- Set the 'thisPackage' DynFlag to 'interactive'
1484 setInteractivePackage hsc_env
1485 = hsc_env { hsc_dflags = (hsc_dflags hsc_env) { thisPackage = interactiveUnitId } }
1486
1487 setInteractivePrintName :: InteractiveContext -> Name -> InteractiveContext
1488 setInteractivePrintName ic n = ic{ic_int_print = n}
1489
1490 -- ToDo: should not add Ids to the gbl env here
1491
1492 -- | Add TyThings to the GlobalRdrEnv, earlier ones in the list shadowing
1493 -- later ones, and shadowing existing entries in the GlobalRdrEnv.
1494 icExtendGblRdrEnv :: GlobalRdrEnv -> [TyThing] -> GlobalRdrEnv
1495 icExtendGblRdrEnv env tythings
1496 = foldr add env tythings -- Foldr makes things in the front of
1497 -- the list shadow things at the back
1498 where
1499 -- One at a time, to ensure each shadows the previous ones
1500 add thing env
1501 | is_sub_bndr thing
1502 = env
1503 | otherwise
1504 = foldl extendGlobalRdrEnv env1 (localGREsFromAvail avail)
1505 where
1506 env1 = shadowNames env (availNames avail)
1507 avail = tyThingAvailInfo thing
1508
1509 -- Ugh! The new_tythings may include record selectors, since they
1510 -- are not implicit-ids, and must appear in the TypeEnv. But they
1511 -- will also be brought into scope by the corresponding (ATyCon
1512 -- tc). And we want the latter, because that has the correct
1513 -- parent (Trac #10520)
1514 is_sub_bndr (AnId f) = case idDetails f of
1515 RecSelId {} -> True
1516 ClassOpId {} -> True
1517 _ -> False
1518 is_sub_bndr _ = False
1519
1520 substInteractiveContext :: InteractiveContext -> TCvSubst -> InteractiveContext
1521 substInteractiveContext ictxt@InteractiveContext{ ic_tythings = tts } subst
1522 | isEmptyTCvSubst subst = ictxt
1523 | otherwise = ictxt { ic_tythings = map subst_ty tts }
1524 where
1525 subst_ty (AnId id) = AnId $ id `setIdType` substTy subst (idType id)
1526 subst_ty tt = tt
1527
1528 instance Outputable InteractiveImport where
1529 ppr (IIModule m) = char '*' <> ppr m
1530 ppr (IIDecl d) = ppr d
1531
1532 {-
1533 ************************************************************************
1534 * *
1535 Building a PrintUnqualified
1536 * *
1537 ************************************************************************
1538
1539 Note [Printing original names]
1540 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1541 Deciding how to print names is pretty tricky. We are given a name
1542 P:M.T, where P is the package name, M is the defining module, and T is
1543 the occurrence name, and we have to decide in which form to display
1544 the name given a GlobalRdrEnv describing the current scope.
1545
1546 Ideally we want to display the name in the form in which it is in
1547 scope. However, the name might not be in scope at all, and that's
1548 where it gets tricky. Here are the cases:
1549
1550 1. T uniquely maps to P:M.T ---> "T" NameUnqual
1551 2. There is an X for which X.T
1552 uniquely maps to P:M.T ---> "X.T" NameQual X
1553 3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
1554 4. Otherwise ---> "P:M.T" NameNotInScope2
1555
1556 (3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
1557 all. In these cases we still want to refer to the name as "M.T", *but*
1558 "M.T" might mean something else in the current scope (e.g. if there's
1559 an "import X as M"), so to avoid confusion we avoid using "M.T" if
1560 there's already a binding for it. Instead we write P:M.T.
1561
1562 There's one further subtlety: in case (3), what if there are two
1563 things around, P1:M.T and P2:M.T? Then we don't want to print both of
1564 them as M.T! However only one of the modules P1:M and P2:M can be
1565 exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
1566 This is handled by the qual_mod component of PrintUnqualified, inside
1567 the (ppr mod) of case (3), in Name.pprModulePrefix
1568
1569 Note [Printing unit ids]
1570 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1571 In the old days, original names were tied to PackageIds, which directly
1572 corresponded to the entities that users wrote in Cabal files, and were perfectly
1573 suitable for printing when we need to disambiguate packages. However, with
1574 UnitId, the situation can be different: if the key is instantiated with
1575 some holes, we should try to give the user some more useful information.
1576 -}
1577
1578 -- | Creates some functions that work out the best ways to format
1579 -- names for the user according to a set of heuristics.
1580 mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
1581 mkPrintUnqualified dflags env = QueryQualify qual_name
1582 (mkQualModule dflags)
1583 (mkQualPackage dflags)
1584 where
1585 qual_name mod occ
1586 | [gre] <- unqual_gres
1587 , right_name gre
1588 = NameUnqual -- If there's a unique entity that's in scope
1589 -- unqualified with 'occ' AND that entity is
1590 -- the right one, then we can use the unqualified name
1591
1592 | [] <- unqual_gres
1593 , any is_name forceUnqualNames
1594 , not (isDerivedOccName occ)
1595 = NameUnqual -- Don't qualify names that come from modules
1596 -- that come with GHC, often appear in error messages,
1597 -- but aren't typically in scope. Doing this does not
1598 -- cause ambiguity, and it reduces the amount of
1599 -- qualification in error messages thus improving
1600 -- readability.
1601 --
1602 -- A motivating example is 'Constraint'. It's often not
1603 -- in scope, but printing GHC.Prim.Constraint seems
1604 -- overkill.
1605
1606 | [gre] <- qual_gres
1607 = NameQual (greQualModName gre)
1608
1609 | null qual_gres
1610 = if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
1611 then NameNotInScope1
1612 else NameNotInScope2
1613
1614 | otherwise
1615 = NameNotInScope1 -- Can happen if 'f' is bound twice in the module
1616 -- Eg f = True; g = 0; f = False
1617 where
1618 is_name :: Name -> Bool
1619 is_name name = nameModule name == mod && nameOccName name == occ
1620
1621 forceUnqualNames :: [Name]
1622 forceUnqualNames =
1623 map tyConName [ constraintKindTyCon, heqTyCon, coercibleTyCon
1624 , starKindTyCon, unicodeStarKindTyCon, ipTyCon ]
1625 ++ [ eqTyConName ]
1626
1627 right_name gre = nameModule_maybe (gre_name gre) == Just mod
1628
1629 unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
1630 qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
1631
1632 -- we can mention a module P:M without the P: qualifier iff
1633 -- "import M" would resolve unambiguously to P:M. (if P is the
1634 -- current package we can just assume it is unqualified).
1635
1636 -- | Creates a function for formatting modules based on two heuristics:
1637 -- (1) if the module is the current module, don't qualify, and (2) if there
1638 -- is only one exposed package which exports this module, don't qualify.
1639 mkQualModule :: DynFlags -> QueryQualifyModule
1640 mkQualModule dflags mod
1641 | moduleUnitId mod == thisPackage dflags = False
1642
1643 | [(_, pkgconfig)] <- lookup,
1644 packageConfigId pkgconfig == moduleUnitId mod
1645 -- this says: we are given a module P:M, is there just one exposed package
1646 -- that exposes a module M, and is it package P?
1647 = False
1648
1649 | otherwise = True
1650 where lookup = lookupModuleInAllPackages dflags (moduleName mod)
1651
1652 -- | Creates a function for formatting packages based on two heuristics:
1653 -- (1) don't qualify if the package in question is "main", and (2) only qualify
1654 -- with a unit id if the package ID would be ambiguous.
1655 mkQualPackage :: DynFlags -> QueryQualifyPackage
1656 mkQualPackage dflags pkg_key
1657 | pkg_key == mainUnitId || pkg_key == interactiveUnitId
1658 -- Skip the lookup if it's main, since it won't be in the package
1659 -- database!
1660 = False
1661 | Just pkgid <- mb_pkgid
1662 , searchPackageId dflags pkgid `lengthIs` 1
1663 -- this says: we are given a package pkg-0.1@MMM, are there only one
1664 -- exposed packages whose package ID is pkg-0.1?
1665 = False
1666 | otherwise
1667 = True
1668 where mb_pkgid = fmap sourcePackageId (lookupPackage dflags pkg_key)
1669
1670 -- | A function which only qualifies package names if necessary; but
1671 -- qualifies all other identifiers.
1672 pkgQual :: DynFlags -> PrintUnqualified
1673 pkgQual dflags = alwaysQualify {
1674 queryQualifyPackage = mkQualPackage dflags
1675 }
1676
1677 {-
1678 ************************************************************************
1679 * *
1680 Implicit TyThings
1681 * *
1682 ************************************************************************
1683
1684 Note [Implicit TyThings]
1685 ~~~~~~~~~~~~~~~~~~~~~~~~
1686 DEFINITION: An "implicit" TyThing is one that does not have its own
1687 IfaceDecl in an interface file. Instead, its binding in the type
1688 environment is created as part of typechecking the IfaceDecl for
1689 some other thing.
1690
1691 Examples:
1692 * All DataCons are implicit, because they are generated from the
1693 IfaceDecl for the data/newtype. Ditto class methods.
1694
1695 * Record selectors are *not* implicit, because they get their own
1696 free-standing IfaceDecl.
1697
1698 * Associated data/type families are implicit because they are
1699 included in the IfaceDecl of the parent class. (NB: the
1700 IfaceClass decl happens to use IfaceDecl recursively for the
1701 associated types, but that's irrelevant here.)
1702
1703 * Dictionary function Ids are not implicit.
1704
1705 * Axioms for newtypes are implicit (same as above), but axioms
1706 for data/type family instances are *not* implicit (like DFunIds).
1707 -}
1708
1709 -- | Determine the 'TyThing's brought into scope by another 'TyThing'
1710 -- /other/ than itself. For example, Id's don't have any implicit TyThings
1711 -- as they just bring themselves into scope, but classes bring their
1712 -- dictionary datatype, type constructor and some selector functions into
1713 -- scope, just for a start!
1714
1715 -- N.B. the set of TyThings returned here *must* match the set of
1716 -- names returned by LoadIface.ifaceDeclImplicitBndrs, in the sense that
1717 -- TyThing.getOccName should define a bijection between the two lists.
1718 -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
1719 -- The order of the list does not matter.
1720 implicitTyThings :: TyThing -> [TyThing]
1721 implicitTyThings (AnId _) = []
1722 implicitTyThings (ACoAxiom _cc) = []
1723 implicitTyThings (ATyCon tc) = implicitTyConThings tc
1724 implicitTyThings (AConLike cl) = implicitConLikeThings cl
1725
1726 implicitConLikeThings :: ConLike -> [TyThing]
1727 implicitConLikeThings (RealDataCon dc)
1728 = dataConImplicitTyThings dc
1729
1730 implicitConLikeThings (PatSynCon {})
1731 = [] -- Pattern synonyms have no implicit Ids; the wrapper and matcher
1732 -- are not "implicit"; they are simply new top-level bindings,
1733 -- and they have their own declaration in an interface file
1734 -- Unless a record pat syn when there are implicit selectors
1735 -- They are still not included here as `implicitConLikeThings` is
1736 -- used by `tcTyClsDecls` whilst pattern synonyms are typed checked
1737 -- by `tcTopValBinds`.
1738
1739 implicitClassThings :: Class -> [TyThing]
1740 implicitClassThings cl
1741 = -- Does not include default methods, because those Ids may have
1742 -- their own pragmas, unfoldings etc, not derived from the Class object
1743
1744 -- associated types
1745 -- No recursive call for the classATs, because they
1746 -- are only the family decls; they have no implicit things
1747 map ATyCon (classATs cl) ++
1748
1749 -- superclass and operation selectors
1750 map AnId (classAllSelIds cl)
1751
1752 implicitTyConThings :: TyCon -> [TyThing]
1753 implicitTyConThings tc
1754 = class_stuff ++
1755 -- fields (names of selectors)
1756
1757 -- (possibly) implicit newtype axioms
1758 -- or type family axioms
1759 implicitCoTyCon tc ++
1760
1761 -- for each data constructor in order,
1762 -- the contructor, worker, and (possibly) wrapper
1763 [ thing | dc <- tyConDataCons tc
1764 , thing <- AConLike (RealDataCon dc) : dataConImplicitTyThings dc ]
1765 -- NB. record selectors are *not* implicit, they have fully-fledged
1766 -- bindings that pass through the compilation pipeline as normal.
1767 where
1768 class_stuff = case tyConClass_maybe tc of
1769 Nothing -> []
1770 Just cl -> implicitClassThings cl
1771
1772 -- For newtypes and closed type families (only) add the implicit coercion tycon
1773 implicitCoTyCon :: TyCon -> [TyThing]
1774 implicitCoTyCon tc
1775 | Just co <- newTyConCo_maybe tc = [ACoAxiom $ toBranchedAxiom co]
1776 | Just co <- isClosedSynFamilyTyConWithAxiom_maybe tc
1777 = [ACoAxiom co]
1778 | otherwise = []
1779
1780 -- | Returns @True@ if there should be no interface-file declaration
1781 -- for this thing on its own: either it is built-in, or it is part
1782 -- of some other declaration, or it is generated implicitly by some
1783 -- other declaration.
1784 isImplicitTyThing :: TyThing -> Bool
1785 isImplicitTyThing (AConLike cl) = case cl of
1786 RealDataCon {} -> True
1787 PatSynCon {} -> False
1788 isImplicitTyThing (AnId id) = isImplicitId id
1789 isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
1790 isImplicitTyThing (ACoAxiom ax) = isImplicitCoAxiom ax
1791
1792 -- | tyThingParent_maybe x returns (Just p)
1793 -- when pprTyThingInContext sould print a declaration for p
1794 -- (albeit with some "..." in it) when asked to show x
1795 -- It returns the *immediate* parent. So a datacon returns its tycon
1796 -- but the tycon could be the associated type of a class, so it in turn
1797 -- might have a parent.
1798 tyThingParent_maybe :: TyThing -> Maybe TyThing
1799 tyThingParent_maybe (AConLike cl) = case cl of
1800 RealDataCon dc -> Just (ATyCon (dataConTyCon dc))
1801 PatSynCon{} -> Nothing
1802 tyThingParent_maybe (ATyCon tc) = case tyConAssoc_maybe tc of
1803 Just cls -> Just (ATyCon (classTyCon cls))
1804 Nothing -> Nothing
1805 tyThingParent_maybe (AnId id) = case idDetails id of
1806 RecSelId { sel_tycon = RecSelData tc } ->
1807 Just (ATyCon tc)
1808 ClassOpId cls ->
1809 Just (ATyCon (classTyCon cls))
1810 _other -> Nothing
1811 tyThingParent_maybe _other = Nothing
1812
1813 tyThingsTyCoVars :: [TyThing] -> TyCoVarSet
1814 tyThingsTyCoVars tts =
1815 unionVarSets $ map ttToVarSet tts
1816 where
1817 ttToVarSet (AnId id) = tyCoVarsOfType $ idType id
1818 ttToVarSet (AConLike cl) = case cl of
1819 RealDataCon dc -> tyCoVarsOfType $ dataConRepType dc
1820 PatSynCon{} -> emptyVarSet
1821 ttToVarSet (ATyCon tc)
1822 = case tyConClass_maybe tc of
1823 Just cls -> (mkVarSet . fst . classTvsFds) cls
1824 Nothing -> tyCoVarsOfType $ tyConKind tc
1825 ttToVarSet (ACoAxiom _) = emptyVarSet
1826
1827 -- | The Names that a TyThing should bring into scope. Used to build
1828 -- the GlobalRdrEnv for the InteractiveContext.
1829 tyThingAvailInfo :: TyThing -> AvailInfo
1830 tyThingAvailInfo (ATyCon t)
1831 = case tyConClass_maybe t of
1832 Just c -> AvailTC n (n : map getName (classMethods c)
1833 ++ map getName (classATs c))
1834 []
1835 where n = getName c
1836 Nothing -> AvailTC n (n : map getName dcs) flds
1837 where n = getName t
1838 dcs = tyConDataCons t
1839 flds = tyConFieldLabels t
1840 tyThingAvailInfo t
1841 = avail (getName t)
1842
1843 {-
1844 ************************************************************************
1845 * *
1846 TypeEnv
1847 * *
1848 ************************************************************************
1849 -}
1850
1851 -- | A map from 'Name's to 'TyThing's, constructed by typechecking
1852 -- local declarations or interface files
1853 type TypeEnv = NameEnv TyThing
1854
1855 emptyTypeEnv :: TypeEnv
1856 typeEnvElts :: TypeEnv -> [TyThing]
1857 typeEnvTyCons :: TypeEnv -> [TyCon]
1858 typeEnvCoAxioms :: TypeEnv -> [CoAxiom Branched]
1859 typeEnvIds :: TypeEnv -> [Id]
1860 typeEnvPatSyns :: TypeEnv -> [PatSyn]
1861 typeEnvDataCons :: TypeEnv -> [DataCon]
1862 typeEnvClasses :: TypeEnv -> [Class]
1863 lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
1864
1865 emptyTypeEnv = emptyNameEnv
1866 typeEnvElts env = nameEnvElts env
1867 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
1868 typeEnvCoAxioms env = [ax | ACoAxiom ax <- typeEnvElts env]
1869 typeEnvIds env = [id | AnId id <- typeEnvElts env]
1870 typeEnvPatSyns env = [ps | AConLike (PatSynCon ps) <- typeEnvElts env]
1871 typeEnvDataCons env = [dc | AConLike (RealDataCon dc) <- typeEnvElts env]
1872 typeEnvClasses env = [cl | tc <- typeEnvTyCons env,
1873 Just cl <- [tyConClass_maybe tc]]
1874
1875 mkTypeEnv :: [TyThing] -> TypeEnv
1876 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
1877
1878 mkTypeEnvWithImplicits :: [TyThing] -> TypeEnv
1879 mkTypeEnvWithImplicits things =
1880 mkTypeEnv things
1881 `plusNameEnv`
1882 mkTypeEnv (concatMap implicitTyThings things)
1883
1884 typeEnvFromEntities :: [Id] -> [TyCon] -> [FamInst] -> TypeEnv
1885 typeEnvFromEntities ids tcs famInsts =
1886 mkTypeEnv ( map AnId ids
1887 ++ map ATyCon all_tcs
1888 ++ concatMap implicitTyConThings all_tcs
1889 ++ map (ACoAxiom . toBranchedAxiom . famInstAxiom) famInsts
1890 )
1891 where
1892 all_tcs = tcs ++ famInstsRepTyCons famInsts
1893
1894 lookupTypeEnv = lookupNameEnv
1895
1896 -- Extend the type environment
1897 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
1898 extendTypeEnv env thing = extendNameEnv env (getName thing) thing
1899
1900 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
1901 extendTypeEnvList env things = foldl extendTypeEnv env things
1902
1903 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
1904 extendTypeEnvWithIds env ids
1905 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
1906
1907 -- | Find the 'TyThing' for the given 'Name' by using all the resources
1908 -- at our disposal: the compiled modules in the 'HomePackageTable' and the
1909 -- compiled modules in other packages that live in 'PackageTypeEnv'. Note
1910 -- that this does NOT look up the 'TyThing' in the module being compiled: you
1911 -- have to do that yourself, if desired
1912 lookupType :: DynFlags
1913 -> HomePackageTable
1914 -> PackageTypeEnv
1915 -> Name
1916 -> Maybe TyThing
1917
1918 lookupType dflags hpt pte name
1919 | isOneShot (ghcMode dflags) -- in one-shot, we don't use the HPT
1920 = lookupNameEnv pte name
1921 | otherwise
1922 = case lookupHptByModule hpt mod of
1923 Just hm -> lookupNameEnv (md_types (hm_details hm)) name
1924 Nothing -> lookupNameEnv pte name
1925 where
1926 mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1927
1928 -- | As 'lookupType', but with a marginally easier-to-use interface
1929 -- if you have a 'HscEnv'
1930 lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
1931 lookupTypeHscEnv hsc_env name = do
1932 eps <- readIORef (hsc_EPS hsc_env)
1933 return $! lookupType dflags hpt (eps_PTE eps) name
1934 where
1935 dflags = hsc_dflags hsc_env
1936 hpt = hsc_HPT hsc_env
1937
1938 -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
1939 tyThingTyCon :: TyThing -> TyCon
1940 tyThingTyCon (ATyCon tc) = tc
1941 tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
1942
1943 -- | Get the 'CoAxiom' from a 'TyThing' if it is a coercion axiom thing. Panics otherwise
1944 tyThingCoAxiom :: TyThing -> CoAxiom Branched
1945 tyThingCoAxiom (ACoAxiom ax) = ax
1946 tyThingCoAxiom other = pprPanic "tyThingCoAxiom" (pprTyThing other)
1947
1948 -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
1949 tyThingDataCon :: TyThing -> DataCon
1950 tyThingDataCon (AConLike (RealDataCon dc)) = dc
1951 tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
1952
1953 -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
1954 tyThingId :: TyThing -> Id
1955 tyThingId (AnId id) = id
1956 tyThingId (AConLike (RealDataCon dc)) = dataConWrapId dc
1957 tyThingId other = pprPanic "tyThingId" (pprTyThing other)
1958
1959 {-
1960 ************************************************************************
1961 * *
1962 \subsection{MonadThings and friends}
1963 * *
1964 ************************************************************************
1965 -}
1966
1967 -- | Class that abstracts out the common ability of the monads in GHC
1968 -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
1969 -- a number of related convenience functions for accessing particular
1970 -- kinds of 'TyThing'
1971 class Monad m => MonadThings m where
1972 lookupThing :: Name -> m TyThing
1973
1974 lookupId :: Name -> m Id
1975 lookupId = liftM tyThingId . lookupThing
1976
1977 lookupDataCon :: Name -> m DataCon
1978 lookupDataCon = liftM tyThingDataCon . lookupThing
1979
1980 lookupTyCon :: Name -> m TyCon
1981 lookupTyCon = liftM tyThingTyCon . lookupThing
1982
1983 {-
1984 ************************************************************************
1985 * *
1986 \subsection{Auxiliary types}
1987 * *
1988 ************************************************************************
1989
1990 These types are defined here because they are mentioned in ModDetails,
1991 but they are mostly elaborated elsewhere
1992 -}
1993
1994 ------------------ Warnings -------------------------
1995 -- | Warning information for a module
1996 data Warnings
1997 = NoWarnings -- ^ Nothing deprecated
1998 | WarnAll WarningTxt -- ^ Whole module deprecated
1999 | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
2000
2001 -- Only an OccName is needed because
2002 -- (1) a deprecation always applies to a binding
2003 -- defined in the module in which the deprecation appears.
2004 -- (2) deprecations are only reported outside the defining module.
2005 -- this is important because, otherwise, if we saw something like
2006 --
2007 -- {-# DEPRECATED f "" #-}
2008 -- f = ...
2009 -- h = f
2010 -- g = let f = undefined in f
2011 --
2012 -- we'd need more information than an OccName to know to say something
2013 -- about the use of f in h but not the use of the locally bound f in g
2014 --
2015 -- however, because we only report about deprecations from the outside,
2016 -- and a module can only export one value called f,
2017 -- an OccName suffices.
2018 --
2019 -- this is in contrast with fixity declarations, where we need to map
2020 -- a Name to its fixity declaration.
2021 deriving( Eq )
2022
2023 instance Binary Warnings where
2024 put_ bh NoWarnings = putByte bh 0
2025 put_ bh (WarnAll t) = do
2026 putByte bh 1
2027 put_ bh t
2028 put_ bh (WarnSome ts) = do
2029 putByte bh 2
2030 put_ bh ts
2031
2032 get bh = do
2033 h <- getByte bh
2034 case h of
2035 0 -> return NoWarnings
2036 1 -> do aa <- get bh
2037 return (WarnAll aa)
2038 _ -> do aa <- get bh
2039 return (WarnSome aa)
2040
2041 -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
2042 mkIfaceWarnCache :: Warnings -> OccName -> Maybe WarningTxt
2043 mkIfaceWarnCache NoWarnings = \_ -> Nothing
2044 mkIfaceWarnCache (WarnAll t) = \_ -> Just t
2045 mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs)
2046
2047 emptyIfaceWarnCache :: OccName -> Maybe WarningTxt
2048 emptyIfaceWarnCache _ = Nothing
2049
2050 plusWarns :: Warnings -> Warnings -> Warnings
2051 plusWarns d NoWarnings = d
2052 plusWarns NoWarnings d = d
2053 plusWarns _ (WarnAll t) = WarnAll t
2054 plusWarns (WarnAll t) _ = WarnAll t
2055 plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
2056
2057 -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
2058 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
2059 mkIfaceFixCache pairs
2060 = \n -> lookupOccEnv env n `orElse` defaultFixity
2061 where
2062 env = mkOccEnv pairs
2063
2064 emptyIfaceFixCache :: OccName -> Fixity
2065 emptyIfaceFixCache _ = defaultFixity
2066
2067 -- | Fixity environment mapping names to their fixities
2068 type FixityEnv = NameEnv FixItem
2069
2070 -- | Fixity information for an 'Name'. We keep the OccName in the range
2071 -- so that we can generate an interface from it
2072 data FixItem = FixItem OccName Fixity
2073
2074 instance Outputable FixItem where
2075 ppr (FixItem occ fix) = ppr fix <+> ppr occ
2076
2077 emptyFixityEnv :: FixityEnv
2078 emptyFixityEnv = emptyNameEnv
2079
2080 lookupFixity :: FixityEnv -> Name -> Fixity
2081 lookupFixity env n = case lookupNameEnv env n of
2082 Just (FixItem _ fix) -> fix
2083 Nothing -> defaultFixity
2084
2085 {-
2086 ************************************************************************
2087 * *
2088 \subsection{WhatsImported}
2089 * *
2090 ************************************************************************
2091 -}
2092
2093 -- | Records whether a module has orphans. An \"orphan\" is one of:
2094 --
2095 -- * An instance declaration in a module other than the definition
2096 -- module for one of the type constructors or classes in the instance head
2097 --
2098 -- * A transformation rule in a module other than the one defining
2099 -- the function in the head of the rule
2100 --
2101 -- * A vectorisation pragma
2102 type WhetherHasOrphans = Bool
2103
2104 -- | Does this module define family instances?
2105 type WhetherHasFamInst = Bool
2106
2107 -- | Did this module originate from a *-boot file?
2108 type IsBootInterface = Bool
2109
2110 -- | Dependency information about ALL modules and packages below this one
2111 -- in the import hierarchy.
2112 --
2113 -- Invariant: the dependencies of a module @M@ never includes @M@.
2114 --
2115 -- Invariant: none of the lists contain duplicates.
2116 data Dependencies
2117 = Deps { dep_mods :: [(ModuleName, IsBootInterface)]
2118 -- ^ All home-package modules transitively below this one
2119 -- I.e. modules that this one imports, or that are in the
2120 -- dep_mods of those directly-imported modules
2121
2122 , dep_pkgs :: [(UnitId, Bool)]
2123 -- ^ All packages transitively below this module
2124 -- I.e. packages to which this module's direct imports belong,
2125 -- or that are in the dep_pkgs of those modules
2126 -- The bool indicates if the package is required to be
2127 -- trusted when the module is imported as a safe import
2128 -- (Safe Haskell). See Note [RnNames . Tracking Trust Transitively]
2129
2130 , dep_orphs :: [Module]
2131 -- ^ Transitive closure of orphan modules (whether
2132 -- home or external pkg).
2133 --
2134 -- (Possible optimization: don't include family
2135 -- instance orphans as they are anyway included in
2136 -- 'dep_finsts'. But then be careful about code
2137 -- which relies on dep_orphs having the complete list!)
2138
2139 , dep_finsts :: [Module]
2140 -- ^ Modules that contain family instances (whether the
2141 -- instances are from the home or an external package)
2142 }
2143 deriving( Eq )
2144 -- Equality used only for old/new comparison in MkIface.addFingerprints
2145 -- See 'TcRnTypes.ImportAvails' for details on dependencies.
2146
2147 instance Binary Dependencies where
2148 put_ bh deps = do put_ bh (dep_mods deps)
2149 put_ bh (dep_pkgs deps)
2150 put_ bh (dep_orphs deps)
2151 put_ bh (dep_finsts deps)
2152
2153 get bh = do ms <- get bh
2154 ps <- get bh
2155 os <- get bh
2156 fis <- get bh
2157 return (Deps { dep_mods = ms, dep_pkgs = ps, dep_orphs = os,
2158 dep_finsts = fis })
2159
2160 noDependencies :: Dependencies
2161 noDependencies = Deps [] [] [] []
2162
2163 -- | Records modules for which changes may force recompilation of this module
2164 -- See wiki: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
2165 --
2166 -- This differs from Dependencies. A module X may be in the dep_mods of this
2167 -- module (via an import chain) but if we don't use anything from X it won't
2168 -- appear in our Usage
2169 data Usage
2170 -- | Module from another package
2171 = UsagePackageModule {
2172 usg_mod :: Module,
2173 -- ^ External package module depended on
2174 usg_mod_hash :: Fingerprint,
2175 -- ^ Cached module fingerprint
2176 usg_safe :: IsSafeImport
2177 -- ^ Was this module imported as a safe import
2178 }
2179 -- | Module from the current package
2180 | UsageHomeModule {
2181 usg_mod_name :: ModuleName,
2182 -- ^ Name of the module
2183 usg_mod_hash :: Fingerprint,
2184 -- ^ Cached module fingerprint
2185 usg_entities :: [(OccName,Fingerprint)],
2186 -- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
2187 -- NB: usages are for parent names only, e.g. type constructors
2188 -- but not the associated data constructors.
2189 usg_exports :: Maybe Fingerprint,
2190 -- ^ Fingerprint for the export list of this module,
2191 -- if we directly imported it (and hence we depend on its export list)
2192 usg_safe :: IsSafeImport
2193 -- ^ Was this module imported as a safe import
2194 } -- ^ Module from the current package
2195 -- | A file upon which the module depends, e.g. a CPP #include, or using TH's
2196 -- 'addDependentFile'
2197 | UsageFile {
2198 usg_file_path :: FilePath,
2199 -- ^ External file dependency. From a CPP #include or TH
2200 -- addDependentFile. Should be absolute.
2201 usg_file_hash :: Fingerprint
2202 -- ^ 'Fingerprint' of the file contents.
2203
2204 -- Note: We don't consider things like modification timestamps
2205 -- here, because there's no reason to recompile if the actual
2206 -- contents don't change. This previously lead to odd
2207 -- recompilation behaviors; see #8114
2208 }
2209 deriving( Eq )
2210 -- The export list field is (Just v) if we depend on the export list:
2211 -- i.e. we imported the module directly, whether or not we
2212 -- enumerated the things we imported, or just imported
2213 -- everything
2214 -- We need to recompile if M's exports change, because
2215 -- if the import was import M, we might now have a name clash
2216 -- in the importing module.
2217 -- if the import was import M(x) M might no longer export x
2218 -- The only way we don't depend on the export list is if we have
2219 -- import M()
2220 -- And of course, for modules that aren't imported directly we don't
2221 -- depend on their export lists
2222
2223 instance Binary Usage where
2224 put_ bh usg@UsagePackageModule{} = do
2225 putByte bh 0
2226 put_ bh (usg_mod usg)
2227 put_ bh (usg_mod_hash usg)
2228 put_ bh (usg_safe usg)
2229
2230 put_ bh usg@UsageHomeModule{} = do
2231 putByte bh 1
2232 put_ bh (usg_mod_name usg)
2233 put_ bh (usg_mod_hash usg)
2234 put_ bh (usg_exports usg)
2235 put_ bh (usg_entities usg)
2236 put_ bh (usg_safe usg)
2237
2238 put_ bh usg@UsageFile{} = do
2239 putByte bh 2
2240 put_ bh (usg_file_path usg)
2241 put_ bh (usg_file_hash usg)
2242
2243 get bh = do
2244 h <- getByte bh
2245 case h of
2246 0 -> do
2247 nm <- get bh
2248 mod <- get bh
2249 safe <- get bh
2250 return UsagePackageModule { usg_mod = nm, usg_mod_hash = mod, usg_safe = safe }
2251 1 -> do
2252 nm <- get bh
2253 mod <- get bh
2254 exps <- get bh
2255 ents <- get bh
2256 safe <- get bh
2257 return UsageHomeModule { usg_mod_name = nm, usg_mod_hash = mod,
2258 usg_exports = exps, usg_entities = ents, usg_safe = safe }
2259 2 -> do
2260 fp <- get bh
2261 hash <- get bh
2262 return UsageFile { usg_file_path = fp, usg_file_hash = hash }
2263 i -> error ("Binary.get(Usage): " ++ show i)
2264
2265 {-
2266 ************************************************************************
2267 * *
2268 The External Package State
2269 * *
2270 ************************************************************************
2271 -}
2272
2273 type PackageTypeEnv = TypeEnv
2274 type PackageRuleBase = RuleBase
2275 type PackageInstEnv = InstEnv
2276 type PackageFamInstEnv = FamInstEnv
2277 type PackageVectInfo = VectInfo
2278 type PackageAnnEnv = AnnEnv
2279
2280 -- | Information about other packages that we have slurped in by reading
2281 -- their interface files
2282 data ExternalPackageState
2283 = EPS {
2284 eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
2285 -- ^ In OneShot mode (only), home-package modules
2286 -- accumulate in the external package state, and are
2287 -- sucked in lazily. For these home-pkg modules
2288 -- (only) we need to record which are boot modules.
2289 -- We set this field after loading all the
2290 -- explicitly-imported interfaces, but before doing
2291 -- anything else
2292 --
2293 -- The 'ModuleName' part is not necessary, but it's useful for
2294 -- debug prints, and it's convenient because this field comes
2295 -- direct from 'TcRnTypes.imp_dep_mods'
2296
2297 eps_PIT :: !PackageIfaceTable,
2298 -- ^ The 'ModIface's for modules in external packages
2299 -- whose interfaces we have opened.
2300 -- The declarations in these interface files are held in the
2301 -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
2302 -- fields of this record, not in the 'mi_decls' fields of the
2303 -- interface we have sucked in.
2304 --
2305 -- What /is/ in the PIT is:
2306 --
2307 -- * The Module
2308 --
2309 -- * Fingerprint info
2310 --
2311 -- * Its exports
2312 --
2313 -- * Fixities
2314 --
2315 -- * Deprecations and warnings
2316
2317 eps_PTE :: !PackageTypeEnv,
2318 -- ^ Result of typechecking all the external package
2319 -- interface files we have sucked in. The domain of
2320 -- the mapping is external-package modules
2321
2322 eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
2323 -- from all the external-package modules
2324 eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
2325 -- from all the external-package modules
2326 eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
2327 -- from all the external-package modules
2328 eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
2329 -- from all the external-package modules
2330 eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
2331 -- from all the external-package modules
2332
2333 eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
2334 -- packages, keyed off the module that declared them
2335
2336 eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
2337 }
2338
2339 -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
2340 -- \"In\" means stuff that is just /read/ from interface files,
2341 -- \"Out\" means actually sucked in and type-checked
2342 data EpsStats = EpsStats { n_ifaces_in
2343 , n_decls_in, n_decls_out
2344 , n_rules_in, n_rules_out
2345 , n_insts_in, n_insts_out :: !Int }
2346
2347 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
2348 -- ^ Add stats for one newly-read interface
2349 addEpsInStats stats n_decls n_insts n_rules
2350 = stats { n_ifaces_in = n_ifaces_in stats + 1
2351 , n_decls_in = n_decls_in stats + n_decls
2352 , n_insts_in = n_insts_in stats + n_insts
2353 , n_rules_in = n_rules_in stats + n_rules }
2354
2355 {-
2356 Names in a NameCache are always stored as a Global, and have the SrcLoc
2357 of their binding locations.
2358
2359 Actually that's not quite right. When we first encounter the original
2360 name, we might not be at its binding site (e.g. we are reading an
2361 interface file); so we give it 'noSrcLoc' then. Later, when we find
2362 its binding site, we fix it up.
2363 -}
2364
2365 -- | The NameCache makes sure that there is just one Unique assigned for
2366 -- each original name; i.e. (module-name, occ-name) pair and provides
2367 -- something of a lookup mechanism for those names.
2368 data NameCache
2369 = NameCache { nsUniqs :: !UniqSupply,
2370 -- ^ Supply of uniques
2371 nsNames :: !OrigNameCache
2372 -- ^ Ensures that one original name gets one unique
2373 }
2374
2375 updNameCacheIO :: HscEnv
2376 -> (NameCache -> (NameCache, c)) -- The updating function
2377 -> IO c
2378 updNameCacheIO hsc_env upd_fn
2379 = atomicModifyIORef' (hsc_NC hsc_env) upd_fn
2380
2381 -- | Per-module cache of original 'OccName's given 'Name's
2382 type OrigNameCache = ModuleEnv (OccEnv Name)
2383
2384 mkSOName :: Platform -> FilePath -> FilePath
2385 mkSOName platform root
2386 = case platformOS platform of
2387 OSDarwin -> ("lib" ++ root) <.> "dylib"
2388 OSMinGW32 -> root <.> "dll"
2389 _ -> ("lib" ++ root) <.> "so"
2390
2391 mkHsSOName :: Platform -> FilePath -> FilePath
2392 mkHsSOName platform root = ("lib" ++ root) <.> soExt platform
2393
2394 soExt :: Platform -> FilePath
2395 soExt platform
2396 = case platformOS platform of
2397 OSDarwin -> "dylib"
2398 OSMinGW32 -> "dll"
2399 _ -> "so"
2400
2401 {-
2402 ************************************************************************
2403 * *
2404 The module graph and ModSummary type
2405 A ModSummary is a node in the compilation manager's
2406 dependency graph, and it's also passed to hscMain
2407 * *
2408 ************************************************************************
2409 -}
2410
2411 -- | A ModuleGraph contains all the nodes from the home package (only).
2412 -- There will be a node for each source module, plus a node for each hi-boot
2413 -- module.
2414 --
2415 -- The graph is not necessarily stored in topologically-sorted order. Use
2416 -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
2417 type ModuleGraph = [ModSummary]
2418
2419 emptyMG :: ModuleGraph
2420 emptyMG = []
2421
2422 -- | A single node in a 'ModuleGraph'. The nodes of the module graph
2423 -- are one of:
2424 --
2425 -- * A regular Haskell source module
2426 -- * A hi-boot source module
2427 --
2428 data ModSummary
2429 = ModSummary {
2430 ms_mod :: Module,
2431 -- ^ Identity of the module
2432 ms_hsc_src :: HscSource,
2433 -- ^ The module source either plain Haskell or hs-boot
2434 ms_location :: ModLocation,
2435 -- ^ Location of the various files belonging to the module
2436 ms_hs_date :: UTCTime,
2437 -- ^ Timestamp of source file
2438 ms_obj_date :: Maybe UTCTime,
2439 -- ^ Timestamp of object, if we have one
2440 ms_iface_date :: Maybe UTCTime,
2441 -- ^ Timestamp of hi file, if we *only* are typechecking (it is
2442 -- 'Nothing' otherwise.
2443 -- See Note [Recompilation checking when typechecking only] and #9243
2444 ms_srcimps :: [(Maybe FastString, Located ModuleName)],
2445 -- ^ Source imports of the module
2446 ms_textual_imps :: [(Maybe FastString, Located ModuleName)],
2447 -- ^ Non-source imports of the module from the module *text*
2448 ms_hspp_file :: FilePath,
2449 -- ^ Filename of preprocessed source file
2450 ms_hspp_opts :: DynFlags,
2451 -- ^ Cached flags from @OPTIONS@, @INCLUDE@ and @LANGUAGE@
2452 -- pragmas in the modules source code
2453 ms_hspp_buf :: Maybe StringBuffer
2454 -- ^ The actual preprocessed source, if we have it
2455 }
2456
2457 ms_mod_name :: ModSummary -> ModuleName
2458 ms_mod_name = moduleName . ms_mod
2459
2460 ms_imps :: ModSummary -> [(Maybe FastString, Located ModuleName)]
2461 ms_imps ms =
2462 ms_textual_imps ms ++
2463 map mk_additional_import (dynFlagDependencies (ms_hspp_opts ms))
2464 where
2465 mk_additional_import mod_nm = (Nothing, noLoc mod_nm)
2466
2467 -- The ModLocation contains both the original source filename and the
2468 -- filename of the cleaned-up source file after all preprocessing has been
2469 -- done. The point is that the summariser will have to cpp/unlit/whatever
2470 -- all files anyway, and there's no point in doing this twice -- just
2471 -- park the result in a temp file, put the name of it in the location,
2472 -- and let @compile@ read from that file on the way back up.
2473
2474 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
2475 -- the ms_hs_date and imports can, of course, change
2476
2477 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
2478 msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
2479 msHiFilePath ms = ml_hi_file (ms_location ms)
2480 msObjFilePath ms = ml_obj_file (ms_location ms)
2481
2482 -- | Did this 'ModSummary' originate from a hs-boot file?
2483 isBootSummary :: ModSummary -> Bool
2484 isBootSummary ms = ms_hsc_src ms == HsBootFile
2485
2486 instance Outputable ModSummary where
2487 ppr ms
2488 = sep [text "ModSummary {",
2489 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
2490 text "ms_mod =" <+> ppr (ms_mod ms)
2491 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
2492 text "ms_textual_imps =" <+> ppr (ms_textual_imps ms),
2493 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
2494 char '}'
2495 ]
2496
2497 showModMsg :: DynFlags -> HscTarget -> Bool -> ModSummary -> String
2498 showModMsg dflags target recomp mod_summary
2499 = showSDoc dflags $
2500 hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
2501 char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
2502 case target of
2503 HscInterpreted | recomp
2504 -> text "interpreted"
2505 HscNothing -> text "nothing"
2506 _ | HsigFile == ms_hsc_src mod_summary -> text "nothing"
2507 | otherwise -> text (normalise $ msObjFilePath mod_summary),
2508 char ')']
2509 where
2510 mod = moduleName (ms_mod mod_summary)
2511 mod_str = showPpr dflags mod
2512 ++ hscSourceString' dflags mod (ms_hsc_src mod_summary)
2513
2514 -- | Variant of hscSourceString which prints more information for signatures.
2515 -- This can't live in DriverPhases because this would cause a module loop.
2516 hscSourceString' :: DynFlags -> ModuleName -> HscSource -> String
2517 hscSourceString' _ _ HsSrcFile = ""
2518 hscSourceString' _ _ HsBootFile = "[boot]"
2519 hscSourceString' dflags mod HsigFile =
2520 "[" ++ (maybe "abstract sig"
2521 (("sig of "++).showPpr dflags)
2522 (getSigOf dflags mod)) ++ "]"
2523 -- NB: -sig-of could be missing if we're just typechecking
2524
2525 {-
2526 ************************************************************************
2527 * *
2528 \subsection{Recmpilation}
2529 * *
2530 ************************************************************************
2531 -}
2532
2533 -- | Indicates whether a given module's source has been modified since it
2534 -- was last compiled.
2535 data SourceModified
2536 = SourceModified
2537 -- ^ the source has been modified
2538 | SourceUnmodified
2539 -- ^ the source has not been modified. Compilation may or may
2540 -- not be necessary, depending on whether any dependencies have
2541 -- changed since we last compiled.
2542 | SourceUnmodifiedAndStable
2543 -- ^ the source has not been modified, and furthermore all of
2544 -- its (transitive) dependencies are up to date; it definitely
2545 -- does not need to be recompiled. This is important for two
2546 -- reasons: (a) we can omit the version check in checkOldIface,
2547 -- and (b) if the module used TH splices we don't need to force
2548 -- recompilation.
2549
2550 {-
2551 ************************************************************************
2552 * *
2553 \subsection{Hpc Support}
2554 * *
2555 ************************************************************************
2556 -}
2557
2558 -- | Information about a modules use of Haskell Program Coverage
2559 data HpcInfo
2560 = HpcInfo
2561 { hpcInfoTickCount :: Int
2562 , hpcInfoHash :: Int
2563 }
2564 | NoHpcInfo
2565 { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
2566 }
2567
2568 -- | This is used to signal if one of my imports used HPC instrumentation
2569 -- even if there is no module-local HPC usage
2570 type AnyHpcUsage = Bool
2571
2572 emptyHpcInfo :: AnyHpcUsage -> HpcInfo
2573 emptyHpcInfo = NoHpcInfo
2574
2575 -- | Find out if HPC is used by this module or any of the modules
2576 -- it depends upon
2577 isHpcUsed :: HpcInfo -> AnyHpcUsage
2578 isHpcUsed (HpcInfo {}) = True
2579 isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
2580
2581 {-
2582 ************************************************************************
2583 * *
2584 \subsection{Vectorisation Support}
2585 * *
2586 ************************************************************************
2587
2588 The following information is generated and consumed by the vectorisation
2589 subsystem. It communicates the vectorisation status of declarations from one
2590 module to another.
2591
2592 Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
2593 below? We need to know `f' when converting to IfaceVectInfo. However, during
2594 vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
2595 on just the OccName easily in a Core pass.
2596 -}
2597
2598 -- |Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'; see also
2599 -- documentation at 'Vectorise.Env.GlobalEnv'.
2600 --
2601 -- NB: The following tables may also include 'Var's, 'TyCon's and 'DataCon's from imported modules,
2602 -- which have been subsequently vectorised in the current module.
2603 --
2604 data VectInfo
2605 = VectInfo
2606 { vectInfoVar :: VarEnv (Var , Var ) -- ^ @(f, f_v)@ keyed on @f@
2607 , vectInfoTyCon :: NameEnv (TyCon , TyCon) -- ^ @(T, T_v)@ keyed on @T@
2608 , vectInfoDataCon :: NameEnv (DataCon, DataCon) -- ^ @(C, C_v)@ keyed on @C@
2609 , vectInfoParallelVars :: VarSet -- ^ set of parallel variables
2610 , vectInfoParallelTyCons :: NameSet -- ^ set of parallel type constructors
2611 }
2612
2613 -- |Vectorisation information for 'ModIface'; i.e, the vectorisation information propagated
2614 -- across module boundaries.
2615 --
2616 -- NB: The field 'ifaceVectInfoVar' explicitly contains the workers of data constructors as well as
2617 -- class selectors — i.e., their mappings are /not/ implicitly generated from the data types.
2618 -- Moreover, whether the worker of a data constructor is in 'ifaceVectInfoVar' determines
2619 -- whether that data constructor was vectorised (or is part of an abstractly vectorised type
2620 -- constructor).
2621 --
2622 data IfaceVectInfo
2623 = IfaceVectInfo
2624 { ifaceVectInfoVar :: [Name] -- ^ All variables in here have a vectorised variant
2625 , ifaceVectInfoTyCon :: [Name] -- ^ All 'TyCon's in here have a vectorised variant;
2626 -- the name of the vectorised variant and those of its
2627 -- data constructors are determined by
2628 -- 'OccName.mkVectTyConOcc' and
2629 -- 'OccName.mkVectDataConOcc'; the names of the
2630 -- isomorphisms are determined by 'OccName.mkVectIsoOcc'
2631 , ifaceVectInfoTyConReuse :: [Name] -- ^ The vectorised form of all the 'TyCon's in here
2632 -- coincides with the unconverted form; the name of the
2633 -- isomorphisms is determined by 'OccName.mkVectIsoOcc'
2634 , ifaceVectInfoParallelVars :: [Name] -- iface version of 'vectInfoParallelVar'
2635 , ifaceVectInfoParallelTyCons :: [Name] -- iface version of 'vectInfoParallelTyCon'
2636 }
2637
2638 noVectInfo :: VectInfo
2639 noVectInfo
2640 = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyVarSet emptyNameSet
2641
2642 plusVectInfo :: VectInfo -> VectInfo -> VectInfo
2643 plusVectInfo vi1 vi2 =
2644 VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
2645 (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
2646 (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
2647 (vectInfoParallelVars vi1 `unionVarSet` vectInfoParallelVars vi2)
2648 (vectInfoParallelTyCons vi1 `unionNameSet` vectInfoParallelTyCons vi2)
2649
2650 concatVectInfo :: [VectInfo] -> VectInfo
2651 concatVectInfo = foldr plusVectInfo noVectInfo
2652
2653 noIfaceVectInfo :: IfaceVectInfo
2654 noIfaceVectInfo = IfaceVectInfo [] [] [] [] []
2655
2656 isNoIfaceVectInfo :: IfaceVectInfo -> Bool
2657 isNoIfaceVectInfo (IfaceVectInfo l1 l2 l3 l4 l5)
2658 = null l1 && null l2 && null l3 && null l4 && null l5
2659
2660 instance Outputable VectInfo where
2661 ppr info = vcat
2662 [ ptext (sLit "variables :") <+> ppr (vectInfoVar info)
2663 , ptext (sLit "tycons :") <+> ppr (vectInfoTyCon info)
2664 , ptext (sLit "datacons :") <+> ppr (vectInfoDataCon info)
2665 , ptext (sLit "parallel vars :") <+> ppr (vectInfoParallelVars info)
2666 , ptext (sLit "parallel tycons :") <+> ppr (vectInfoParallelTyCons info)
2667 ]
2668
2669 instance Outputable IfaceVectInfo where
2670 ppr info = vcat
2671 [ ptext (sLit "variables :") <+> ppr (ifaceVectInfoVar info)
2672 , ptext (sLit "tycons :") <+> ppr (ifaceVectInfoTyCon info)
2673 , ptext (sLit "tycons reuse :") <+> ppr (ifaceVectInfoTyConReuse info)
2674 , ptext (sLit "parallel vars :") <+> ppr (ifaceVectInfoParallelVars info)
2675 , ptext (sLit "parallel tycons :") <+> ppr (ifaceVectInfoParallelTyCons info)
2676 ]
2677
2678
2679 instance Binary IfaceVectInfo where
2680 put_ bh (IfaceVectInfo a1 a2 a3 a4 a5) = do
2681 put_ bh a1
2682 put_ bh a2
2683 put_ bh a3
2684 put_ bh a4
2685 put_ bh a5
2686 get bh = do
2687 a1 <- get bh
2688 a2 <- get bh
2689 a3 <- get bh
2690 a4 <- get bh
2691 a5 <- get bh
2692 return (IfaceVectInfo a1 a2 a3 a4 a5)
2693
2694 {-
2695 ************************************************************************
2696 * *
2697 \subsection{Safe Haskell Support}
2698 * *
2699 ************************************************************************
2700
2701 This stuff here is related to supporting the Safe Haskell extension,
2702 primarily about storing under what trust type a module has been compiled.
2703 -}
2704
2705 -- | Is an import a safe import?
2706 type IsSafeImport = Bool
2707
2708 -- | Safe Haskell information for 'ModIface'
2709 -- Simply a wrapper around SafeHaskellMode to sepperate iface and flags
2710 newtype IfaceTrustInfo = TrustInfo SafeHaskellMode
2711
2712 getSafeMode :: IfaceTrustInfo -> SafeHaskellMode
2713 getSafeMode (TrustInfo x) = x
2714
2715 setSafeMode :: SafeHaskellMode -> IfaceTrustInfo
2716 setSafeMode = TrustInfo
2717
2718 noIfaceTrustInfo :: IfaceTrustInfo
2719 noIfaceTrustInfo = setSafeMode Sf_None
2720
2721 trustInfoToNum :: IfaceTrustInfo -> Word8
2722 trustInfoToNum it
2723 = case getSafeMode it of
2724 Sf_None -> 0
2725 Sf_Unsafe -> 1
2726 Sf_Trustworthy -> 2
2727 Sf_Safe -> 3
2728
2729 numToTrustInfo :: Word8 -> IfaceTrustInfo
2730 numToTrustInfo 0 = setSafeMode Sf_None
2731 numToTrustInfo 1 = setSafeMode Sf_Unsafe
2732 numToTrustInfo 2 = setSafeMode Sf_Trustworthy
2733 numToTrustInfo 3 = setSafeMode Sf_Safe
2734 numToTrustInfo 4 = setSafeMode Sf_Safe -- retained for backwards compat, used
2735 -- to be Sf_SafeInfered but we no longer
2736 -- differentiate.
2737 numToTrustInfo n = error $ "numToTrustInfo: bad input number! (" ++ show n ++ ")"
2738
2739 instance Outputable IfaceTrustInfo where
2740 ppr (TrustInfo Sf_None) = ptext $ sLit "none"
2741 ppr (TrustInfo Sf_Unsafe) = ptext $ sLit "unsafe"
2742 ppr (TrustInfo Sf_Trustworthy) = ptext $ sLit "trustworthy"
2743 ppr (TrustInfo Sf_Safe) = ptext $ sLit "safe"
2744
2745 instance Binary IfaceTrustInfo where
2746 put_ bh iftrust = putByte bh $ trustInfoToNum iftrust
2747 get bh = getByte bh >>= (return . numToTrustInfo)
2748
2749 {-
2750 ************************************************************************
2751 * *
2752 \subsection{Parser result}
2753 * *
2754 ************************************************************************
2755 -}
2756
2757 data HsParsedModule = HsParsedModule {
2758 hpm_module :: Located (HsModule RdrName),
2759 hpm_src_files :: [FilePath],
2760 -- ^ extra source files (e.g. from #includes). The lexer collects
2761 -- these from '# <file> <line>' pragmas, which the C preprocessor
2762 -- leaves behind. These files and their timestamps are stored in
2763 -- the .hi file, so that we can force recompilation if any of
2764 -- them change (#3589)
2765 hpm_annotations :: ApiAnns
2766 -- See note [Api annotations] in ApiAnnotation.hs
2767 }
2768
2769 {-
2770 ************************************************************************
2771 * *
2772 \subsection{Linkable stuff}
2773 * *
2774 ************************************************************************
2775
2776 This stuff is in here, rather than (say) in Linker.hs, because the Linker.hs
2777 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
2778 -}
2779
2780 -- | Information we can use to dynamically link modules into the compiler
2781 data Linkable = LM {
2782 linkableTime :: UTCTime, -- ^ Time at which this linkable was built
2783 -- (i.e. when the bytecodes were produced,
2784 -- or the mod date on the files)
2785 linkableModule :: Module, -- ^ The linkable module itself
2786 linkableUnlinked :: [Unlinked]
2787 -- ^ Those files and chunks of code we have yet to link.
2788 --
2789 -- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
2790 -- If this list is empty, the Linkable represents a fake linkable, which
2791 -- is generated in HscNothing mode to avoid recompiling modules.
2792 --
2793 -- ToDo: Do items get removed from this list when they get linked?
2794 }
2795
2796 isObjectLinkable :: Linkable -> Bool
2797 isObjectLinkable l = not (null unlinked) && all isObject unlinked
2798 where unlinked = linkableUnlinked l
2799 -- A linkable with no Unlinked's is treated as a BCO. We can
2800 -- generate a linkable with no Unlinked's as a result of
2801 -- compiling a module in HscNothing mode, and this choice
2802 -- happens to work well with checkStability in module GHC.
2803
2804 linkableObjs :: Linkable -> [FilePath]
2805 linkableObjs l = [ f | DotO f <- linkableUnlinked l ]
2806
2807 instance Outputable Linkable where
2808 ppr (LM when_made mod unlinkeds)
2809 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
2810 $$ nest 3 (ppr unlinkeds)
2811
2812 -------------------------------------------
2813
2814 -- | Objects which have yet to be linked by the compiler
2815 data Unlinked
2816 = DotO FilePath -- ^ An object file (.o)
2817 | DotA FilePath -- ^ Static archive file (.a)
2818 | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
2819 | BCOs CompiledByteCode -- ^ A byte-code object, lives only in memory
2820
2821 #ifndef GHCI
2822 data CompiledByteCode = CompiledByteCodeUndefined
2823 _unusedCompiledByteCode :: CompiledByteCode
2824 _unusedCompiledByteCode = CompiledByteCodeUndefined
2825
2826 data ModBreaks = ModBreaksUndefined
2827 emptyModBreaks :: ModBreaks
2828 emptyModBreaks = ModBreaksUndefined
2829 #endif
2830
2831 instance Outputable Unlinked where
2832 ppr (DotO path) = text "DotO" <+> text path
2833 ppr (DotA path) = text "DotA" <+> text path
2834 ppr (DotDLL path) = text "DotDLL" <+> text path
2835 #ifdef GHCI
2836 ppr (BCOs bcos) = text "BCOs" <+> ppr bcos
2837 #else
2838 ppr (BCOs _) = text "No byte code"
2839 #endif
2840
2841 -- | Is this an actual file on disk we can link in somehow?
2842 isObject :: Unlinked -> Bool
2843 isObject (DotO _) = True
2844 isObject (DotA _) = True
2845 isObject (DotDLL _) = True
2846 isObject _ = False
2847
2848 -- | Is this a bytecode linkable with no file on disk?
2849 isInterpretable :: Unlinked -> Bool
2850 isInterpretable = not . isObject
2851
2852 -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
2853 nameOfObject :: Unlinked -> FilePath
2854 nameOfObject (DotO fn) = fn
2855 nameOfObject (DotA fn) = fn
2856 nameOfObject (DotDLL fn) = fn
2857 nameOfObject other = pprPanic "nameOfObject" (ppr other)
2858
2859 -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
2860 byteCodeOfObject :: Unlinked -> CompiledByteCode
2861 byteCodeOfObject (BCOs bc) = bc
2862 byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
2863