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