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