165f8604367be93a44811c8f91951c2f49bb16e5
[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 ++ ic_tythings ictxt
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
1655 -- Discard old instances that have been fully overridden
1656 -- See Note [Override identical instances in GHCi]
1657 (cls_insts, fam_insts) = ic_instances ictxt
1658 old_cls_insts = filterOut (\i -> any (identicalClsInstHead i) new_cls_insts) cls_insts
1659
1660 extendInteractiveContextWithIds :: InteractiveContext -> [Id] -> InteractiveContext
1661 -- Just a specialised version
1662 extendInteractiveContextWithIds ictxt new_ids
1663 | null new_ids = ictxt
1664 | otherwise = ictxt { ic_mod_index = ic_mod_index ictxt + 1
1665 , ic_tythings = new_tythings ++ ic_tythings ictxt
1666 , ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings }
1667 where
1668 new_tythings = map AnId new_ids
1669
1670 setInteractivePackage :: HscEnv -> HscEnv
1671 -- Set the 'thisPackage' DynFlag to 'interactive'
1672 setInteractivePackage hsc_env
1673 = hsc_env { hsc_dflags = (hsc_dflags hsc_env)
1674 { thisInstalledUnitId = toInstalledUnitId interactiveUnitId } }
1675
1676 setInteractivePrintName :: InteractiveContext -> Name -> InteractiveContext
1677 setInteractivePrintName ic n = ic{ic_int_print = n}
1678
1679 -- ToDo: should not add Ids to the gbl env here
1680
1681 -- | Add TyThings to the GlobalRdrEnv, earlier ones in the list shadowing
1682 -- later ones, and shadowing existing entries in the GlobalRdrEnv.
1683 icExtendGblRdrEnv :: GlobalRdrEnv -> [TyThing] -> GlobalRdrEnv
1684 icExtendGblRdrEnv env tythings
1685 = foldr add env tythings -- Foldr makes things in the front of
1686 -- the list shadow things at the back
1687 where
1688 -- One at a time, to ensure each shadows the previous ones
1689 add thing env
1690 | is_sub_bndr thing
1691 = env
1692 | otherwise
1693 = foldl extendGlobalRdrEnv env1 (concatMap localGREsFromAvail avail)
1694 where
1695 env1 = shadowNames env (concatMap availNames avail)
1696 avail = tyThingAvailInfo thing
1697
1698 -- Ugh! The new_tythings may include record selectors, since they
1699 -- are not implicit-ids, and must appear in the TypeEnv. But they
1700 -- will also be brought into scope by the corresponding (ATyCon
1701 -- tc). And we want the latter, because that has the correct
1702 -- parent (Trac #10520)
1703 is_sub_bndr (AnId f) = case idDetails f of
1704 RecSelId {} -> True
1705 ClassOpId {} -> True
1706 _ -> False
1707 is_sub_bndr _ = False
1708
1709 substInteractiveContext :: InteractiveContext -> TCvSubst -> InteractiveContext
1710 substInteractiveContext ictxt@InteractiveContext{ ic_tythings = tts } subst
1711 | isEmptyTCvSubst subst = ictxt
1712 | otherwise = ictxt { ic_tythings = map subst_ty tts }
1713 where
1714 subst_ty (AnId id)
1715 = AnId $ id `setIdType` substTyAddInScope subst (idType id)
1716 -- Variables in the interactive context *can* mention free type variables
1717 -- because of the runtime debugger. Otherwise you'd expect all
1718 -- variables bound in the interactive context to be closed.
1719 subst_ty tt
1720 = tt
1721
1722 instance Outputable InteractiveImport where
1723 ppr (IIModule m) = char '*' <> ppr m
1724 ppr (IIDecl d) = ppr d
1725
1726 {-
1727 ************************************************************************
1728 * *
1729 Building a PrintUnqualified
1730 * *
1731 ************************************************************************
1732
1733 Note [Printing original names]
1734 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1735 Deciding how to print names is pretty tricky. We are given a name
1736 P:M.T, where P is the package name, M is the defining module, and T is
1737 the occurrence name, and we have to decide in which form to display
1738 the name given a GlobalRdrEnv describing the current scope.
1739
1740 Ideally we want to display the name in the form in which it is in
1741 scope. However, the name might not be in scope at all, and that's
1742 where it gets tricky. Here are the cases:
1743
1744 1. T uniquely maps to P:M.T ---> "T" NameUnqual
1745 2. There is an X for which X.T
1746 uniquely maps to P:M.T ---> "X.T" NameQual X
1747 3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
1748 4. Otherwise ---> "P:M.T" NameNotInScope2
1749
1750 (3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
1751 all. In these cases we still want to refer to the name as "M.T", *but*
1752 "M.T" might mean something else in the current scope (e.g. if there's
1753 an "import X as M"), so to avoid confusion we avoid using "M.T" if
1754 there's already a binding for it. Instead we write P:M.T.
1755
1756 There's one further subtlety: in case (3), what if there are two
1757 things around, P1:M.T and P2:M.T? Then we don't want to print both of
1758 them as M.T! However only one of the modules P1:M and P2:M can be
1759 exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
1760 This is handled by the qual_mod component of PrintUnqualified, inside
1761 the (ppr mod) of case (3), in Name.pprModulePrefix
1762
1763 Note [Printing unit ids]
1764 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1765 In the old days, original names were tied to PackageIds, which directly
1766 corresponded to the entities that users wrote in Cabal files, and were perfectly
1767 suitable for printing when we need to disambiguate packages. However, with
1768 UnitId, the situation can be different: if the key is instantiated with
1769 some holes, we should try to give the user some more useful information.
1770 -}
1771
1772 -- | Creates some functions that work out the best ways to format
1773 -- names for the user according to a set of heuristics.
1774 mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
1775 mkPrintUnqualified dflags env = QueryQualify qual_name
1776 (mkQualModule dflags)
1777 (mkQualPackage dflags)
1778 where
1779 qual_name mod occ
1780 | [gre] <- unqual_gres
1781 , right_name gre
1782 = NameUnqual -- If there's a unique entity that's in scope
1783 -- unqualified with 'occ' AND that entity is
1784 -- the right one, then we can use the unqualified name
1785
1786 | [] <- unqual_gres
1787 , any is_name forceUnqualNames
1788 , not (isDerivedOccName occ)
1789 = NameUnqual -- Don't qualify names that come from modules
1790 -- that come with GHC, often appear in error messages,
1791 -- but aren't typically in scope. Doing this does not
1792 -- cause ambiguity, and it reduces the amount of
1793 -- qualification in error messages thus improving
1794 -- readability.
1795 --
1796 -- A motivating example is 'Constraint'. It's often not
1797 -- in scope, but printing GHC.Prim.Constraint seems
1798 -- overkill.
1799
1800 | [gre] <- qual_gres
1801 = NameQual (greQualModName gre)
1802
1803 | null qual_gres
1804 = if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
1805 then NameNotInScope1
1806 else NameNotInScope2
1807
1808 | otherwise
1809 = NameNotInScope1 -- Can happen if 'f' is bound twice in the module
1810 -- Eg f = True; g = 0; f = False
1811 where
1812 is_name :: Name -> Bool
1813 is_name name = ASSERT2( isExternalName name, ppr name )
1814 nameModule name == mod && nameOccName name == occ
1815
1816 forceUnqualNames :: [Name]
1817 forceUnqualNames =
1818 map tyConName [ constraintKindTyCon, heqTyCon, coercibleTyCon
1819 , starKindTyCon, unicodeStarKindTyCon ]
1820 ++ [ eqTyConName ]
1821
1822 right_name gre = nameModule_maybe (gre_name gre) == Just mod
1823
1824 unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
1825 qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
1826
1827 -- we can mention a module P:M without the P: qualifier iff
1828 -- "import M" would resolve unambiguously to P:M. (if P is the
1829 -- current package we can just assume it is unqualified).
1830
1831 -- | Creates a function for formatting modules based on two heuristics:
1832 -- (1) if the module is the current module, don't qualify, and (2) if there
1833 -- is only one exposed package which exports this module, don't qualify.
1834 mkQualModule :: DynFlags -> QueryQualifyModule
1835 mkQualModule dflags mod
1836 | moduleUnitId mod == thisPackage dflags = False
1837
1838 | [(_, pkgconfig)] <- lookup,
1839 packageConfigId pkgconfig == moduleUnitId mod
1840 -- this says: we are given a module P:M, is there just one exposed package
1841 -- that exposes a module M, and is it package P?
1842 = False
1843
1844 | otherwise = True
1845 where lookup = lookupModuleInAllPackages dflags (moduleName mod)
1846
1847 -- | Creates a function for formatting packages based on two heuristics:
1848 -- (1) don't qualify if the package in question is "main", and (2) only qualify
1849 -- with a unit id if the package ID would be ambiguous.
1850 mkQualPackage :: DynFlags -> QueryQualifyPackage
1851 mkQualPackage dflags pkg_key
1852 | pkg_key == mainUnitId || pkg_key == interactiveUnitId
1853 -- Skip the lookup if it's main, since it won't be in the package
1854 -- database!
1855 = False
1856 | Just pkgid <- mb_pkgid
1857 , searchPackageId dflags pkgid `lengthIs` 1
1858 -- this says: we are given a package pkg-0.1@MMM, are there only one
1859 -- exposed packages whose package ID is pkg-0.1?
1860 = False
1861 | otherwise
1862 = True
1863 where mb_pkgid = fmap sourcePackageId (lookupPackage dflags pkg_key)
1864
1865 -- | A function which only qualifies package names if necessary; but
1866 -- qualifies all other identifiers.
1867 pkgQual :: DynFlags -> PrintUnqualified
1868 pkgQual dflags = alwaysQualify {
1869 queryQualifyPackage = mkQualPackage dflags
1870 }
1871
1872 {-
1873 ************************************************************************
1874 * *
1875 Implicit TyThings
1876 * *
1877 ************************************************************************
1878
1879 Note [Implicit TyThings]
1880 ~~~~~~~~~~~~~~~~~~~~~~~~
1881 DEFINITION: An "implicit" TyThing is one that does not have its own
1882 IfaceDecl in an interface file. Instead, its binding in the type
1883 environment is created as part of typechecking the IfaceDecl for
1884 some other thing.
1885
1886 Examples:
1887 * All DataCons are implicit, because they are generated from the
1888 IfaceDecl for the data/newtype. Ditto class methods.
1889
1890 * Record selectors are *not* implicit, because they get their own
1891 free-standing IfaceDecl.
1892
1893 * Associated data/type families are implicit because they are
1894 included in the IfaceDecl of the parent class. (NB: the
1895 IfaceClass decl happens to use IfaceDecl recursively for the
1896 associated types, but that's irrelevant here.)
1897
1898 * Dictionary function Ids are not implicit.
1899
1900 * Axioms for newtypes are implicit (same as above), but axioms
1901 for data/type family instances are *not* implicit (like DFunIds).
1902 -}
1903
1904 -- | Determine the 'TyThing's brought into scope by another 'TyThing'
1905 -- /other/ than itself. For example, Id's don't have any implicit TyThings
1906 -- as they just bring themselves into scope, but classes bring their
1907 -- dictionary datatype, type constructor and some selector functions into
1908 -- scope, just for a start!
1909
1910 -- N.B. the set of TyThings returned here *must* match the set of
1911 -- names returned by LoadIface.ifaceDeclImplicitBndrs, in the sense that
1912 -- TyThing.getOccName should define a bijection between the two lists.
1913 -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
1914 -- The order of the list does not matter.
1915 implicitTyThings :: TyThing -> [TyThing]
1916 implicitTyThings (AnId _) = []
1917 implicitTyThings (ACoAxiom _cc) = []
1918 implicitTyThings (ATyCon tc) = implicitTyConThings tc
1919 implicitTyThings (AConLike cl) = implicitConLikeThings cl
1920
1921 implicitConLikeThings :: ConLike -> [TyThing]
1922 implicitConLikeThings (RealDataCon dc)
1923 = dataConImplicitTyThings dc
1924
1925 implicitConLikeThings (PatSynCon {})
1926 = [] -- Pattern synonyms have no implicit Ids; the wrapper and matcher
1927 -- are not "implicit"; they are simply new top-level bindings,
1928 -- and they have their own declaration in an interface file
1929 -- Unless a record pat syn when there are implicit selectors
1930 -- They are still not included here as `implicitConLikeThings` is
1931 -- used by `tcTyClsDecls` whilst pattern synonyms are typed checked
1932 -- by `tcTopValBinds`.
1933
1934 implicitClassThings :: Class -> [TyThing]
1935 implicitClassThings cl
1936 = -- Does not include default methods, because those Ids may have
1937 -- their own pragmas, unfoldings etc, not derived from the Class object
1938
1939 -- associated types
1940 -- No recursive call for the classATs, because they
1941 -- are only the family decls; they have no implicit things
1942 map ATyCon (classATs cl) ++
1943
1944 -- superclass and operation selectors
1945 map AnId (classAllSelIds cl)
1946
1947 implicitTyConThings :: TyCon -> [TyThing]
1948 implicitTyConThings tc
1949 = class_stuff ++
1950 -- fields (names of selectors)
1951
1952 -- (possibly) implicit newtype axioms
1953 -- or type family axioms
1954 implicitCoTyCon tc ++
1955
1956 -- for each data constructor in order,
1957 -- the constructor, worker, and (possibly) wrapper
1958 [ thing | dc <- tyConDataCons tc
1959 , thing <- AConLike (RealDataCon dc) : dataConImplicitTyThings dc ]
1960 -- NB. record selectors are *not* implicit, they have fully-fledged
1961 -- bindings that pass through the compilation pipeline as normal.
1962 where
1963 class_stuff = case tyConClass_maybe tc of
1964 Nothing -> []
1965 Just cl -> implicitClassThings cl
1966
1967 -- For newtypes and closed type families (only) add the implicit coercion tycon
1968 implicitCoTyCon :: TyCon -> [TyThing]
1969 implicitCoTyCon tc
1970 | Just co <- newTyConCo_maybe tc = [ACoAxiom $ toBranchedAxiom co]
1971 | Just co <- isClosedSynFamilyTyConWithAxiom_maybe tc
1972 = [ACoAxiom co]
1973 | otherwise = []
1974
1975 -- | Returns @True@ if there should be no interface-file declaration
1976 -- for this thing on its own: either it is built-in, or it is part
1977 -- of some other declaration, or it is generated implicitly by some
1978 -- other declaration.
1979 isImplicitTyThing :: TyThing -> Bool
1980 isImplicitTyThing (AConLike cl) = case cl of
1981 RealDataCon {} -> True
1982 PatSynCon {} -> False
1983 isImplicitTyThing (AnId id) = isImplicitId id
1984 isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
1985 isImplicitTyThing (ACoAxiom ax) = isImplicitCoAxiom ax
1986
1987 -- | tyThingParent_maybe x returns (Just p)
1988 -- when pprTyThingInContext should print a declaration for p
1989 -- (albeit with some "..." in it) when asked to show x
1990 -- It returns the *immediate* parent. So a datacon returns its tycon
1991 -- but the tycon could be the associated type of a class, so it in turn
1992 -- might have a parent.
1993 tyThingParent_maybe :: TyThing -> Maybe TyThing
1994 tyThingParent_maybe (AConLike cl) = case cl of
1995 RealDataCon dc -> Just (ATyCon (dataConTyCon dc))
1996 PatSynCon{} -> Nothing
1997 tyThingParent_maybe (ATyCon tc) = case tyConAssoc_maybe tc of
1998 Just cls -> Just (ATyCon (classTyCon cls))
1999 Nothing -> Nothing
2000 tyThingParent_maybe (AnId id) = case idDetails id of
2001 RecSelId { sel_tycon = RecSelData tc } ->
2002 Just (ATyCon tc)
2003 ClassOpId cls ->
2004 Just (ATyCon (classTyCon cls))
2005 _other -> Nothing
2006 tyThingParent_maybe _other = Nothing
2007
2008 tyThingsTyCoVars :: [TyThing] -> TyCoVarSet
2009 tyThingsTyCoVars tts =
2010 unionVarSets $ map ttToVarSet tts
2011 where
2012 ttToVarSet (AnId id) = tyCoVarsOfType $ idType id
2013 ttToVarSet (AConLike cl) = case cl of
2014 RealDataCon dc -> tyCoVarsOfType $ dataConRepType dc
2015 PatSynCon{} -> emptyVarSet
2016 ttToVarSet (ATyCon tc)
2017 = case tyConClass_maybe tc of
2018 Just cls -> (mkVarSet . fst . classTvsFds) cls
2019 Nothing -> tyCoVarsOfType $ tyConKind tc
2020 ttToVarSet (ACoAxiom _) = emptyVarSet
2021
2022 -- | The Names that a TyThing should bring into scope. Used to build
2023 -- the GlobalRdrEnv for the InteractiveContext.
2024 tyThingAvailInfo :: TyThing -> [AvailInfo]
2025 tyThingAvailInfo (ATyCon t)
2026 = case tyConClass_maybe t of
2027 Just c -> [AvailTC n (n : map getName (classMethods c)
2028 ++ map getName (classATs c))
2029 [] ]
2030 where n = getName c
2031 Nothing -> [AvailTC n (n : map getName dcs) flds]
2032 where n = getName t
2033 dcs = tyConDataCons t
2034 flds = tyConFieldLabels t
2035 tyThingAvailInfo (AConLike (PatSynCon p))
2036 = map avail ((getName p) : map flSelector (patSynFieldLabels p))
2037 tyThingAvailInfo t
2038 = [avail (getName t)]
2039
2040 {-
2041 ************************************************************************
2042 * *
2043 TypeEnv
2044 * *
2045 ************************************************************************
2046 -}
2047
2048 -- | A map from 'Name's to 'TyThing's, constructed by typechecking
2049 -- local declarations or interface files
2050 type TypeEnv = NameEnv TyThing
2051
2052 emptyTypeEnv :: TypeEnv
2053 typeEnvElts :: TypeEnv -> [TyThing]
2054 typeEnvTyCons :: TypeEnv -> [TyCon]
2055 typeEnvCoAxioms :: TypeEnv -> [CoAxiom Branched]
2056 typeEnvIds :: TypeEnv -> [Id]
2057 typeEnvPatSyns :: TypeEnv -> [PatSyn]
2058 typeEnvDataCons :: TypeEnv -> [DataCon]
2059 typeEnvClasses :: TypeEnv -> [Class]
2060 lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
2061
2062 emptyTypeEnv = emptyNameEnv
2063 typeEnvElts env = nameEnvElts env
2064 typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
2065 typeEnvCoAxioms env = [ax | ACoAxiom ax <- typeEnvElts env]
2066 typeEnvIds env = [id | AnId id <- typeEnvElts env]
2067 typeEnvPatSyns env = [ps | AConLike (PatSynCon ps) <- typeEnvElts env]
2068 typeEnvDataCons env = [dc | AConLike (RealDataCon dc) <- typeEnvElts env]
2069 typeEnvClasses env = [cl | tc <- typeEnvTyCons env,
2070 Just cl <- [tyConClass_maybe tc]]
2071
2072 mkTypeEnv :: [TyThing] -> TypeEnv
2073 mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
2074
2075 mkTypeEnvWithImplicits :: [TyThing] -> TypeEnv
2076 mkTypeEnvWithImplicits things =
2077 mkTypeEnv things
2078 `plusNameEnv`
2079 mkTypeEnv (concatMap implicitTyThings things)
2080
2081 typeEnvFromEntities :: [Id] -> [TyCon] -> [FamInst] -> TypeEnv
2082 typeEnvFromEntities ids tcs famInsts =
2083 mkTypeEnv ( map AnId ids
2084 ++ map ATyCon all_tcs
2085 ++ concatMap implicitTyConThings all_tcs
2086 ++ map (ACoAxiom . toBranchedAxiom . famInstAxiom) famInsts
2087 )
2088 where
2089 all_tcs = tcs ++ famInstsRepTyCons famInsts
2090
2091 lookupTypeEnv = lookupNameEnv
2092
2093 -- Extend the type environment
2094 extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
2095 extendTypeEnv env thing = extendNameEnv env (getName thing) thing
2096
2097 extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
2098 extendTypeEnvList env things = foldl extendTypeEnv env things
2099
2100 extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
2101 extendTypeEnvWithIds env ids
2102 = extendNameEnvList env [(getName id, AnId id) | id <- ids]
2103
2104 plusTypeEnv :: TypeEnv -> TypeEnv -> TypeEnv
2105 plusTypeEnv env1 env2 = plusNameEnv env1 env2
2106
2107 -- | Find the 'TyThing' for the given 'Name' by using all the resources
2108 -- at our disposal: the compiled modules in the 'HomePackageTable' and the
2109 -- compiled modules in other packages that live in 'PackageTypeEnv'. Note
2110 -- that this does NOT look up the 'TyThing' in the module being compiled: you
2111 -- have to do that yourself, if desired
2112 lookupType :: DynFlags
2113 -> HomePackageTable
2114 -> PackageTypeEnv
2115 -> Name
2116 -> Maybe TyThing
2117
2118 lookupType dflags hpt pte name
2119 | isOneShot (ghcMode dflags) -- in one-shot, we don't use the HPT
2120 = lookupNameEnv pte name
2121 | otherwise
2122 = case lookupHptByModule hpt mod of
2123 Just hm -> lookupNameEnv (md_types (hm_details hm)) name
2124 Nothing -> lookupNameEnv pte name
2125 where
2126 mod = ASSERT2( isExternalName name, ppr name )
2127 if isHoleName name
2128 then mkModule (thisPackage dflags) (moduleName (nameModule name))
2129 else nameModule name
2130
2131 -- | As 'lookupType', but with a marginally easier-to-use interface
2132 -- if you have a 'HscEnv'
2133 lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
2134 lookupTypeHscEnv hsc_env name = do
2135 eps <- readIORef (hsc_EPS hsc_env)
2136 return $! lookupType dflags hpt (eps_PTE eps) name
2137 where
2138 dflags = hsc_dflags hsc_env
2139 hpt = hsc_HPT hsc_env
2140
2141 -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
2142 tyThingTyCon :: TyThing -> TyCon
2143 tyThingTyCon (ATyCon tc) = tc
2144 tyThingTyCon other = pprPanic "tyThingTyCon" (ppr other)
2145
2146 -- | Get the 'CoAxiom' from a 'TyThing' if it is a coercion axiom thing. Panics otherwise
2147 tyThingCoAxiom :: TyThing -> CoAxiom Branched
2148 tyThingCoAxiom (ACoAxiom ax) = ax
2149 tyThingCoAxiom other = pprPanic "tyThingCoAxiom" (ppr other)
2150
2151 -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
2152 tyThingDataCon :: TyThing -> DataCon
2153 tyThingDataCon (AConLike (RealDataCon dc)) = dc
2154 tyThingDataCon other = pprPanic "tyThingDataCon" (ppr other)
2155
2156 -- | Get the 'ConLike' from a 'TyThing' if it is a data constructor thing.
2157 -- Panics otherwise
2158 tyThingConLike :: TyThing -> ConLike
2159 tyThingConLike (AConLike dc) = dc
2160 tyThingConLike other = pprPanic "tyThingConLike" (ppr other)
2161
2162 -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
2163 tyThingId :: TyThing -> Id
2164 tyThingId (AnId id) = id
2165 tyThingId (AConLike (RealDataCon dc)) = dataConWrapId dc
2166 tyThingId other = pprPanic "tyThingId" (ppr other)
2167
2168 {-
2169 ************************************************************************
2170 * *
2171 \subsection{MonadThings and friends}
2172 * *
2173 ************************************************************************
2174 -}
2175
2176 -- | Class that abstracts out the common ability of the monads in GHC
2177 -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
2178 -- a number of related convenience functions for accessing particular
2179 -- kinds of 'TyThing'
2180 class Monad m => MonadThings m where
2181 lookupThing :: Name -> m TyThing
2182
2183 lookupId :: Name -> m Id
2184 lookupId = liftM tyThingId . lookupThing
2185
2186 lookupDataCon :: Name -> m DataCon
2187 lookupDataCon = liftM tyThingDataCon . lookupThing
2188
2189 lookupTyCon :: Name -> m TyCon
2190 lookupTyCon = liftM tyThingTyCon . lookupThing
2191
2192 {-
2193 ************************************************************************
2194 * *
2195 \subsection{Auxiliary types}
2196 * *
2197 ************************************************************************
2198
2199 These types are defined here because they are mentioned in ModDetails,
2200 but they are mostly elaborated elsewhere
2201 -}
2202
2203 ------------------ Warnings -------------------------
2204 -- | Warning information for a module
2205 data Warnings
2206 = NoWarnings -- ^ Nothing deprecated
2207 | WarnAll WarningTxt -- ^ Whole module deprecated
2208 | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
2209
2210 -- Only an OccName is needed because
2211 -- (1) a deprecation always applies to a binding
2212 -- defined in the module in which the deprecation appears.
2213 -- (2) deprecations are only reported outside the defining module.
2214 -- this is important because, otherwise, if we saw something like
2215 --
2216 -- {-# DEPRECATED f "" #-}
2217 -- f = ...
2218 -- h = f
2219 -- g = let f = undefined in f
2220 --
2221 -- we'd need more information than an OccName to know to say something
2222 -- about the use of f in h but not the use of the locally bound f in g
2223 --
2224 -- however, because we only report about deprecations from the outside,
2225 -- and a module can only export one value called f,
2226 -- an OccName suffices.
2227 --
2228 -- this is in contrast with fixity declarations, where we need to map
2229 -- a Name to its fixity declaration.
2230 deriving( Eq )
2231
2232 instance Binary Warnings where
2233 put_ bh NoWarnings = putByte bh 0
2234 put_ bh (WarnAll t) = do
2235 putByte bh 1
2236 put_ bh t
2237 put_ bh (WarnSome ts) = do
2238 putByte bh 2
2239 put_ bh ts
2240
2241 get bh = do
2242 h <- getByte bh
2243 case h of
2244 0 -> return NoWarnings
2245 1 -> do aa <- get bh
2246 return (WarnAll aa)
2247 _ -> do aa <- get bh
2248 return (WarnSome aa)
2249
2250 -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
2251 mkIfaceWarnCache :: Warnings -> OccName -> Maybe WarningTxt
2252 mkIfaceWarnCache NoWarnings = \_ -> Nothing
2253 mkIfaceWarnCache (WarnAll t) = \_ -> Just t
2254 mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs)
2255
2256 emptyIfaceWarnCache :: OccName -> Maybe WarningTxt
2257 emptyIfaceWarnCache _ = Nothing
2258
2259 plusWarns :: Warnings -> Warnings -> Warnings
2260 plusWarns d NoWarnings = d
2261 plusWarns NoWarnings d = d
2262 plusWarns _ (WarnAll t) = WarnAll t
2263 plusWarns (WarnAll t) _ = WarnAll t
2264 plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
2265
2266 -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
2267 mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Maybe Fixity
2268 mkIfaceFixCache pairs
2269 = \n -> lookupOccEnv env n
2270 where
2271 env = mkOccEnv pairs
2272
2273 emptyIfaceFixCache :: OccName -> Maybe Fixity
2274 emptyIfaceFixCache _ = Nothing
2275
2276 -- | Fixity environment mapping names to their fixities
2277 type FixityEnv = NameEnv FixItem
2278
2279 -- | Fixity information for an 'Name'. We keep the OccName in the range
2280 -- so that we can generate an interface from it
2281 data FixItem = FixItem OccName Fixity
2282
2283 instance Outputable FixItem where
2284 ppr (FixItem occ fix) = ppr fix <+> ppr occ
2285
2286 emptyFixityEnv :: FixityEnv
2287 emptyFixityEnv = emptyNameEnv
2288
2289 lookupFixity :: FixityEnv -> Name -> Fixity
2290 lookupFixity env n = case lookupNameEnv env n of
2291 Just (FixItem _ fix) -> fix
2292 Nothing -> defaultFixity
2293
2294 {-
2295 ************************************************************************
2296 * *
2297 \subsection{WhatsImported}
2298 * *
2299 ************************************************************************
2300 -}
2301
2302 -- | Records whether a module has orphans. An \"orphan\" is one of:
2303 --
2304 -- * An instance declaration in a module other than the definition
2305 -- module for one of the type constructors or classes in the instance head
2306 --
2307 -- * A transformation rule in a module other than the one defining
2308 -- the function in the head of the rule
2309 --
2310 -- * A vectorisation pragma
2311 type WhetherHasOrphans = Bool
2312
2313 -- | Does this module define family instances?
2314 type WhetherHasFamInst = Bool
2315
2316 -- | Did this module originate from a *-boot file?
2317 type IsBootInterface = Bool
2318
2319 -- | Dependency information about ALL modules and packages below this one
2320 -- in the import hierarchy.
2321 --
2322 -- Invariant: the dependencies of a module @M@ never includes @M@.
2323 --
2324 -- Invariant: none of the lists contain duplicates.
2325 data Dependencies
2326 = Deps { dep_mods :: [(ModuleName, IsBootInterface)]
2327 -- ^ All home-package modules transitively below this one
2328 -- I.e. modules that this one imports, or that are in the
2329 -- dep_mods of those directly-imported modules
2330
2331 , dep_pkgs :: [(InstalledUnitId, Bool)]
2332 -- ^ All packages transitively below this module
2333 -- I.e. packages to which this module's direct imports belong,
2334 -- or that are in the dep_pkgs of those modules
2335 -- The bool indicates if the package is required to be
2336 -- trusted when the module is imported as a safe import
2337 -- (Safe Haskell). See Note [RnNames . Tracking Trust Transitively]
2338
2339 , dep_orphs :: [Module]
2340 -- ^ Transitive closure of orphan modules (whether
2341 -- home or external pkg).
2342 --
2343 -- (Possible optimization: don't include family
2344 -- instance orphans as they are anyway included in
2345 -- 'dep_finsts'. But then be careful about code
2346 -- which relies on dep_orphs having the complete list!)
2347 -- This does NOT include us, unlike 'imp_orphs'.
2348
2349 , dep_finsts :: [Module]
2350 -- ^ Transitive closure of depended upon modules which
2351 -- contain family instances (whether home or external).
2352 -- This is used by 'checkFamInstConsistency'. This
2353 -- does NOT include us, unlike 'imp_finsts'. See Note
2354 -- [The type family instance consistency story].
2355 }
2356 deriving( Eq )
2357 -- Equality used only for old/new comparison in MkIface.addFingerprints
2358 -- See 'TcRnTypes.ImportAvails' for details on dependencies.
2359
2360 instance Binary Dependencies where
2361 put_ bh deps = do put_ bh (dep_mods deps)
2362 put_ bh (dep_pkgs deps)
2363 put_ bh (dep_orphs deps)
2364 put_ bh (dep_finsts deps)
2365
2366 get bh = do ms <- get bh
2367 ps <- get bh
2368 os <- get bh
2369 fis <- get bh
2370 return (Deps { dep_mods = ms, dep_pkgs = ps, dep_orphs = os,
2371 dep_finsts = fis })
2372
2373 noDependencies :: Dependencies
2374 noDependencies = Deps [] [] [] []
2375
2376 -- | Records modules for which changes may force recompilation of this module
2377 -- See wiki: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
2378 --
2379 -- This differs from Dependencies. A module X may be in the dep_mods of this
2380 -- module (via an import chain) but if we don't use anything from X it won't
2381 -- appear in our Usage
2382 data Usage
2383 -- | Module from another package
2384 = UsagePackageModule {
2385 usg_mod :: Module,
2386 -- ^ External package module depended on
2387 usg_mod_hash :: Fingerprint,
2388 -- ^ Cached module fingerprint
2389 usg_safe :: IsSafeImport
2390 -- ^ Was this module imported as a safe import
2391 }
2392 -- | Module from the current package
2393 | UsageHomeModule {
2394 usg_mod_name :: ModuleName,
2395 -- ^ Name of the module
2396 usg_mod_hash :: Fingerprint,
2397 -- ^ Cached module fingerprint
2398 usg_entities :: [(OccName,Fingerprint)],
2399 -- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
2400 -- NB: usages are for parent names only, e.g. type constructors
2401 -- but not the associated data constructors.
2402 usg_exports :: Maybe Fingerprint,
2403 -- ^ Fingerprint for the export list of this module,
2404 -- if we directly imported it (and hence we depend on its export list)
2405 usg_safe :: IsSafeImport
2406 -- ^ Was this module imported as a safe import
2407 } -- ^ Module from the current package
2408 -- | A file upon which the module depends, e.g. a CPP #include, or using TH's
2409 -- 'addDependentFile'
2410 | UsageFile {
2411 usg_file_path :: FilePath,
2412 -- ^ External file dependency. From a CPP #include or TH
2413 -- addDependentFile. Should be absolute.
2414 usg_file_hash :: Fingerprint
2415 -- ^ 'Fingerprint' of the file contents.
2416
2417 -- Note: We don't consider things like modification timestamps
2418 -- here, because there's no reason to recompile if the actual
2419 -- contents don't change. This previously lead to odd
2420 -- recompilation behaviors; see #8114
2421 }
2422 -- | A requirement which was merged into this one.
2423 | UsageMergedRequirement {
2424 usg_mod :: Module,
2425 usg_mod_hash :: Fingerprint
2426 }
2427 deriving( Eq )
2428 -- The export list field is (Just v) if we depend on the export list:
2429 -- i.e. we imported the module directly, whether or not we
2430 -- enumerated the things we imported, or just imported
2431 -- everything
2432 -- We need to recompile if M's exports change, because
2433 -- if the import was import M, we might now have a name clash
2434 -- in the importing module.
2435 -- if the import was import M(x) M might no longer export x
2436 -- The only way we don't depend on the export list is if we have
2437 -- import M()
2438 -- And of course, for modules that aren't imported directly we don't
2439 -- depend on their export lists
2440
2441 instance Binary Usage where
2442 put_ bh usg@UsagePackageModule{} = do
2443 putByte bh 0
2444 put_ bh (usg_mod usg)
2445 put_ bh (usg_mod_hash usg)
2446 put_ bh (usg_safe usg)
2447
2448 put_ bh usg@UsageHomeModule{} = do
2449 putByte bh 1
2450 put_ bh (usg_mod_name usg)
2451 put_ bh (usg_mod_hash usg)
2452 put_ bh (usg_exports usg)
2453 put_ bh (usg_entities usg)
2454 put_ bh (usg_safe usg)
2455
2456 put_ bh usg@UsageFile{} = do
2457 putByte bh 2
2458 put_ bh (usg_file_path usg)
2459 put_ bh (usg_file_hash usg)
2460
2461 put_ bh usg@UsageMergedRequirement{} = do
2462 putByte bh 3
2463 put_ bh (usg_mod usg)
2464 put_ bh (usg_mod_hash usg)
2465
2466 get bh = do
2467 h <- getByte bh
2468 case h of
2469 0 -> do
2470 nm <- get bh
2471 mod <- get bh
2472 safe <- get bh
2473 return UsagePackageModule { usg_mod = nm, usg_mod_hash = mod, usg_safe = safe }
2474 1 -> do
2475 nm <- get bh
2476 mod <- get bh
2477 exps <- get bh
2478 ents <- get bh
2479 safe <- get bh
2480 return UsageHomeModule { usg_mod_name = nm, usg_mod_hash = mod,
2481 usg_exports = exps, usg_entities = ents, usg_safe = safe }
2482 2 -> do
2483 fp <- get bh
2484 hash <- get bh
2485 return UsageFile { usg_file_path = fp, usg_file_hash = hash }
2486 3 -> do
2487 mod <- get bh
2488 hash <- get bh
2489 return UsageMergedRequirement { usg_mod = mod, usg_mod_hash = hash }
2490 i -> error ("Binary.get(Usage): " ++ show i)
2491
2492 {-
2493 ************************************************************************
2494 * *
2495 The External Package State
2496 * *
2497 ************************************************************************
2498 -}
2499
2500 type PackageTypeEnv = TypeEnv
2501 type PackageRuleBase = RuleBase
2502 type PackageInstEnv = InstEnv
2503 type PackageFamInstEnv = FamInstEnv
2504 type PackageVectInfo = VectInfo
2505 type PackageAnnEnv = AnnEnv
2506 type PackageCompleteMatchMap = CompleteMatchMap
2507
2508 -- | Information about other packages that we have slurped in by reading
2509 -- their interface files
2510 data ExternalPackageState
2511 = EPS {
2512 eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
2513 -- ^ In OneShot mode (only), home-package modules
2514 -- accumulate in the external package state, and are
2515 -- sucked in lazily. For these home-pkg modules
2516 -- (only) we need to record which are boot modules.
2517 -- We set this field after loading all the
2518 -- explicitly-imported interfaces, but before doing
2519 -- anything else
2520 --
2521 -- The 'ModuleName' part is not necessary, but it's useful for
2522 -- debug prints, and it's convenient because this field comes
2523 -- direct from 'TcRnTypes.imp_dep_mods'
2524
2525 eps_PIT :: !PackageIfaceTable,
2526 -- ^ The 'ModIface's for modules in external packages
2527 -- whose interfaces we have opened.
2528 -- The declarations in these interface files are held in the
2529 -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
2530 -- fields of this record, not in the 'mi_decls' fields of the
2531 -- interface we have sucked in.
2532 --
2533 -- What /is/ in the PIT is:
2534 --
2535 -- * The Module
2536 --
2537 -- * Fingerprint info
2538 --
2539 -- * Its exports
2540 --
2541 -- * Fixities
2542 --
2543 -- * Deprecations and warnings
2544
2545 eps_free_holes :: InstalledModuleEnv (UniqDSet ModuleName),
2546 -- ^ Cache for 'mi_free_holes'. Ordinarily, we can rely on
2547 -- the 'eps_PIT' for this information, EXCEPT that when
2548 -- we do dependency analysis, we need to look at the
2549 -- 'Dependencies' of our imports to determine what their
2550 -- precise free holes are ('moduleFreeHolesPrecise'). We
2551 -- don't want to repeatedly reread in the interface
2552 -- for every import, so cache it here. When the PIT
2553 -- gets filled in we can drop these entries.
2554
2555 eps_PTE :: !PackageTypeEnv,
2556 -- ^ Result of typechecking all the external package
2557 -- interface files we have sucked in. The domain of
2558 -- the mapping is external-package modules
2559
2560 eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
2561 -- from all the external-package modules
2562 eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
2563 -- from all the external-package modules
2564 eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
2565 -- from all the external-package modules
2566 eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
2567 -- from all the external-package modules
2568 eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
2569 -- from all the external-package modules
2570 eps_complete_matches :: !PackageCompleteMatchMap,
2571 -- ^ The total 'CompleteMatchMap' accumulated
2572 -- from all the external-package modules
2573
2574 eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
2575 -- packages, keyed off the module that declared them
2576
2577 eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
2578 }
2579
2580 -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
2581 -- \"In\" means stuff that is just /read/ from interface files,
2582 -- \"Out\" means actually sucked in and type-checked
2583 data EpsStats = EpsStats { n_ifaces_in
2584 , n_decls_in, n_decls_out
2585 , n_rules_in, n_rules_out
2586 , n_insts_in, n_insts_out :: !Int }
2587
2588 addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
2589 -- ^ Add stats for one newly-read interface
2590 addEpsInStats stats n_decls n_insts n_rules
2591 = stats { n_ifaces_in = n_ifaces_in stats + 1
2592 , n_decls_in = n_decls_in stats + n_decls
2593 , n_insts_in = n_insts_in stats + n_insts
2594 , n_rules_in = n_rules_in stats + n_rules }
2595
2596 {-
2597 Names in a NameCache are always stored as a Global, and have the SrcLoc
2598 of their binding locations.
2599
2600 Actually that's not quite right. When we first encounter the original
2601 name, we might not be at its binding site (e.g. we are reading an
2602 interface file); so we give it 'noSrcLoc' then. Later, when we find
2603 its binding site, we fix it up.
2604 -}
2605
2606 updNameCacheIO :: HscEnv
2607 -> (NameCache -> (NameCache, c)) -- The updating function
2608 -> IO c
2609 updNameCacheIO hsc_env upd_fn
2610 = atomicModifyIORef' (hsc_NC hsc_env) upd_fn
2611
2612 mkSOName :: Platform -> FilePath -> FilePath
2613 mkSOName platform root
2614 = case platformOS platform of
2615 OSMinGW32 -> root <.> soExt platform
2616 _ -> ("lib" ++ root) <.> soExt platform
2617
2618 mkHsSOName :: Platform -> FilePath -> FilePath
2619 mkHsSOName platform root = ("lib" ++ root) <.> soExt platform
2620
2621 soExt :: Platform -> FilePath
2622 soExt platform
2623 = case platformOS platform of
2624 OSDarwin -> "dylib"
2625 OSMinGW32 -> "dll"
2626 _ -> "so"
2627
2628 {-
2629 ************************************************************************
2630 * *
2631 The module graph and ModSummary type
2632 A ModSummary is a node in the compilation manager's
2633 dependency graph, and it's also passed to hscMain
2634 * *
2635 ************************************************************************
2636 -}
2637
2638 -- | A ModuleGraph contains all the nodes from the home package (only).
2639 -- There will be a node for each source module, plus a node for each hi-boot
2640 -- module.
2641 --
2642 -- The graph is not necessarily stored in topologically-sorted order. Use
2643 -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
2644 data ModuleGraph = ModuleGraph
2645 { mg_mss :: [ModSummary]
2646 , mg_non_boot :: ModuleEnv ModSummary
2647 -- a map of all non-boot ModSummaries keyed by Modules
2648 , mg_boot :: ModuleSet
2649 -- a set of boot Modules
2650 , mg_needs_th_or_qq :: !Bool
2651 -- does any of the modules in mg_mss require TemplateHaskell or
2652 -- QuasiQuotes?
2653 }
2654
2655 -- | Determines whether a set of modules requires Template Haskell or
2656 -- Quasi Quotes
2657 --
2658 -- Note that if the session's 'DynFlags' enabled Template Haskell when
2659 -- 'depanal' was called, then each module in the returned module graph will
2660 -- have Template Haskell enabled whether it is actually needed or not.
2661 needsTemplateHaskellOrQQ :: ModuleGraph -> Bool
2662 needsTemplateHaskellOrQQ mg = mg_needs_th_or_qq mg
2663
2664 -- | Map a function 'f' over all the 'ModSummaries'.
2665 -- To preserve invariants 'f' can't change the isBoot status.
2666 mapMG :: (ModSummary -> ModSummary) -> ModuleGraph -> ModuleGraph
2667 mapMG f mg@ModuleGraph{..} = mg
2668 { mg_mss = map f mg_mss
2669 , mg_non_boot = mapModuleEnv f mg_non_boot
2670 }
2671
2672 mgBootModules :: ModuleGraph -> ModuleSet
2673 mgBootModules ModuleGraph{..} = mg_boot
2674
2675 mgModSummaries :: ModuleGraph -> [ModSummary]
2676 mgModSummaries = mg_mss
2677
2678 mgElemModule :: ModuleGraph -> Module -> Bool
2679 mgElemModule ModuleGraph{..} m = elemModuleEnv m mg_non_boot
2680
2681 -- | Look up a ModSummary in the ModuleGraph
2682 mgLookupModule :: ModuleGraph -> Module -> Maybe ModSummary
2683 mgLookupModule ModuleGraph{..} m = lookupModuleEnv mg_non_boot m
2684
2685 emptyMG :: ModuleGraph
2686 emptyMG = ModuleGraph [] emptyModuleEnv emptyModuleSet False
2687
2688 isTemplateHaskellOrQQNonBoot :: ModSummary -> Bool
2689 isTemplateHaskellOrQQNonBoot ms =
2690 (xopt LangExt.TemplateHaskell (ms_hspp_opts ms)
2691 || xopt LangExt.QuasiQuotes (ms_hspp_opts ms)) &&
2692 not (isBootSummary ms)
2693
2694 -- | Add a ModSummary to ModuleGraph. Assumes that the new ModSummary is
2695 -- not an element of the ModuleGraph.
2696 extendMG :: ModuleGraph -> ModSummary -> ModuleGraph
2697 extendMG ModuleGraph{..} ms = ModuleGraph
2698 { mg_mss = ms:mg_mss
2699 , mg_non_boot = if isBootSummary ms
2700 then mg_non_boot
2701 else extendModuleEnv mg_non_boot (ms_mod ms) ms
2702 , mg_boot = if isBootSummary ms
2703 then extendModuleSet mg_boot (ms_mod ms)
2704 else mg_boot
2705 , mg_needs_th_or_qq = mg_needs_th_or_qq || isTemplateHaskellOrQQNonBoot ms
2706 }
2707
2708 mkModuleGraph :: [ModSummary] -> ModuleGraph
2709 mkModuleGraph = foldr (flip extendMG) emptyMG
2710
2711 -- | A single node in a 'ModuleGraph'. The nodes of the module graph
2712 -- are one of:
2713 --
2714 -- * A regular Haskell source module
2715 -- * A hi-boot source module
2716 --
2717 data ModSummary
2718 = ModSummary {
2719 ms_mod :: Module,
2720 -- ^ Identity of the module
2721 ms_hsc_src :: HscSource,
2722 -- ^ The module source either plain Haskell or hs-boot
2723 ms_location :: ModLocation,
2724 -- ^ Location of the various files belonging to the module
2725 ms_hs_date :: UTCTime,
2726 -- ^ Timestamp of source file
2727 ms_obj_date :: Maybe UTCTime,
2728 -- ^ Timestamp of object, if we have one
2729 ms_iface_date :: Maybe UTCTime,
2730 -- ^ Timestamp of hi file, if we *only* are typechecking (it is
2731 -- 'Nothing' otherwise.
2732 -- See Note [Recompilation checking in -fno-code mode] and #9243
2733 ms_srcimps :: [(Maybe FastString, Located ModuleName)],
2734 -- ^ Source imports of the module
2735 ms_textual_imps :: [(Maybe FastString, Located ModuleName)],
2736 -- ^ Non-source imports of the module from the module *text*
2737 ms_parsed_mod :: Maybe HsParsedModule,
2738 -- ^ The parsed, nonrenamed source, if we have it. This is also
2739 -- used to support "inline module syntax" in Backpack files.
2740 ms_hspp_file :: FilePath,
2741 -- ^ Filename of preprocessed source file
2742 ms_hspp_opts :: DynFlags,
2743 -- ^ Cached flags from @OPTIONS@, @INCLUDE@ and @LANGUAGE@
2744 -- pragmas in the modules source code
2745 ms_hspp_buf :: Maybe StringBuffer
2746 -- ^ The actual preprocessed source, if we have it
2747 }
2748
2749 ms_installed_mod :: ModSummary -> InstalledModule
2750 ms_installed_mod = fst . splitModuleInsts . ms_mod
2751
2752 ms_mod_name :: ModSummary -> ModuleName
2753 ms_mod_name = moduleName . ms_mod
2754
2755 ms_imps :: ModSummary -> [(Maybe FastString, Located ModuleName)]
2756 ms_imps ms =
2757 ms_textual_imps ms ++
2758 map mk_additional_import (dynFlagDependencies (ms_hspp_opts ms))
2759 where
2760 mk_additional_import mod_nm = (Nothing, noLoc mod_nm)
2761
2762 -- The ModLocation contains both the original source filename and the
2763 -- filename of the cleaned-up source file after all preprocessing has been
2764 -- done. The point is that the summariser will have to cpp/unlit/whatever
2765 -- all files anyway, and there's no point in doing this twice -- just
2766 -- park the result in a temp file, put the name of it in the location,
2767 -- and let @compile@ read from that file on the way back up.
2768
2769 -- The ModLocation is stable over successive up-sweeps in GHCi, wheres
2770 -- the ms_hs_date and imports can, of course, change
2771
2772 msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
2773 msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
2774 msHiFilePath ms = ml_hi_file (ms_location ms)
2775 msObjFilePath ms = ml_obj_file (ms_location ms)
2776
2777 -- | Did this 'ModSummary' originate from a hs-boot file?
2778 isBootSummary :: ModSummary -> Bool
2779 isBootSummary ms = ms_hsc_src ms == HsBootFile
2780
2781 instance Outputable ModSummary where
2782 ppr ms
2783 = sep [text "ModSummary {",
2784 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
2785 text "ms_mod =" <+> ppr (ms_mod ms)
2786 <> text (hscSourceString (ms_hsc_src ms)) <> comma,
2787 text "ms_textual_imps =" <+> ppr (ms_textual_imps ms),
2788 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
2789 char '}'
2790 ]
2791
2792 showModMsg :: DynFlags -> HscTarget -> Bool -> ModSummary -> String
2793 showModMsg dflags target recomp mod_summary = showSDoc dflags $
2794 if gopt Opt_HideSourcePaths dflags
2795 then text mod_str
2796 else hsep
2797 [ text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' ')
2798 , char '('
2799 , text (op $ msHsFilePath mod_summary) <> char ','
2800 , case target of
2801 HscInterpreted | recomp -> text "interpreted"
2802 HscNothing -> text "nothing"
2803 _ -> text (op $ msObjFilePath mod_summary)
2804 , char ')'
2805 ]
2806 where
2807 op = normalise
2808 mod = moduleName (ms_mod mod_summary)
2809 mod_str = showPpr dflags mod ++ hscSourceString (ms_hsc_src mod_summary)
2810
2811 {-
2812 ************************************************************************
2813 * *
2814 \subsection{Recmpilation}
2815 * *
2816 ************************************************************************
2817 -}
2818
2819 -- | Indicates whether a given module's source has been modified since it
2820 -- was last compiled.
2821 data SourceModified
2822 = SourceModified
2823 -- ^ the source has been modified
2824 | SourceUnmodified
2825 -- ^ the source has not been modified. Compilation may or may
2826 -- not be necessary, depending on whether any dependencies have
2827 -- changed since we last compiled.
2828 | SourceUnmodifiedAndStable
2829 -- ^ the source has not been modified, and furthermore all of
2830 -- its (transitive) dependencies are up to date; it definitely
2831 -- does not need to be recompiled. This is important for two
2832 -- reasons: (a) we can omit the version check in checkOldIface,
2833 -- and (b) if the module used TH splices we don't need to force
2834 -- recompilation.
2835
2836 {-
2837 ************************************************************************
2838 * *
2839 \subsection{Hpc Support}
2840 * *
2841 ************************************************************************
2842 -}
2843
2844 -- | Information about a modules use of Haskell Program Coverage
2845 data HpcInfo
2846 = HpcInfo
2847 { hpcInfoTickCount :: Int
2848 , hpcInfoHash :: Int
2849 }
2850 | NoHpcInfo
2851 { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
2852 }
2853
2854 -- | This is used to signal if one of my imports used HPC instrumentation
2855 -- even if there is no module-local HPC usage
2856 type AnyHpcUsage = Bool
2857
2858 emptyHpcInfo :: AnyHpcUsage -> HpcInfo
2859 emptyHpcInfo = NoHpcInfo
2860
2861 -- | Find out if HPC is used by this module or any of the modules
2862 -- it depends upon
2863 isHpcUsed :: HpcInfo -> AnyHpcUsage
2864 isHpcUsed (HpcInfo {}) = True
2865 isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
2866
2867 {-
2868 ************************************************************************
2869 * *
2870 \subsection{Vectorisation Support}
2871 * *
2872 ************************************************************************
2873
2874 The following information is generated and consumed by the vectorisation
2875 subsystem. It communicates the vectorisation status of declarations from one
2876 module to another.
2877
2878 Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
2879 below? We need to know `f' when converting to IfaceVectInfo. However, during
2880 vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
2881 on just the OccName easily in a Core pass.
2882 -}
2883
2884 -- |Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'; see also
2885 -- documentation at 'Vectorise.Env.GlobalEnv'.
2886 --
2887 -- NB: The following tables may also include 'Var's, 'TyCon's and 'DataCon's from imported modules,
2888 -- which have been subsequently vectorised in the current module.
2889 --
2890 data VectInfo
2891 = VectInfo
2892 { vectInfoVar :: DVarEnv (Var , Var ) -- ^ @(f, f_v)@ keyed on @f@
2893 , vectInfoTyCon :: NameEnv (TyCon , TyCon) -- ^ @(T, T_v)@ keyed on @T@
2894 , vectInfoDataCon :: NameEnv (DataCon, DataCon) -- ^ @(C, C_v)@ keyed on @C@
2895 , vectInfoParallelVars :: DVarSet -- ^ set of parallel variables
2896 , vectInfoParallelTyCons :: NameSet -- ^ set of parallel type constructors
2897 }
2898
2899 -- |Vectorisation information for 'ModIface'; i.e, the vectorisation information propagated
2900 -- across module boundaries.
2901 --
2902 -- NB: The field 'ifaceVectInfoVar' explicitly contains the workers of data constructors as well as
2903 -- class selectors — i.e., their mappings are /not/ implicitly generated from the data types.
2904 -- Moreover, whether the worker of a data constructor is in 'ifaceVectInfoVar' determines
2905 -- whether that data constructor was vectorised (or is part of an abstractly vectorised type
2906 -- constructor).
2907 --
2908 data IfaceVectInfo
2909 = IfaceVectInfo
2910 { ifaceVectInfoVar :: [Name] -- ^ All variables in here have a vectorised variant
2911 , ifaceVectInfoTyCon :: [Name] -- ^ All 'TyCon's in here have a vectorised variant;
2912 -- the name of the vectorised variant and those of its
2913 -- data constructors are determined by
2914 -- 'OccName.mkVectTyConOcc' and
2915 -- 'OccName.mkVectDataConOcc'; the names of the
2916 -- isomorphisms are determined by 'OccName.mkVectIsoOcc'
2917 , ifaceVectInfoTyConReuse :: [Name] -- ^ The vectorised form of all the 'TyCon's in here
2918 -- coincides with the unconverted form; the name of the
2919 -- isomorphisms is determined by 'OccName.mkVectIsoOcc'
2920 , ifaceVectInfoParallelVars :: [Name] -- iface version of 'vectInfoParallelVar'
2921 , ifaceVectInfoParallelTyCons :: [Name] -- iface version of 'vectInfoParallelTyCon'
2922 }
2923
2924 noVectInfo :: VectInfo
2925 noVectInfo
2926 = VectInfo emptyDVarEnv emptyNameEnv emptyNameEnv emptyDVarSet emptyNameSet
2927
2928 plusVectInfo :: VectInfo -> VectInfo -> VectInfo
2929 plusVectInfo vi1 vi2 =
2930 VectInfo (vectInfoVar vi1 `plusDVarEnv` vectInfoVar vi2)
2931 (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
2932 (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
2933 (vectInfoParallelVars vi1 `unionDVarSet` vectInfoParallelVars vi2)
2934 (vectInfoParallelTyCons vi1 `unionNameSet` vectInfoParallelTyCons vi2)
2935
2936 concatVectInfo :: [VectInfo] -> VectInfo
2937 concatVectInfo = foldr plusVectInfo noVectInfo
2938
2939 noIfaceVectInfo :: IfaceVectInfo
2940 noIfaceVectInfo = IfaceVectInfo [] [] [] [] []
2941
2942 isNoIfaceVectInfo :: IfaceVectInfo -> Bool
2943 isNoIfaceVectInfo (IfaceVectInfo l1 l2 l3 l4 l5)
2944 = null l1 && null l2 && null l3 && null l4 && null l5
2945
2946 instance Outputable VectInfo where
2947 ppr info = vcat
2948 [ text "variables :" <+> ppr (vectInfoVar info)
2949 , text "tycons :" <+> ppr (vectInfoTyCon info)
2950 , text "datacons :" <+> ppr (vectInfoDataCon info)
2951 , text "parallel vars :" <+> ppr (vectInfoParallelVars info)
2952 , text "parallel tycons :" <+> ppr (vectInfoParallelTyCons info)
2953 ]
2954
2955 instance Outputable IfaceVectInfo where
2956 ppr info = vcat
2957 [ text "variables :" <+> ppr (ifaceVectInfoVar info)
2958 , text "tycons :" <+> ppr (ifaceVectInfoTyCon info)
2959 , text "tycons reuse :" <+> ppr (ifaceVectInfoTyConReuse info)
2960 , text "parallel vars :" <+> ppr (ifaceVectInfoParallelVars info)
2961 , text "parallel tycons :" <+> ppr (ifaceVectInfoParallelTyCons info)
2962 ]
2963
2964
2965 instance Binary IfaceVectInfo where
2966 put_ bh (IfaceVectInfo a1 a2 a3 a4 a5) = do
2967 put_ bh a1
2968 put_ bh a2
2969 put_ bh a3
2970 put_ bh a4
2971 put_ bh a5
2972 get bh = do
2973 a1 <- get bh
2974 a2 <- get bh
2975 a3 <- get bh
2976 a4 <- get bh
2977 a5 <- get bh
2978 return (IfaceVectInfo a1 a2 a3 a4 a5)
2979
2980 {-
2981 ************************************************************************
2982 * *
2983 \subsection{Safe Haskell Support}
2984 * *
2985 ************************************************************************
2986
2987 This stuff here is related to supporting the Safe Haskell extension,
2988 primarily about storing under what trust type a module has been compiled.
2989 -}
2990
2991 -- | Is an import a safe import?
2992 type IsSafeImport = Bool
2993
2994 -- | Safe Haskell information for 'ModIface'
2995 -- Simply a wrapper around SafeHaskellMode to sepperate iface and flags
2996 newtype IfaceTrustInfo = TrustInfo SafeHaskellMode
2997
2998 getSafeMode :: IfaceTrustInfo -> SafeHaskellMode
2999 getSafeMode (TrustInfo x) = x
3000
3001 setSafeMode :: SafeHaskellMode -> IfaceTrustInfo
3002 setSafeMode = TrustInfo
3003
3004 noIfaceTrustInfo :: IfaceTrustInfo
3005 noIfaceTrustInfo = setSafeMode Sf_None
3006
3007 trustInfoToNum :: IfaceTrustInfo -> Word8
3008 trustInfoToNum it
3009 = case getSafeMode it of
3010 Sf_None -> 0
3011 Sf_Unsafe -> 1
3012 Sf_Trustworthy -> 2
3013 Sf_Safe -> 3
3014
3015 numToTrustInfo :: Word8 -> IfaceTrustInfo
3016 numToTrustInfo 0 = setSafeMode Sf_None
3017 numToTrustInfo 1 = setSafeMode Sf_Unsafe
3018 numToTrustInfo 2 = setSafeMode Sf_Trustworthy
3019 numToTrustInfo 3 = setSafeMode Sf_Safe
3020 numToTrustInfo 4 = setSafeMode Sf_Safe -- retained for backwards compat, used
3021 -- to be Sf_SafeInfered but we no longer
3022 -- differentiate.
3023 numToTrustInfo n = error $ "numToTrustInfo: bad input number! (" ++ show n ++ ")"
3024
3025 instance Outputable IfaceTrustInfo where
3026 ppr (TrustInfo Sf_None) = text "none"
3027 ppr (TrustInfo Sf_Unsafe) = text "unsafe"
3028 ppr (TrustInfo Sf_Trustworthy) = text "trustworthy"
3029 ppr (TrustInfo Sf_Safe) = text "safe"
3030
3031 instance Binary IfaceTrustInfo where
3032 put_ bh iftrust = putByte bh $ trustInfoToNum iftrust
3033 get bh = getByte bh >>= (return . numToTrustInfo)
3034
3035 {-
3036 ************************************************************************
3037 * *
3038 \subsection{Parser result}
3039 * *
3040 ************************************************************************
3041 -}
3042
3043 data HsParsedModule = HsParsedModule {
3044 hpm_module :: Located (HsModule GhcPs),
3045 hpm_src_files :: [FilePath],
3046 -- ^ extra source files (e.g. from #includes). The lexer collects
3047 -- these from '# <file> <line>' pragmas, which the C preprocessor
3048 -- leaves behind. These files and their timestamps are stored in
3049 -- the .hi file, so that we can force recompilation if any of
3050 -- them change (#3589)
3051 hpm_annotations :: ApiAnns
3052 -- See note [Api annotations] in ApiAnnotation.hs
3053 }
3054
3055 {-
3056 ************************************************************************
3057 * *
3058 \subsection{Linkable stuff}
3059 * *
3060 ************************************************************************
3061
3062 This stuff is in here, rather than (say) in Linker.hs, because the Linker.hs
3063 stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
3064 -}
3065
3066 -- | Information we can use to dynamically link modules into the compiler
3067 data Linkable = LM {
3068 linkableTime :: UTCTime, -- ^ Time at which this linkable was built
3069 -- (i.e. when the bytecodes were produced,
3070 -- or the mod date on the files)
3071 linkableModule :: Module, -- ^ The linkable module itself
3072 linkableUnlinked :: [Unlinked]
3073 -- ^ Those files and chunks of code we have yet to link.
3074 --
3075 -- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
3076 -- If this list is empty, the Linkable represents a fake linkable, which
3077 -- is generated in HscNothing mode to avoid recompiling modules.
3078 --
3079 -- ToDo: Do items get removed from this list when they get linked?
3080 }
3081
3082 isObjectLinkable :: Linkable -> Bool
3083 isObjectLinkable l = not (null unlinked) && all isObject unlinked
3084 where unlinked = linkableUnlinked l
3085 -- A linkable with no Unlinked's is treated as a BCO. We can
3086 -- generate a linkable with no Unlinked's as a result of
3087 -- compiling a module in HscNothing mode, and this choice
3088 -- happens to work well with checkStability in module GHC.
3089
3090 linkableObjs :: Linkable -> [FilePath]
3091 linkableObjs l = [ f | DotO f <- linkableUnlinked l ]
3092
3093 instance Outputable Linkable where
3094 ppr (LM when_made mod unlinkeds)
3095 = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
3096 $$ nest 3 (ppr unlinkeds)
3097
3098 -------------------------------------------
3099
3100 -- | Objects which have yet to be linked by the compiler
3101 data Unlinked
3102 = DotO FilePath -- ^ An object file (.o)
3103 | DotA FilePath -- ^ Static archive file (.a)
3104 | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
3105 | BCOs CompiledByteCode
3106 [SptEntry] -- ^ A byte-code object, lives only in memory. Also
3107 -- carries some static pointer table entries which
3108 -- should be loaded along with the BCOs.
3109 -- See Note [Grant plan for static forms] in
3110 -- StaticPtrTable.
3111
3112 instance Outputable Unlinked where
3113 ppr (DotO path) = text "DotO" <+> text path
3114 ppr (DotA path) = text "DotA" <+> text path
3115 ppr (DotDLL path) = text "DotDLL" <+> text path
3116 ppr (BCOs bcos spt) = text "BCOs" <+> ppr bcos <+> ppr spt
3117
3118 -- | Is this an actual file on disk we can link in somehow?
3119 isObject :: Unlinked -> Bool
3120 isObject (DotO _) = True
3121 isObject (DotA _) = True
3122 isObject (DotDLL _) = True
3123 isObject _ = False
3124
3125 -- | Is this a bytecode linkable with no file on disk?
3126 isInterpretable :: Unlinked -> Bool
3127 isInterpretable = not . isObject
3128
3129 -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
3130 nameOfObject :: Unlinked -> FilePath
3131 nameOfObject (DotO fn) = fn
3132 nameOfObject (DotA fn) = fn
3133 nameOfObject (DotDLL fn) = fn
3134 nameOfObject other = pprPanic "nameOfObject" (ppr other)
3135
3136 -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
3137 byteCodeOfObject :: Unlinked -> CompiledByteCode
3138 byteCodeOfObject (BCOs bc _) = bc
3139 byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
3140
3141
3142 -------------------------------------------
3143
3144 -- | A list of conlikes which represents a complete pattern match.
3145 -- These arise from @COMPLETE@ signatures.
3146
3147 -- See Note [Implementation of COMPLETE signatures]
3148 data CompleteMatch = CompleteMatch {
3149 completeMatchConLikes :: [Name]
3150 -- ^ The ConLikes that form a covering family
3151 -- (e.g. Nothing, Just)
3152 , completeMatchTyCon :: Name
3153 -- ^ The TyCon that they cover (e.g. Maybe)
3154 }
3155
3156 instance Outputable CompleteMatch where
3157 ppr (CompleteMatch cl ty) = text "CompleteMatch:" <+> ppr cl
3158 <+> dcolon <+> ppr ty
3159
3160 -- | A map keyed by the 'completeMatchTyCon'.
3161
3162 -- See Note [Implementation of COMPLETE signatures]
3163 type CompleteMatchMap = UniqFM [CompleteMatch]
3164
3165 mkCompleteMatchMap :: [CompleteMatch] -> CompleteMatchMap
3166 mkCompleteMatchMap = extendCompleteMatchMap emptyUFM
3167
3168 extendCompleteMatchMap :: CompleteMatchMap -> [CompleteMatch]
3169 -> CompleteMatchMap
3170 extendCompleteMatchMap = foldl' insertMatch
3171 where
3172 insertMatch :: CompleteMatchMap -> CompleteMatch -> CompleteMatchMap
3173 insertMatch ufm c@(CompleteMatch _ t) = addToUFM_C (++) ufm t [c]
3174
3175 {-
3176 Note [Implementation of COMPLETE signatures]
3177 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3178 A COMPLETE signature represents a set of conlikes (i.e., constructors or
3179 pattern synonyms) such that if they are all pattern-matched against in a
3180 function, it gives rise to a total function. An example is:
3181
3182 newtype Boolean = Boolean Int
3183 pattern F, T :: Boolean
3184 pattern F = Boolean 0
3185 pattern T = Boolean 1
3186 {-# COMPLETE F, T #-}
3187
3188 -- This is a total function
3189 booleanToInt :: Boolean -> Int
3190 booleanToInt F = 0
3191 booleanToInt T = 1
3192
3193 COMPLETE sets are represented internally in GHC with the CompleteMatch data
3194 type. For example, {-# COMPLETE F, T #-} would be represented as:
3195
3196 CompleteMatch { complateMatchConLikes = [F, T]
3197 , completeMatchTyCon = Boolean }
3198
3199 Note that GHC was able to infer the completeMatchTyCon (Boolean), but for the
3200 cases in which it's ambiguous, you can also explicitly specify it in the source
3201 language by writing this:
3202
3203 {-# COMPLETE F, T :: Boolean #-}
3204
3205 For efficiency purposes, GHC collects all of the CompleteMatches that it knows
3206 about into a CompleteMatchMap, which is a map that is keyed by the
3207 completeMatchTyCon. In other words, you could have a multiple COMPLETE sets
3208 for the same TyCon:
3209
3210 {-# COMPLETE F, T1 :: Boolean #-}
3211 {-# COMPLETE F, T2 :: Boolean #-}
3212
3213 And looking up the values in the CompleteMatchMap associated with Boolean
3214 would give you [CompleteMatch [F, T1] Boolean, CompleteMatch [F, T2] Boolean].
3215 dsGetCompleteMatches in DsMeta accomplishes this lookup.
3216
3217 Also see Note [Typechecking Complete Matches] in TcBinds for a more detailed
3218 explanation for how GHC ensures that all the conlikes in a COMPLETE set are
3219 consistent.
3220 -}