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