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