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