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