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