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