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