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