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