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