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