add runMeta hook
[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 -> InteractiveContext
1407 extendInteractiveContext ictxt ids tcs new_cls_insts new_fam_insts defaults
1408 = ictxt { ic_mod_index = ic_mod_index ictxt + 1
1409 -- Always bump this; even instances should create
1410 -- a new mod_index (Trac #9426)
1411 , ic_tythings = new_tythings ++ old_tythings
1412 , ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings
1413 , ic_instances = (new_cls_insts ++ old_cls_insts, new_fam_insts ++ old_fam_insts)
1414 , ic_default = defaults }
1415 where
1416 new_tythings = map AnId ids ++ map ATyCon tcs
1417 old_tythings = filterOut (shadowed_by ids) (ic_tythings ictxt)
1418
1419 -- Discard old instances that have been fully overrridden
1420 -- See Note [Override identical instances in GHCi]
1421 (cls_insts, fam_insts) = ic_instances ictxt
1422 old_cls_insts = filterOut (\i -> any (identicalClsInstHead i) new_cls_insts) cls_insts
1423 old_fam_insts = filterOut (\i -> any (identicalFamInstHead i) new_fam_insts) fam_insts
1424
1425 extendInteractiveContextWithIds :: InteractiveContext -> [Id] -> InteractiveContext
1426 extendInteractiveContextWithIds ictxt ids
1427 | null ids = ictxt
1428 | otherwise = ictxt { ic_mod_index = ic_mod_index ictxt + 1
1429 , ic_tythings = new_tythings ++ old_tythings
1430 , ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings }
1431 where
1432 new_tythings = map AnId ids
1433 old_tythings = filterOut (shadowed_by ids) (ic_tythings ictxt)
1434
1435 shadowed_by :: [Id] -> TyThing -> Bool
1436 shadowed_by ids = shadowed
1437 where
1438 shadowed id = getOccName id `elemOccSet` new_occs
1439 new_occs = mkOccSet (map getOccName ids)
1440
1441 setInteractivePackage :: HscEnv -> HscEnv
1442 -- Set the 'thisPackage' DynFlag to 'interactive'
1443 setInteractivePackage hsc_env
1444 = hsc_env { hsc_dflags = (hsc_dflags hsc_env) { thisPackage = interactivePackageKey } }
1445
1446 setInteractivePrintName :: InteractiveContext -> Name -> InteractiveContext
1447 setInteractivePrintName ic n = ic{ic_int_print = n}
1448
1449 -- ToDo: should not add Ids to the gbl env here
1450
1451 -- | Add TyThings to the GlobalRdrEnv, earlier ones in the list shadowing
1452 -- later ones, and shadowing existing entries in the GlobalRdrEnv.
1453 icExtendGblRdrEnv :: GlobalRdrEnv -> [TyThing] -> GlobalRdrEnv
1454 icExtendGblRdrEnv env tythings
1455 = foldr add env tythings -- Foldr makes things in the front of
1456 -- the list shadow things at the back
1457 where
1458 add thing env = extendGlobalRdrEnv True {- Shadowing please -} env
1459 [tyThingAvailInfo thing]
1460 -- One at a time, to ensure each shadows the previous ones
1461
1462 substInteractiveContext :: InteractiveContext -> TvSubst -> InteractiveContext
1463 substInteractiveContext ictxt@InteractiveContext{ ic_tythings = tts } subst
1464 | isEmptyTvSubst subst = ictxt
1465 | otherwise = ictxt { ic_tythings = map subst_ty tts }
1466 where
1467 subst_ty (AnId id) = AnId $ id `setIdType` substTy subst (idType id)
1468 subst_ty tt = tt
1469
1470 instance Outputable InteractiveImport where
1471 ppr (IIModule m) = char '*' <> ppr m
1472 ppr (IIDecl d) = ppr d
1473
1474 {-
1475 ************************************************************************
1476 * *
1477 Building a PrintUnqualified
1478 * *
1479 ************************************************************************
1480
1481 Note [Printing original names]
1482 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1483 Deciding how to print names is pretty tricky. We are given a name
1484 P:M.T, where P is the package name, M is the defining module, and T is
1485 the occurrence name, and we have to decide in which form to display
1486 the name given a GlobalRdrEnv describing the current scope.
1487
1488 Ideally we want to display the name in the form in which it is in
1489 scope. However, the name might not be in scope at all, and that's
1490 where it gets tricky. Here are the cases:
1491
1492 1. T uniquely maps to P:M.T ---> "T" NameUnqual
1493 2. There is an X for which X.T
1494 uniquely maps to P:M.T ---> "X.T" NameQual X
1495 3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
1496 4. Otherwise ---> "P:M.T" NameNotInScope2
1497
1498 (3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
1499 all. In these cases we still want to refer to the name as "M.T", *but*
1500 "M.T" might mean something else in the current scope (e.g. if there's
1501 an "import X as M"), so to avoid confusion we avoid using "M.T" if
1502 there's already a binding for it. Instead we write P:M.T.
1503
1504 There's one further subtlety: in case (3), what if there are two
1505 things around, P1:M.T and P2:M.T? Then we don't want to print both of
1506 them as M.T! However only one of the modules P1:M and P2:M can be
1507 exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
1508 This is handled by the qual_mod component of PrintUnqualified, inside
1509 the (ppr mod) of case (3), in Name.pprModulePrefix
1510
1511 Note [Printing package keys]
1512 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1513 In the old days, original names were tied to PackageIds, which directly
1514 corresponded to the entities that users wrote in Cabal files, and were perfectly
1515 suitable for printing when we need to disambiguate packages. However, with
1516 PackageKey, the situation is different. First, the key is not a human readable
1517 at all, so we need to consult the package database to find the appropriate
1518 PackageId to display. Second, there may be multiple copies of a library visible
1519 with the same PackageId, in which case we need to disambiguate. For now,
1520 we just emit the actual package key (which the user can go look up); however,
1521 another scheme is to (recursively) say which dependencies are different.
1522
1523 NB: When we extend package keys to also have holes, we will have to disambiguate
1524 those as well.
1525 -}
1526
1527 -- | Creates some functions that work out the best ways to format
1528 -- names for the user according to a set of heuristics.
1529 mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
1530 mkPrintUnqualified dflags env = QueryQualify qual_name
1531 (mkQualModule dflags)
1532 (mkQualPackage dflags)
1533 where
1534 qual_name mod occ
1535 | [gre] <- unqual_gres
1536 , right_name gre
1537 = NameUnqual
1538 -- If there's a unique entity that's in scope unqualified with 'occ'
1539 -- AND that entity is the right one, then we can use the unqualified name
1540
1541 | [gre] <- qual_gres
1542 = NameQual (get_qual_mod (gre_prov gre))
1543
1544 | null qual_gres
1545 = if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
1546 then NameNotInScope1
1547 else NameNotInScope2
1548
1549 | otherwise
1550 = NameNotInScope1 -- Can happen if 'f' is bound twice in the module
1551 -- Eg f = True; g = 0; f = False
1552 where
1553 right_name gre = nameModule_maybe (gre_name gre) == Just mod
1554
1555 unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
1556 qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
1557
1558 get_qual_mod LocalDef = moduleName mod
1559 get_qual_mod (Imported is) = ASSERT( not (null is) ) is_as (is_decl (head is))
1560
1561 -- we can mention a module P:M without the P: qualifier iff
1562 -- "import M" would resolve unambiguously to P:M. (if P is the
1563 -- current package we can just assume it is unqualified).
1564
1565 -- | Creates a function for formatting modules based on two heuristics:
1566 -- (1) if the module is the current module, don't qualify, and (2) if there
1567 -- is only one exposed package which exports this module, don't qualify.
1568 mkQualModule :: DynFlags -> QueryQualifyModule
1569 mkQualModule dflags mod
1570 | modulePackageKey mod == thisPackage dflags = False
1571
1572 | [(_, pkgconfig)] <- lookup,
1573 packageConfigId pkgconfig == modulePackageKey mod
1574 -- this says: we are given a module P:M, is there just one exposed package
1575 -- that exposes a module M, and is it package P?
1576 = False
1577
1578 | otherwise = True
1579 where lookup = lookupModuleInAllPackages dflags (moduleName mod)
1580
1581 -- | Creates a function for formatting packages based on two heuristics:
1582 -- (1) don't qualify if the package in question is "main", and (2) only qualify
1583 -- with a package key if the package ID would be ambiguous.
1584 mkQualPackage :: DynFlags -> QueryQualifyPackage
1585 mkQualPackage dflags pkg_key
1586 | pkg_key == mainPackageKey || pkg_key == interactivePackageKey
1587 -- Skip the lookup if it's main, since it won't be in the package
1588 -- database!
1589 = False
1590 | searchPackageId dflags pkgid `lengthIs` 1
1591 -- this says: we are given a package pkg-0.1@MMM, are there only one
1592 -- exposed packages whose package ID is pkg-0.1?
1593 = False
1594 | otherwise
1595 = True
1596 where pkg = fromMaybe (pprPanic "qual_pkg" (ftext (packageKeyFS pkg_key)))
1597 (lookupPackage dflags pkg_key)
1598 pkgid = sourcePackageId pkg
1599
1600 -- | A function which only qualifies package names if necessary; but
1601 -- qualifies all other identifiers.
1602 pkgQual :: DynFlags -> PrintUnqualified
1603 pkgQual dflags = alwaysQualify {
1604 queryQualifyPackage = mkQualPackage dflags
1605 }
1606
1607 {-
1608 ************************************************************************
1609 * *
1610 Implicit TyThings
1611 * *
1612 ************************************************************************
1613
1614 Note [Implicit TyThings]
1615 ~~~~~~~~~~~~~~~~~~~~~~~~
1616 DEFINITION: An "implicit" TyThing is one that does not have its own
1617 IfaceDecl in an interface file. Instead, its binding in the type
1618 environment is created as part of typechecking the IfaceDecl for
1619 some other thing.
1620
1621 Examples:
1622 * All DataCons are implicit, because they are generated from the
1623 IfaceDecl for the data/newtype. Ditto class methods.
1624
1625 * Record selectors are *not* implicit, because they get their own
1626 free-standing IfaceDecl.
1627
1628 * Associated data/type families are implicit because they are
1629 included in the IfaceDecl of the parent class. (NB: the
1630 IfaceClass decl happens to use IfaceDecl recursively for the
1631 associated types, but that's irrelevant here.)
1632
1633 * Dictionary function Ids are not implicit.
1634
1635 * Axioms for newtypes are implicit (same as above), but axioms
1636 for data/type family instances are *not* implicit (like DFunIds).
1637 -}
1638
1639 -- | Determine the 'TyThing's brought into scope by another 'TyThing'
1640 -- /other/ than itself. For example, Id's don't have any implicit TyThings
1641 -- as they just bring themselves into scope, but classes bring their
1642 -- dictionary datatype, type constructor and some selector functions into
1643 -- scope, just for a start!
1644
1645 -- N.B. the set of TyThings returned here *must* match the set of
1646 -- names returned by LoadIface.ifaceDeclImplicitBndrs, in the sense that
1647 -- TyThing.getOccName should define a bijection between the two lists.
1648 -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
1649 -- The order of the list does not matter.
1650 implicitTyThings :: TyThing -> [TyThing]
1651 implicitTyThings (AnId _) = []
1652 implicitTyThings (ACoAxiom _cc) = []
1653 implicitTyThings (ATyCon tc) = implicitTyConThings tc
1654 implicitTyThings (AConLike cl) = implicitConLikeThings cl
1655
1656 implicitConLikeThings :: ConLike -> [TyThing]
1657 implicitConLikeThings (RealDataCon dc)
1658 = map AnId (dataConImplicitIds dc)
1659 -- For data cons add the worker and (possibly) wrapper
1660
1661 implicitConLikeThings (PatSynCon {})
1662 = [] -- Pattern synonyms have no implicit Ids; the wrapper and matcher
1663 -- are not "implicit"; they are simply new top-level bindings,
1664 -- and they have their own declaration in an interface file
1665
1666 implicitClassThings :: Class -> [TyThing]
1667 implicitClassThings cl
1668 = -- Does not include default methods, because those Ids may have
1669 -- their own pragmas, unfoldings etc, not derived from the Class object
1670 -- associated types
1671 -- No extras_plus (recursive call) for the classATs, because they
1672 -- are only the family decls; they have no implicit things
1673 map ATyCon (classATs cl) ++
1674 -- superclass and operation selectors
1675 map AnId (classAllSelIds cl)
1676
1677 implicitTyConThings :: TyCon -> [TyThing]
1678 implicitTyConThings tc
1679 = class_stuff ++
1680 -- fields (names of selectors)
1681
1682 -- (possibly) implicit newtype coercion
1683 implicitCoTyCon tc ++
1684
1685 -- for each data constructor in order,
1686 -- the contructor, worker, and (possibly) wrapper
1687 concatMap (extras_plus . AConLike . RealDataCon) (tyConDataCons tc)
1688 -- NB. record selectors are *not* implicit, they have fully-fledged
1689 -- bindings that pass through the compilation pipeline as normal.
1690 where
1691 class_stuff = case tyConClass_maybe tc of
1692 Nothing -> []
1693 Just cl -> implicitClassThings cl
1694
1695 -- add a thing and recursive call
1696 extras_plus :: TyThing -> [TyThing]
1697 extras_plus thing = thing : implicitTyThings thing
1698
1699 -- For newtypes and closed type families (only) add the implicit coercion tycon
1700 implicitCoTyCon :: TyCon -> [TyThing]
1701 implicitCoTyCon tc
1702 | Just co <- newTyConCo_maybe tc = [ACoAxiom $ toBranchedAxiom co]
1703 | Just co <- isClosedSynFamilyTyCon_maybe tc
1704 = [ACoAxiom co]
1705 | otherwise = []
1706
1707 -- | Returns @True@ if there should be no interface-file declaration
1708 -- for this thing on its own: either it is built-in, or it is part
1709 -- of some other declaration, or it is generated implicitly by some
1710 -- other declaration.
1711 isImplicitTyThing :: TyThing -> Bool
1712 isImplicitTyThing (AConLike cl) = case cl of
1713 RealDataCon {} -> True
1714 PatSynCon {} -> False
1715 isImplicitTyThing (AnId id) = isImplicitId id
1716 isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
1717 isImplicitTyThing (ACoAxiom ax) = isImplicitCoAxiom ax
1718
1719 -- | tyThingParent_maybe x returns (Just p)
1720 -- when pprTyThingInContext sould print a declaration for p
1721 -- (albeit with some "..." in it) when asked to show x
1722 -- It returns the *immediate* parent. So a datacon returns its tycon
1723 -- but the tycon could be the associated type of a class, so it in turn
1724 -- might have a parent.
1725 tyThingParent_maybe :: TyThing -> Maybe TyThing
1726 tyThingParent_maybe (AConLike cl) = case cl of
1727 RealDataCon dc -> Just (ATyCon (dataConTyCon dc))
1728 PatSynCon{} -> Nothing
1729 tyThingParent_maybe (ATyCon tc) = case tyConAssoc_maybe tc of
1730 Just cls -> Just (ATyCon (classTyCon cls))
1731 Nothing -> Nothing
1732 tyThingParent_maybe (AnId id) = case idDetails id of
1733 RecSelId { sel_tycon = tc } -> Just (ATyCon tc)
1734 ClassOpId cls -> Just (ATyCon (classTyCon cls))
1735 _other -> Nothing
1736 tyThingParent_maybe _other = Nothing
1737
1738 tyThingsTyVars :: [TyThing] -> TyVarSet
1739 tyThingsTyVars tts =
1740 unionVarSets $ map ttToVarSet tts
1741 where
1742 ttToVarSet (AnId id) = tyVarsOfType $ idType id
1743 ttToVarSet (AConLike cl) = case cl of
1744 RealDataCon dc -> tyVarsOfType $ dataConRepType dc
1745 PatSynCon{} -> emptyVarSet
1746 ttToVarSet (ATyCon tc)
1747 = case tyConClass_maybe tc of
1748 Just cls -> (mkVarSet . fst . classTvsFds) cls
1749 Nothing -> tyVarsOfType $ tyConKind tc
1750 ttToVarSet _ = emptyVarSet
1751
1752 -- | The Names that a TyThing should bring into scope. Used to build
1753 -- the GlobalRdrEnv for the InteractiveContext.
1754 tyThingAvailInfo :: TyThing -> AvailInfo
1755 tyThingAvailInfo (ATyCon t)
1756 = case tyConClass_maybe t of
1757 Just c -> AvailTC n (n : map getName (classMethods c)
1758 ++ map getName (classATs c))
1759 where n = getName c
1760 Nothing -> AvailTC n (n : map getName dcs ++
1761 concatMap dataConFieldLabels dcs)
1762 where n = getName t
1763 dcs = tyConDataCons t
1764 tyThingAvailInfo t
1765 = Avail (getName t)
1766
1767 {-
1768 ************************************************************************
1769 * *
1770 TypeEnv
1771 * *
1772 ************************************************************************
1773 -}
1774
1775 -- | A map from 'Name's to 'TyThing's, constructed by typechecking
1776 -- local declarations or interface files
1777 type TypeEnv = NameEnv TyThing
1778
1779 emptyTypeEnv :: TypeEnv
1780 typeEnvElts :: TypeEnv -> [TyThing]
1781 typeEnvTyCons :: TypeEnv -> [TyCon]
1782 typeEnvCoAxioms :: TypeEnv -> [CoAxiom Branched]
1783 typeEnvIds :: TypeEnv -> [Id]
1784 typeEnvPatSyns :: TypeEnv -> [PatSyn]
1785 typeEnvDataCons :: TypeEnv -> [DataCon]
1786 typeEnvClasses :: TypeEnv -> [Class]
1787 lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
1788
1789 emptyTypeEnv = emptyNameEnv
1790 typeEnvElts env = nameEnvElts env
1791 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
1792 typeEnvCoAxioms env = [ax | ACoAxiom ax <- typeEnvElts env]
1793 typeEnvIds env = [id | AnId id <- typeEnvElts env]
1794 typeEnvPatSyns env = [ps | AConLike (PatSynCon ps) <- typeEnvElts env]
1795 typeEnvDataCons env = [dc | AConLike (RealDataCon dc) <- typeEnvElts env]
1796 typeEnvClasses env = [cl | tc <- typeEnvTyCons env,
1797 Just cl <- [tyConClass_maybe tc]]
1798
1799 mkTypeEnv :: [TyThing] -> TypeEnv
1800 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
1801
1802 mkTypeEnvWithImplicits :: [TyThing] -> TypeEnv
1803 mkTypeEnvWithImplicits things =
1804 mkTypeEnv things
1805 `plusNameEnv`
1806 mkTypeEnv (concatMap implicitTyThings things)
1807
1808 typeEnvFromEntities :: [Id] -> [TyCon] -> [FamInst] -> TypeEnv
1809 typeEnvFromEntities ids tcs famInsts =
1810 mkTypeEnv ( map AnId ids
1811 ++ map ATyCon all_tcs
1812 ++ concatMap implicitTyConThings all_tcs
1813 ++ map (ACoAxiom . toBranchedAxiom . famInstAxiom) famInsts
1814 )
1815 where
1816 all_tcs = tcs ++ famInstsRepTyCons famInsts
1817
1818 lookupTypeEnv = lookupNameEnv
1819
1820 -- Extend the type environment
1821 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
1822 extendTypeEnv env thing = extendNameEnv env (getName thing) thing
1823
1824 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
1825 extendTypeEnvList env things = foldl extendTypeEnv env things
1826
1827 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
1828 extendTypeEnvWithIds env ids
1829 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
1830
1831 -- | Find the 'TyThing' for the given 'Name' by using all the resources
1832 -- at our disposal: the compiled modules in the 'HomePackageTable' and the
1833 -- compiled modules in other packages that live in 'PackageTypeEnv'. Note
1834 -- that this does NOT look up the 'TyThing' in the module being compiled: you
1835 -- have to do that yourself, if desired
1836 lookupType :: DynFlags
1837 -> HomePackageTable
1838 -> PackageTypeEnv
1839 -> Name
1840 -> Maybe TyThing
1841
1842 lookupType dflags hpt pte name
1843 | isOneShot (ghcMode dflags) -- in one-shot, we don't use the HPT
1844 = lookupNameEnv pte name
1845 | otherwise
1846 = case lookupHptByModule hpt mod of
1847 Just hm -> lookupNameEnv (md_types (hm_details hm)) name
1848 Nothing -> lookupNameEnv pte name
1849 where
1850 mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1851
1852 -- | As 'lookupType', but with a marginally easier-to-use interface
1853 -- if you have a 'HscEnv'
1854 lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
1855 lookupTypeHscEnv hsc_env name = do
1856 eps <- readIORef (hsc_EPS hsc_env)
1857 return $! lookupType dflags hpt (eps_PTE eps) name
1858 where
1859 dflags = hsc_dflags hsc_env
1860 hpt = hsc_HPT hsc_env
1861
1862 -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
1863 tyThingTyCon :: TyThing -> TyCon
1864 tyThingTyCon (ATyCon tc) = tc
1865 tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
1866
1867 -- | Get the 'CoAxiom' from a 'TyThing' if it is a coercion axiom thing. Panics otherwise
1868 tyThingCoAxiom :: TyThing -> CoAxiom Branched
1869 tyThingCoAxiom (ACoAxiom ax) = ax
1870 tyThingCoAxiom other = pprPanic "tyThingCoAxiom" (pprTyThing other)
1871
1872 -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
1873 tyThingDataCon :: TyThing -> DataCon
1874 tyThingDataCon (AConLike (RealDataCon dc)) = dc
1875 tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
1876
1877 -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
1878 tyThingId :: TyThing -> Id
1879 tyThingId (AnId id) = id
1880 tyThingId (AConLike (RealDataCon dc)) = dataConWrapId dc
1881 tyThingId other = pprPanic "tyThingId" (pprTyThing other)
1882
1883 {-
1884 ************************************************************************
1885 * *
1886 \subsection{MonadThings and friends}
1887 * *
1888 ************************************************************************
1889 -}
1890
1891 -- | Class that abstracts out the common ability of the monads in GHC
1892 -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
1893 -- a number of related convenience functions for accessing particular
1894 -- kinds of 'TyThing'
1895 class Monad m => MonadThings m where
1896 lookupThing :: Name -> m TyThing
1897
1898 lookupId :: Name -> m Id
1899 lookupId = liftM tyThingId . lookupThing
1900
1901 lookupDataCon :: Name -> m DataCon
1902 lookupDataCon = liftM tyThingDataCon . lookupThing
1903
1904 lookupTyCon :: Name -> m TyCon
1905 lookupTyCon = liftM tyThingTyCon . lookupThing
1906
1907 {-
1908 ************************************************************************
1909 * *
1910 \subsection{Auxiliary types}
1911 * *
1912 ************************************************************************
1913
1914 These types are defined here because they are mentioned in ModDetails,
1915 but they are mostly elaborated elsewhere
1916 -}
1917
1918 ------------------ Warnings -------------------------
1919 -- | Warning information for a module
1920 data Warnings
1921 = NoWarnings -- ^ Nothing deprecated
1922 | WarnAll WarningTxt -- ^ Whole module deprecated
1923 | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
1924
1925 -- Only an OccName is needed because
1926 -- (1) a deprecation always applies to a binding
1927 -- defined in the module in which the deprecation appears.
1928 -- (2) deprecations are only reported outside the defining module.
1929 -- this is important because, otherwise, if we saw something like
1930 --
1931 -- {-# DEPRECATED f "" #-}
1932 -- f = ...
1933 -- h = f
1934 -- g = let f = undefined in f
1935 --
1936 -- we'd need more information than an OccName to know to say something
1937 -- about the use of f in h but not the use of the locally bound f in g
1938 --
1939 -- however, because we only report about deprecations from the outside,
1940 -- and a module can only export one value called f,
1941 -- an OccName suffices.
1942 --
1943 -- this is in contrast with fixity declarations, where we need to map
1944 -- a Name to its fixity declaration.
1945 deriving( Eq )
1946
1947 instance Binary Warnings where
1948 put_ bh NoWarnings = putByte bh 0
1949 put_ bh (WarnAll t) = do
1950 putByte bh 1
1951 put_ bh t
1952 put_ bh (WarnSome ts) = do
1953 putByte bh 2
1954 put_ bh ts
1955
1956 get bh = do
1957 h <- getByte bh
1958 case h of
1959 0 -> return NoWarnings
1960 1 -> do aa <- get bh
1961 return (WarnAll aa)
1962 _ -> do aa <- get bh
1963 return (WarnSome aa)
1964
1965 -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
1966 mkIfaceWarnCache :: Warnings -> Name -> Maybe WarningTxt
1967 mkIfaceWarnCache NoWarnings = \_ -> Nothing
1968 mkIfaceWarnCache (WarnAll t) = \_ -> Just t
1969 mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
1970
1971 emptyIfaceWarnCache :: Name -> Maybe WarningTxt
1972 emptyIfaceWarnCache _ = Nothing
1973
1974 plusWarns :: Warnings -> Warnings -> Warnings
1975 plusWarns d NoWarnings = d
1976 plusWarns NoWarnings d = d
1977 plusWarns _ (WarnAll t) = WarnAll t
1978 plusWarns (WarnAll t) _ = WarnAll t
1979 plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
1980
1981 -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
1982 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
1983 mkIfaceFixCache pairs
1984 = \n -> lookupOccEnv env n `orElse` defaultFixity
1985 where
1986 env = mkOccEnv pairs
1987
1988 emptyIfaceFixCache :: OccName -> Fixity
1989 emptyIfaceFixCache _ = defaultFixity
1990
1991 -- | Fixity environment mapping names to their fixities
1992 type FixityEnv = NameEnv FixItem
1993
1994 -- | Fixity information for an 'Name'. We keep the OccName in the range
1995 -- so that we can generate an interface from it
1996 data FixItem = FixItem OccName Fixity
1997
1998 instance Outputable FixItem where
1999 ppr (FixItem occ fix) = ppr fix <+> ppr occ
2000
2001 emptyFixityEnv :: FixityEnv
2002 emptyFixityEnv = emptyNameEnv
2003
2004 lookupFixity :: FixityEnv -> Name -> Fixity
2005 lookupFixity env n = case lookupNameEnv env n of
2006 Just (FixItem _ fix) -> fix
2007 Nothing -> defaultFixity
2008
2009 {-
2010 ************************************************************************
2011 * *
2012 \subsection{WhatsImported}
2013 * *
2014 ************************************************************************
2015 -}
2016
2017 -- | Records whether a module has orphans. An \"orphan\" is one of:
2018 --
2019 -- * An instance declaration in a module other than the definition
2020 -- module for one of the type constructors or classes in the instance head
2021 --
2022 -- * A transformation rule in a module other than the one defining
2023 -- the function in the head of the rule
2024 --
2025 -- * A vectorisation pragma
2026 type WhetherHasOrphans = Bool
2027
2028 -- | Does this module define family instances?
2029 type WhetherHasFamInst = Bool
2030
2031 -- | Did this module originate from a *-boot file?
2032 type IsBootInterface = Bool
2033
2034 -- | Dependency information about ALL modules and packages below this one
2035 -- in the import hierarchy.
2036 --
2037 -- Invariant: the dependencies of a module @M@ never includes @M@.
2038 --
2039 -- Invariant: none of the lists contain duplicates.
2040 data Dependencies
2041 = Deps { dep_mods :: [(ModuleName, IsBootInterface)]
2042 -- ^ All home-package modules transitively below this one
2043 -- I.e. modules that this one imports, or that are in the
2044 -- dep_mods of those directly-imported modules
2045
2046 , dep_pkgs :: [(PackageKey, Bool)]
2047 -- ^ All packages transitively below this module
2048 -- I.e. packages to which this module's direct imports belong,
2049 -- or that are in the dep_pkgs of those modules
2050 -- The bool indicates if the package is required to be
2051 -- trusted when the module is imported as a safe import
2052 -- (Safe Haskell). See Note [RnNames . Tracking Trust Transitively]
2053
2054 , dep_orphs :: [Module]
2055 -- ^ Transitive closure of orphan modules (whether
2056 -- home or external pkg).
2057 --
2058 -- (Possible optimization: don't include family
2059 -- instance orphans as they are anyway included in
2060 -- 'dep_finsts'. But then be careful about code
2061 -- which relies on dep_orphs having the complete list!)
2062
2063 , dep_finsts :: [Module]
2064 -- ^ Modules that contain family instances (whether the
2065 -- instances are from the home or an external package)
2066 }
2067 deriving( Eq )
2068 -- Equality used only for old/new comparison in MkIface.addFingerprints
2069 -- See 'TcRnTypes.ImportAvails' for details on dependencies.
2070
2071 instance Binary Dependencies where
2072 put_ bh deps = do put_ bh (dep_mods deps)
2073 put_ bh (dep_pkgs deps)
2074 put_ bh (dep_orphs deps)
2075 put_ bh (dep_finsts deps)
2076
2077 get bh = do ms <- get bh
2078 ps <- get bh
2079 os <- get bh
2080 fis <- get bh
2081 return (Deps { dep_mods = ms, dep_pkgs = ps, dep_orphs = os,
2082 dep_finsts = fis })
2083
2084 noDependencies :: Dependencies
2085 noDependencies = Deps [] [] [] []
2086
2087 -- | Records modules for which changes may force recompilation of this module
2088 -- See wiki: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
2089 --
2090 -- This differs from Dependencies. A module X may be in the dep_mods of this
2091 -- module (via an import chain) but if we don't use anything from X it won't
2092 -- appear in our Usage
2093 data Usage
2094 -- | Module from another package
2095 = UsagePackageModule {
2096 usg_mod :: Module,
2097 -- ^ External package module depended on
2098 usg_mod_hash :: Fingerprint,
2099 -- ^ Cached module fingerprint
2100 usg_safe :: IsSafeImport
2101 -- ^ Was this module imported as a safe import
2102 }
2103 -- | Module from the current package
2104 | UsageHomeModule {
2105 usg_mod_name :: ModuleName,
2106 -- ^ Name of the module
2107 usg_mod_hash :: Fingerprint,
2108 -- ^ Cached module fingerprint
2109 usg_entities :: [(OccName,Fingerprint)],
2110 -- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
2111 -- NB: usages are for parent names only, e.g. type constructors
2112 -- but not the associated data constructors.
2113 usg_exports :: Maybe Fingerprint,
2114 -- ^ Fingerprint for the export list of this module,
2115 -- if we directly imported it (and hence we depend on its export list)
2116 usg_safe :: IsSafeImport
2117 -- ^ Was this module imported as a safe import
2118 } -- ^ Module from the current package
2119 -- | A file upon which the module depends, e.g. a CPP #include, or using TH's
2120 -- 'addDependentFile'
2121 | UsageFile {
2122 usg_file_path :: FilePath,
2123 -- ^ External file dependency. From a CPP #include or TH
2124 -- addDependentFile. Should be absolute.
2125 usg_file_hash :: Fingerprint
2126 -- ^ 'Fingerprint' of the file contents.
2127
2128 -- Note: We don't consider things like modification timestamps
2129 -- here, because there's no reason to recompile if the actual
2130 -- contents don't change. This previously lead to odd
2131 -- recompilation behaviors; see #8114
2132 }
2133 deriving( Eq )
2134 -- The export list field is (Just v) if we depend on the export list:
2135 -- i.e. we imported the module directly, whether or not we
2136 -- enumerated the things we imported, or just imported
2137 -- everything
2138 -- We need to recompile if M's exports change, because
2139 -- if the import was import M, we might now have a name clash
2140 -- in the importing module.
2141 -- if the import was import M(x) M might no longer export x
2142 -- The only way we don't depend on the export list is if we have
2143 -- import M()
2144 -- And of course, for modules that aren't imported directly we don't
2145 -- depend on their export lists
2146
2147 instance Binary Usage where
2148 put_ bh usg@UsagePackageModule{} = do
2149 putByte bh 0
2150 put_ bh (usg_mod usg)
2151 put_ bh (usg_mod_hash usg)
2152 put_ bh (usg_safe usg)
2153
2154 put_ bh usg@UsageHomeModule{} = do
2155 putByte bh 1
2156 put_ bh (usg_mod_name usg)
2157 put_ bh (usg_mod_hash usg)
2158 put_ bh (usg_exports usg)
2159 put_ bh (usg_entities usg)
2160 put_ bh (usg_safe usg)
2161
2162 put_ bh usg@UsageFile{} = do
2163 putByte bh 2
2164 put_ bh (usg_file_path usg)
2165 put_ bh (usg_file_hash usg)
2166
2167 get bh = do
2168 h <- getByte bh
2169 case h of
2170 0 -> do
2171 nm <- get bh
2172 mod <- get bh
2173 safe <- get bh
2174 return UsagePackageModule { usg_mod = nm, usg_mod_hash = mod, usg_safe = safe }
2175 1 -> do
2176 nm <- get bh
2177 mod <- get bh
2178 exps <- get bh
2179 ents <- get bh
2180 safe <- get bh
2181 return UsageHomeModule { usg_mod_name = nm, usg_mod_hash = mod,
2182 usg_exports = exps, usg_entities = ents, usg_safe = safe }
2183 2 -> do
2184 fp <- get bh
2185 hash <- get bh
2186 return UsageFile { usg_file_path = fp, usg_file_hash = hash }
2187 i -> error ("Binary.get(Usage): " ++ show i)
2188
2189 {-
2190 ************************************************************************
2191 * *
2192 The External Package State
2193 * *
2194 ************************************************************************
2195 -}
2196
2197 type PackageTypeEnv = TypeEnv
2198 type PackageRuleBase = RuleBase
2199 type PackageInstEnv = InstEnv
2200 type PackageFamInstEnv = FamInstEnv
2201 type PackageVectInfo = VectInfo
2202 type PackageAnnEnv = AnnEnv
2203
2204 -- | Information about other packages that we have slurped in by reading
2205 -- their interface files
2206 data ExternalPackageState
2207 = EPS {
2208 eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
2209 -- ^ In OneShot mode (only), home-package modules
2210 -- accumulate in the external package state, and are
2211 -- sucked in lazily. For these home-pkg modules
2212 -- (only) we need to record which are boot modules.
2213 -- We set this field after loading all the
2214 -- explicitly-imported interfaces, but before doing
2215 -- anything else
2216 --
2217 -- The 'ModuleName' part is not necessary, but it's useful for
2218 -- debug prints, and it's convenient because this field comes
2219 -- direct from 'TcRnTypes.imp_dep_mods'
2220
2221 eps_PIT :: !PackageIfaceTable,
2222 -- ^ The 'ModIface's for modules in external packages
2223 -- whose interfaces we have opened.
2224 -- The declarations in these interface files are held in the
2225 -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
2226 -- fields of this record, not in the 'mi_decls' fields of the
2227 -- interface we have sucked in.
2228 --
2229 -- What /is/ in the PIT is:
2230 --
2231 -- * The Module
2232 --
2233 -- * Fingerprint info
2234 --
2235 -- * Its exports
2236 --
2237 -- * Fixities
2238 --
2239 -- * Deprecations and warnings
2240
2241 eps_PTE :: !PackageTypeEnv,
2242 -- ^ Result of typechecking all the external package
2243 -- interface files we have sucked in. The domain of
2244 -- the mapping is external-package modules
2245
2246 eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
2247 -- from all the external-package modules
2248 eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
2249 -- from all the external-package modules
2250 eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
2251 -- from all the external-package modules
2252 eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
2253 -- from all the external-package modules
2254 eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
2255 -- from all the external-package modules
2256
2257 eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
2258 -- packages, keyed off the module that declared them
2259
2260 eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
2261 }
2262
2263 -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
2264 -- \"In\" means stuff that is just /read/ from interface files,
2265 -- \"Out\" means actually sucked in and type-checked
2266 data EpsStats = EpsStats { n_ifaces_in
2267 , n_decls_in, n_decls_out
2268 , n_rules_in, n_rules_out
2269 , n_insts_in, n_insts_out :: !Int }
2270
2271 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
2272 -- ^ Add stats for one newly-read interface
2273 addEpsInStats stats n_decls n_insts n_rules
2274 = stats { n_ifaces_in = n_ifaces_in stats + 1
2275 , n_decls_in = n_decls_in stats + n_decls
2276 , n_insts_in = n_insts_in stats + n_insts
2277 , n_rules_in = n_rules_in stats + n_rules }
2278
2279 {-
2280 Names in a NameCache are always stored as a Global, and have the SrcLoc
2281 of their binding locations.
2282
2283 Actually that's not quite right. When we first encounter the original
2284 name, we might not be at its binding site (e.g. we are reading an
2285 interface file); so we give it 'noSrcLoc' then. Later, when we find
2286 its binding site, we fix it up.
2287 -}
2288
2289 -- | The NameCache makes sure that there is just one Unique assigned for
2290 -- each original name; i.e. (module-name, occ-name) pair and provides
2291 -- something of a lookup mechanism for those names.
2292 data NameCache
2293 = NameCache { nsUniqs :: !UniqSupply,
2294 -- ^ Supply of uniques
2295 nsNames :: !OrigNameCache
2296 -- ^ Ensures that one original name gets one unique
2297 }
2298
2299 -- | Per-module cache of original 'OccName's given 'Name's
2300 type OrigNameCache = ModuleEnv (OccEnv Name)
2301
2302 mkSOName :: Platform -> FilePath -> FilePath
2303 mkSOName platform root
2304 = case platformOS platform of
2305 OSDarwin -> ("lib" ++ root) <.> "dylib"
2306 OSMinGW32 -> root <.> "dll"
2307 _ -> ("lib" ++ root) <.> "so"
2308
2309 mkHsSOName :: Platform -> FilePath -> FilePath
2310 mkHsSOName platform root = ("lib" ++ root) <.> soExt platform
2311
2312 soExt :: Platform -> FilePath
2313 soExt platform
2314 = case platformOS platform of
2315 OSDarwin -> "dylib"
2316 OSMinGW32 -> "dll"
2317 _ -> "so"
2318
2319 {-
2320 ************************************************************************
2321 * *
2322 The module graph and ModSummary type
2323 A ModSummary is a node in the compilation manager's
2324 dependency graph, and it's also passed to hscMain
2325 * *
2326 ************************************************************************
2327 -}
2328
2329 -- | A ModuleGraph contains all the nodes from the home package (only).
2330 -- There will be a node for each source module, plus a node for each hi-boot
2331 -- module.
2332 --
2333 -- The graph is not necessarily stored in topologically-sorted order. Use
2334 -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
2335 type ModuleGraph = [ModSummary]
2336
2337 emptyMG :: ModuleGraph
2338 emptyMG = []
2339
2340 -- | A single node in a 'ModuleGraph'. The nodes of the module graph
2341 -- are one of:
2342 --
2343 -- * A regular Haskell source module
2344 -- * A hi-boot source module
2345 -- * An external-core source module
2346 --
2347 data ModSummary
2348 = ModSummary {
2349 ms_mod :: Module,
2350 -- ^ Identity of the module
2351 ms_hsc_src :: HscSource,
2352 -- ^ The module source either plain Haskell, hs-boot or external core
2353 ms_location :: ModLocation,
2354 -- ^ Location of the various files belonging to the module
2355 ms_hs_date :: UTCTime,
2356 -- ^ Timestamp of source file
2357 ms_obj_date :: Maybe UTCTime,
2358 -- ^ Timestamp of object, if we have one
2359 ms_srcimps :: [Located (ImportDecl RdrName)],
2360 -- ^ Source imports of the module
2361 ms_textual_imps :: [Located (ImportDecl RdrName)],
2362 -- ^ Non-source imports of the module from the module *text*
2363 ms_hspp_file :: FilePath,
2364 -- ^ Filename of preprocessed source file
2365 ms_hspp_opts :: DynFlags,
2366 -- ^ Cached flags from @OPTIONS@, @INCLUDE@ and @LANGUAGE@
2367 -- pragmas in the modules source code
2368 ms_hspp_buf :: Maybe StringBuffer
2369 -- ^ The actual preprocessed source, if we have it
2370 }
2371
2372 ms_mod_name :: ModSummary -> ModuleName
2373 ms_mod_name = moduleName . ms_mod
2374
2375 ms_imps :: ModSummary -> [Located (ImportDecl RdrName)]
2376 ms_imps ms =
2377 ms_textual_imps ms ++
2378 map mk_additional_import (dynFlagDependencies (ms_hspp_opts ms))
2379 where
2380 -- This is a not-entirely-satisfactory means of creating an import
2381 -- that corresponds to an import that did not occur in the program
2382 -- text, such as those induced by the use of plugins (the -plgFoo
2383 -- flag)
2384 mk_additional_import mod_nm = noLoc $ ImportDecl {
2385 ideclName = noLoc mod_nm,
2386 ideclPkgQual = Nothing,
2387 ideclSource = False,
2388 ideclImplicit = True, -- Maybe implicit because not "in the program text"
2389 ideclQualified = False,
2390 ideclAs = Nothing,
2391 ideclHiding = Nothing,
2392 ideclSafe = False
2393 }
2394
2395 -- The ModLocation contains both the original source filename and the
2396 -- filename of the cleaned-up source file after all preprocessing has been
2397 -- done. The point is that the summariser will have to cpp/unlit/whatever
2398 -- all files anyway, and there's no point in doing this twice -- just
2399 -- park the result in a temp file, put the name of it in the location,
2400 -- and let @compile@ read from that file on the way back up.
2401
2402 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
2403 -- the ms_hs_date and imports can, of course, change
2404
2405 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
2406 msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
2407 msHiFilePath ms = ml_hi_file (ms_location ms)
2408 msObjFilePath ms = ml_obj_file (ms_location ms)
2409
2410 -- | Did this 'ModSummary' originate from a hs-boot file?
2411 isBootSummary :: ModSummary -> Bool
2412 isBootSummary ms = ms_hsc_src ms == HsBootFile
2413
2414 instance Outputable ModSummary where
2415 ppr ms
2416 = sep [text "ModSummary {",
2417 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
2418 text "ms_mod =" <+> ppr (ms_mod ms)
2419 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
2420 text "ms_textual_imps =" <+> ppr (ms_textual_imps ms),
2421 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
2422 char '}'
2423 ]
2424
2425 showModMsg :: DynFlags -> HscTarget -> Bool -> ModSummary -> String
2426 showModMsg dflags target recomp mod_summary
2427 = showSDoc dflags $
2428 hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
2429 char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
2430 case target of
2431 HscInterpreted | recomp
2432 -> text "interpreted"
2433 HscNothing -> text "nothing"
2434 _ | HsigFile == ms_hsc_src mod_summary -> text "nothing"
2435 | otherwise -> text (normalise $ msObjFilePath mod_summary),
2436 char ')']
2437 where
2438 mod = moduleName (ms_mod mod_summary)
2439 mod_str = showPpr dflags mod
2440 ++ hscSourceString' dflags mod (ms_hsc_src mod_summary)
2441
2442 -- | Variant of hscSourceString which prints more information for signatures.
2443 -- This can't live in DriverPhases because this would cause a module loop.
2444 hscSourceString' :: DynFlags -> ModuleName -> HscSource -> String
2445 hscSourceString' _ _ HsSrcFile = ""
2446 hscSourceString' _ _ HsBootFile = "[boot]"
2447 hscSourceString' dflags mod HsigFile =
2448 "[" ++ (maybe "abstract sig"
2449 (("sig of "++).showPpr dflags)
2450 (getSigOf dflags mod)) ++ "]"
2451 -- NB: -sig-of could be missing if we're just typechecking
2452
2453 {-
2454 ************************************************************************
2455 * *
2456 \subsection{Recmpilation}
2457 * *
2458 ************************************************************************
2459 -}
2460
2461 -- | Indicates whether a given module's source has been modified since it
2462 -- was last compiled.
2463 data SourceModified
2464 = SourceModified
2465 -- ^ the source has been modified
2466 | SourceUnmodified
2467 -- ^ the source has not been modified. Compilation may or may
2468 -- not be necessary, depending on whether any dependencies have
2469 -- changed since we last compiled.
2470 | SourceUnmodifiedAndStable
2471 -- ^ the source has not been modified, and furthermore all of
2472 -- its (transitive) dependencies are up to date; it definitely
2473 -- does not need to be recompiled. This is important for two
2474 -- reasons: (a) we can omit the version check in checkOldIface,
2475 -- and (b) if the module used TH splices we don't need to force
2476 -- recompilation.
2477
2478 {-
2479 ************************************************************************
2480 * *
2481 \subsection{Hpc Support}
2482 * *
2483 ************************************************************************
2484 -}
2485
2486 -- | Information about a modules use of Haskell Program Coverage
2487 data HpcInfo
2488 = HpcInfo
2489 { hpcInfoTickCount :: Int
2490 , hpcInfoHash :: Int
2491 }
2492 | NoHpcInfo
2493 { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
2494 }
2495
2496 -- | This is used to signal if one of my imports used HPC instrumentation
2497 -- even if there is no module-local HPC usage
2498 type AnyHpcUsage = Bool
2499
2500 emptyHpcInfo :: AnyHpcUsage -> HpcInfo
2501 emptyHpcInfo = NoHpcInfo
2502
2503 -- | Find out if HPC is used by this module or any of the modules
2504 -- it depends upon
2505 isHpcUsed :: HpcInfo -> AnyHpcUsage
2506 isHpcUsed (HpcInfo {}) = True
2507 isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
2508
2509 {-
2510 ************************************************************************
2511 * *
2512 \subsection{Vectorisation Support}
2513 * *
2514 ************************************************************************
2515
2516 The following information is generated and consumed by the vectorisation
2517 subsystem. It communicates the vectorisation status of declarations from one
2518 module to another.
2519
2520 Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
2521 below? We need to know `f' when converting to IfaceVectInfo. However, during
2522 vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
2523 on just the OccName easily in a Core pass.
2524 -}
2525
2526 -- |Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'; see also
2527 -- documentation at 'Vectorise.Env.GlobalEnv'.
2528 --
2529 -- NB: The following tables may also include 'Var's, 'TyCon's and 'DataCon's from imported modules,
2530 -- which have been subsequently vectorised in the current module.
2531 --
2532 data VectInfo
2533 = VectInfo
2534 { vectInfoVar :: VarEnv (Var , Var ) -- ^ @(f, f_v)@ keyed on @f@
2535 , vectInfoTyCon :: NameEnv (TyCon , TyCon) -- ^ @(T, T_v)@ keyed on @T@
2536 , vectInfoDataCon :: NameEnv (DataCon, DataCon) -- ^ @(C, C_v)@ keyed on @C@
2537 , vectInfoParallelVars :: VarSet -- ^ set of parallel variables
2538 , vectInfoParallelTyCons :: NameSet -- ^ set of parallel type constructors
2539 }
2540
2541 -- |Vectorisation information for 'ModIface'; i.e, the vectorisation information propagated
2542 -- across module boundaries.
2543 --
2544 -- NB: The field 'ifaceVectInfoVar' explicitly contains the workers of data constructors as well as
2545 -- class selectors — i.e., their mappings are /not/ implicitly generated from the data types.
2546 -- Moreover, whether the worker of a data constructor is in 'ifaceVectInfoVar' determines
2547 -- whether that data constructor was vectorised (or is part of an abstractly vectorised type
2548 -- constructor).
2549 --
2550 data IfaceVectInfo
2551 = IfaceVectInfo
2552 { ifaceVectInfoVar :: [Name] -- ^ All variables in here have a vectorised variant
2553 , ifaceVectInfoTyCon :: [Name] -- ^ All 'TyCon's in here have a vectorised variant;
2554 -- the name of the vectorised variant and those of its
2555 -- data constructors are determined by
2556 -- 'OccName.mkVectTyConOcc' and
2557 -- 'OccName.mkVectDataConOcc'; the names of the
2558 -- isomorphisms are determined by 'OccName.mkVectIsoOcc'
2559 , ifaceVectInfoTyConReuse :: [Name] -- ^ The vectorised form of all the 'TyCon's in here
2560 -- coincides with the unconverted form; the name of the
2561 -- isomorphisms is determined by 'OccName.mkVectIsoOcc'
2562 , ifaceVectInfoParallelVars :: [Name] -- iface version of 'vectInfoParallelVar'
2563 , ifaceVectInfoParallelTyCons :: [Name] -- iface version of 'vectInfoParallelTyCon'
2564 }
2565
2566 noVectInfo :: VectInfo
2567 noVectInfo
2568 = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyVarSet emptyNameSet
2569
2570 plusVectInfo :: VectInfo -> VectInfo -> VectInfo
2571 plusVectInfo vi1 vi2 =
2572 VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
2573 (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
2574 (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
2575 (vectInfoParallelVars vi1 `unionVarSet` vectInfoParallelVars vi2)
2576 (vectInfoParallelTyCons vi1 `unionNameSet` vectInfoParallelTyCons vi2)
2577
2578 concatVectInfo :: [VectInfo] -> VectInfo
2579 concatVectInfo = foldr plusVectInfo noVectInfo
2580
2581 noIfaceVectInfo :: IfaceVectInfo
2582 noIfaceVectInfo = IfaceVectInfo [] [] [] [] []
2583
2584 isNoIfaceVectInfo :: IfaceVectInfo -> Bool
2585 isNoIfaceVectInfo (IfaceVectInfo l1 l2 l3 l4 l5)
2586 = null l1 && null l2 && null l3 && null l4 && null l5
2587
2588 instance Outputable VectInfo where
2589 ppr info = vcat
2590 [ ptext (sLit "variables :") <+> ppr (vectInfoVar info)
2591 , ptext (sLit "tycons :") <+> ppr (vectInfoTyCon info)
2592 , ptext (sLit "datacons :") <+> ppr (vectInfoDataCon info)
2593 , ptext (sLit "parallel vars :") <+> ppr (vectInfoParallelVars info)
2594 , ptext (sLit "parallel tycons :") <+> ppr (vectInfoParallelTyCons info)
2595 ]
2596
2597 instance Outputable IfaceVectInfo where
2598 ppr info = vcat
2599 [ ptext (sLit "variables :") <+> ppr (ifaceVectInfoVar info)
2600 , ptext (sLit "tycons :") <+> ppr (ifaceVectInfoTyCon info)
2601 , ptext (sLit "tycons reuse :") <+> ppr (ifaceVectInfoTyConReuse info)
2602 , ptext (sLit "parallel vars :") <+> ppr (ifaceVectInfoParallelVars info)
2603 , ptext (sLit "parallel tycons :") <+> ppr (ifaceVectInfoParallelTyCons info)
2604 ]
2605
2606
2607 instance Binary IfaceVectInfo where
2608 put_ bh (IfaceVectInfo a1 a2 a3 a4 a5) = do
2609 put_ bh a1
2610 put_ bh a2
2611 put_ bh a3
2612 put_ bh a4
2613 put_ bh a5
2614 get bh = do
2615 a1 <- get bh
2616 a2 <- get bh
2617 a3 <- get bh
2618 a4 <- get bh
2619 a5 <- get bh
2620 return (IfaceVectInfo a1 a2 a3 a4 a5)
2621
2622 {-
2623 ************************************************************************
2624 * *
2625 \subsection{Safe Haskell Support}
2626 * *
2627 ************************************************************************
2628
2629 This stuff here is related to supporting the Safe Haskell extension,
2630 primarily about storing under what trust type a module has been compiled.
2631 -}
2632
2633 -- | Is an import a safe import?
2634 type IsSafeImport = Bool
2635
2636 -- | Safe Haskell information for 'ModIface'
2637 -- Simply a wrapper around SafeHaskellMode to sepperate iface and flags
2638 newtype IfaceTrustInfo = TrustInfo SafeHaskellMode
2639
2640 getSafeMode :: IfaceTrustInfo -> SafeHaskellMode
2641 getSafeMode (TrustInfo x) = x
2642
2643 setSafeMode :: SafeHaskellMode -> IfaceTrustInfo
2644 setSafeMode = TrustInfo
2645
2646 noIfaceTrustInfo :: IfaceTrustInfo
2647 noIfaceTrustInfo = setSafeMode Sf_None
2648
2649 trustInfoToNum :: IfaceTrustInfo -> Word8
2650 trustInfoToNum it
2651 = case getSafeMode it of
2652 Sf_None -> 0
2653 Sf_Unsafe -> 1
2654 Sf_Trustworthy -> 2
2655 Sf_Safe -> 3
2656
2657 numToTrustInfo :: Word8 -> IfaceTrustInfo
2658 numToTrustInfo 0 = setSafeMode Sf_None
2659 numToTrustInfo 1 = setSafeMode Sf_Unsafe
2660 numToTrustInfo 2 = setSafeMode Sf_Trustworthy
2661 numToTrustInfo 3 = setSafeMode Sf_Safe
2662 numToTrustInfo 4 = setSafeMode Sf_Safe -- retained for backwards compat, used
2663 -- to be Sf_SafeInfered but we no longer
2664 -- differentiate.
2665 numToTrustInfo n = error $ "numToTrustInfo: bad input number! (" ++ show n ++ ")"
2666
2667 instance Outputable IfaceTrustInfo where
2668 ppr (TrustInfo Sf_None) = ptext $ sLit "none"
2669 ppr (TrustInfo Sf_Unsafe) = ptext $ sLit "unsafe"
2670 ppr (TrustInfo Sf_Trustworthy) = ptext $ sLit "trustworthy"
2671 ppr (TrustInfo Sf_Safe) = ptext $ sLit "safe"
2672
2673 instance Binary IfaceTrustInfo where
2674 put_ bh iftrust = putByte bh $ trustInfoToNum iftrust
2675 get bh = getByte bh >>= (return . numToTrustInfo)
2676
2677 {-
2678 ************************************************************************
2679 * *
2680 \subsection{Parser result}
2681 * *
2682 ************************************************************************
2683 -}
2684
2685 data HsParsedModule = HsParsedModule {
2686 hpm_module :: Located (HsModule RdrName),
2687 hpm_src_files :: [FilePath],
2688 -- ^ extra source files (e.g. from #includes). The lexer collects
2689 -- these from '# <file> <line>' pragmas, which the C preprocessor
2690 -- leaves behind. These files and their timestamps are stored in
2691 -- the .hi file, so that we can force recompilation if any of
2692 -- them change (#3589)
2693 hpm_annotations :: ApiAnns
2694 -- See note [Api annotations] in ApiAnnotation.hs
2695 }
2696
2697 {-
2698 ************************************************************************
2699 * *
2700 \subsection{Linkable stuff}
2701 * *
2702 ************************************************************************
2703
2704 This stuff is in here, rather than (say) in Linker.lhs, because the Linker.lhs
2705 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
2706 -}
2707
2708 -- | Information we can use to dynamically link modules into the compiler
2709 data Linkable = LM {
2710 linkableTime :: UTCTime, -- ^ Time at which this linkable was built
2711 -- (i.e. when the bytecodes were produced,
2712 -- or the mod date on the files)
2713 linkableModule :: Module, -- ^ The linkable module itself
2714 linkableUnlinked :: [Unlinked]
2715 -- ^ Those files and chunks of code we have yet to link.
2716 --
2717 -- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
2718 -- If this list is empty, the Linkable represents a fake linkable, which
2719 -- is generated in HscNothing mode to avoid recompiling modules.
2720 --
2721 -- ToDo: Do items get removed from this list when they get linked?
2722 }
2723
2724 isObjectLinkable :: Linkable -> Bool
2725 isObjectLinkable l = not (null unlinked) && all isObject unlinked
2726 where unlinked = linkableUnlinked l
2727 -- A linkable with no Unlinked's is treated as a BCO. We can
2728 -- generate a linkable with no Unlinked's as a result of
2729 -- compiling a module in HscNothing mode, and this choice
2730 -- happens to work well with checkStability in module GHC.
2731
2732 linkableObjs :: Linkable -> [FilePath]
2733 linkableObjs l = [ f | DotO f <- linkableUnlinked l ]
2734
2735 instance Outputable Linkable where
2736 ppr (LM when_made mod unlinkeds)
2737 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
2738 $$ nest 3 (ppr unlinkeds)
2739
2740 -------------------------------------------
2741
2742 -- | Objects which have yet to be linked by the compiler
2743 data Unlinked
2744 = DotO FilePath -- ^ An object file (.o)
2745 | DotA FilePath -- ^ Static archive file (.a)
2746 | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
2747 | BCOs CompiledByteCode ModBreaks -- ^ A byte-code object, lives only in memory
2748
2749 #ifndef GHCI
2750 data CompiledByteCode = CompiledByteCodeUndefined
2751 _unused :: CompiledByteCode
2752 _unused = CompiledByteCodeUndefined
2753 #endif
2754
2755 instance Outputable Unlinked where
2756 ppr (DotO path) = text "DotO" <+> text path
2757 ppr (DotA path) = text "DotA" <+> text path
2758 ppr (DotDLL path) = text "DotDLL" <+> text path
2759 #ifdef GHCI
2760 ppr (BCOs bcos _) = text "BCOs" <+> ppr bcos
2761 #else
2762 ppr (BCOs _ _) = text "No byte code"
2763 #endif
2764
2765 -- | Is this an actual file on disk we can link in somehow?
2766 isObject :: Unlinked -> Bool
2767 isObject (DotO _) = True
2768 isObject (DotA _) = True
2769 isObject (DotDLL _) = True
2770 isObject _ = False
2771
2772 -- | Is this a bytecode linkable with no file on disk?
2773 isInterpretable :: Unlinked -> Bool
2774 isInterpretable = not . isObject
2775
2776 -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
2777 nameOfObject :: Unlinked -> FilePath
2778 nameOfObject (DotO fn) = fn
2779 nameOfObject (DotA fn) = fn
2780 nameOfObject (DotDLL fn) = fn
2781 nameOfObject other = pprPanic "nameOfObject" (ppr other)
2782
2783 -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
2784 byteCodeOfObject :: Unlinked -> CompiledByteCode
2785 byteCodeOfObject (BCOs bc _) = bc
2786 byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
2787
2788 {-
2789 ************************************************************************
2790 * *
2791 \subsection{Breakpoint Support}
2792 * *
2793 ************************************************************************
2794 -}
2795
2796 -- | Breakpoint index
2797 type BreakIndex = Int
2798
2799 -- | All the information about the breakpoints for a given module
2800 data ModBreaks
2801 = ModBreaks
2802 { modBreaks_flags :: BreakArray
2803 -- ^ The array of flags, one per breakpoint,
2804 -- indicating which breakpoints are enabled.
2805 , modBreaks_locs :: !(Array BreakIndex SrcSpan)
2806 -- ^ An array giving the source span of each breakpoint.
2807 , modBreaks_vars :: !(Array BreakIndex [OccName])
2808 -- ^ An array giving the names of the free variables at each breakpoint.
2809 , modBreaks_decls :: !(Array BreakIndex [String])
2810 -- ^ An array giving the names of the declarations enclosing each breakpoint.
2811 }
2812
2813 -- | Construct an empty ModBreaks
2814 emptyModBreaks :: ModBreaks
2815 emptyModBreaks = ModBreaks
2816 { modBreaks_flags = error "ModBreaks.modBreaks_array not initialised"
2817 -- ToDo: can we avoid this?
2818 , modBreaks_locs = array (0,-1) []
2819 , modBreaks_vars = array (0,-1) []
2820 , modBreaks_decls = array (0,-1) []
2821 }