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