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