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