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