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