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