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