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