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