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