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