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