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