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