Make Core Lint check for locally-bound GlobalIds
[ghc.git] / compiler / main / HscMain.hs
1 {-# LANGUAGE BangPatterns, CPP, MagicHash, NondecreasingIndentation #-}
2
3 -------------------------------------------------------------------------------
4 --
5 -- | Main API for compiling plain Haskell source code.
6 --
7 -- This module implements compilation of a Haskell source. It is
8 -- /not/ concerned with preprocessing of source files; this is handled
9 -- in "DriverPipeline".
10 --
11 -- There are various entry points depending on what mode we're in:
12 -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
13 -- "interactive" mode (GHCi). There are also entry points for
14 -- individual passes: parsing, typechecking/renaming, desugaring, and
15 -- simplification.
16 --
17 -- All the functions here take an 'HscEnv' as a parameter, but none of
18 -- them return a new one: 'HscEnv' is treated as an immutable value
19 -- from here on in (although it has mutable components, for the
20 -- caches).
21 --
22 -- Warning messages are dealt with consistently throughout this API:
23 -- during compilation warnings are collected, and before any function
24 -- in @HscMain@ returns, the warnings are either printed, or turned
25 -- into a real compialtion error if the @-Werror@ flag is enabled.
26 --
27 -- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
28 --
29 -------------------------------------------------------------------------------
30
31 module HscMain
32 (
33 -- * Making an HscEnv
34 newHscEnv
35
36 -- * Compiling complete source files
37 , Messager, batchMsg
38 , HscStatus (..)
39 , hscCompileOneShot
40 , hscCompileCmmFile
41 , hscCompileCore
42
43 , genericHscCompileGetFrontendResult
44
45 , genModDetails
46 , hscSimpleIface
47 , hscWriteIface
48 , hscNormalIface
49 , hscGenHardCode
50 , hscInteractive
51
52 -- * Running passes separately
53 , hscParse
54 , hscTypecheckRename
55 , hscDesugar
56 , makeSimpleIface
57 , makeSimpleDetails
58 , hscSimplify -- ToDo, shouldn't really export this
59
60 -- * Support for interactive evaluation
61 , hscParseIdentifier
62 , hscTcRcLookupName
63 , hscTcRnGetInfo
64 , hscCheckSafe
65 , hscGetSafe
66 #ifdef GHCI
67 , hscIsGHCiMonad
68 , hscGetModuleInterface
69 , hscRnImportDecls
70 , hscTcRnLookupRdrName
71 , hscStmt, hscStmtWithLocation
72 , hscDecls, hscDeclsWithLocation
73 , hscTcExpr, hscImport, hscKcType
74 , hscCompileCoreExpr
75 -- * Low-level exports for hooks
76 , hscCompileCoreExpr'
77 #endif
78 -- We want to make sure that we export enough to be able to redefine
79 -- hscFileFrontEnd in client code
80 , hscParse', hscSimplify', hscDesugar', tcRnModule'
81 , getHscEnv
82 , hscSimpleIface', hscNormalIface'
83 , oneShotMsg
84 , hscFileFrontEnd, genericHscFrontend, dumpIfaceStats
85 ) where
86
87 #ifdef GHCI
88 import Id
89 import BasicTypes ( HValue )
90 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
91 import Linker
92 import CoreTidy ( tidyExpr )
93 import Type ( Type )
94 import PrelNames
95 import {- Kind parts of -} Type ( Kind )
96 import CoreLint ( lintInteractiveExpr )
97 import DsMeta ( templateHaskellNames )
98 import VarEnv ( emptyTidyEnv )
99 import Panic
100
101 import GHC.Exts
102 #endif
103
104 import Module
105 import Packages
106 import RdrName
107 import HsSyn
108 import CoreSyn
109 import StringBuffer
110 import Parser
111 import Lexer
112 import SrcLoc
113 import TcRnDriver
114 import TcIface ( typecheckIface )
115 import TcRnMonad
116 import IfaceEnv ( initNameCache )
117 import LoadIface ( ifaceStats, initExternalPackageState )
118 import PrelInfo
119 import MkIface
120 import Desugar
121 import SimplCore
122 import TidyPgm
123 import CorePrep
124 import CoreToStg ( coreToStg )
125 import qualified StgCmm ( codeGen )
126 import StgSyn
127 import CostCentre
128 import ProfInit
129 import TyCon
130 import Name
131 import SimplStg ( stg2stg )
132 import Cmm
133 import CmmParse ( parseCmmFile )
134 import CmmBuildInfoTables
135 import CmmPipeline
136 import CmmInfo
137 import CodeOutput
138 import NameEnv ( emptyNameEnv )
139 import NameSet ( emptyNameSet )
140 import InstEnv
141 import FamInstEnv
142 import Fingerprint ( Fingerprint )
143 import Hooks
144
145 import DynFlags
146 import ErrUtils
147
148 import Outputable
149 import HscStats ( ppSourceStats )
150 import HscTypes
151 import FastString
152 import UniqFM ( emptyUFM )
153 import UniqSupply
154 import Bag
155 import Exception
156 import qualified Stream
157 import Stream (Stream)
158
159 import Util
160
161 import Data.List
162 import Control.Monad
163 import Data.Maybe
164 import Data.IORef
165 import System.FilePath as FilePath
166 import System.Directory
167 import qualified Data.Map as Map
168
169 #include "HsVersions.h"
170
171
172 {- **********************************************************************
173 %* *
174 Initialisation
175 %* *
176 %********************************************************************* -}
177
178 newHscEnv :: DynFlags -> IO HscEnv
179 newHscEnv dflags = do
180 eps_var <- newIORef initExternalPackageState
181 us <- mkSplitUniqSupply 'r'
182 nc_var <- newIORef (initNameCache us knownKeyNames)
183 fc_var <- newIORef emptyUFM
184 mlc_var <- newIORef emptyModuleEnv
185 return HscEnv { hsc_dflags = dflags,
186 hsc_targets = [],
187 hsc_mod_graph = [],
188 hsc_IC = emptyInteractiveContext dflags,
189 hsc_HPT = emptyHomePackageTable,
190 hsc_EPS = eps_var,
191 hsc_NC = nc_var,
192 hsc_FC = fc_var,
193 hsc_MLC = mlc_var,
194 hsc_type_env_var = Nothing }
195
196
197 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
198 knownKeyNames = -- where templateHaskellNames are defined
199 map getName wiredInThings
200 ++ basicKnownKeyNames
201 #ifdef GHCI
202 ++ templateHaskellNames
203 #endif
204
205 -- -----------------------------------------------------------------------------
206
207 getWarnings :: Hsc WarningMessages
208 getWarnings = Hsc $ \_ w -> return (w, w)
209
210 clearWarnings :: Hsc ()
211 clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
212
213 logWarnings :: WarningMessages -> Hsc ()
214 logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
215
216 getHscEnv :: Hsc HscEnv
217 getHscEnv = Hsc $ \e w -> return (e, w)
218
219 handleWarnings :: Hsc ()
220 handleWarnings = do
221 dflags <- getDynFlags
222 w <- getWarnings
223 liftIO $ printOrThrowWarnings dflags w
224 clearWarnings
225
226 -- | log warning in the monad, and if there are errors then
227 -- throw a SourceError exception.
228 logWarningsReportErrors :: Messages -> Hsc ()
229 logWarningsReportErrors (warns,errs) = do
230 logWarnings warns
231 when (not $ isEmptyBag errs) $ throwErrors errs
232
233 -- | Throw some errors.
234 throwErrors :: ErrorMessages -> Hsc a
235 throwErrors = liftIO . throwIO . mkSrcErr
236
237 -- | Deal with errors and warnings returned by a compilation step
238 --
239 -- In order to reduce dependencies to other parts of the compiler, functions
240 -- outside the "main" parts of GHC return warnings and errors as a parameter
241 -- and signal success via by wrapping the result in a 'Maybe' type. This
242 -- function logs the returned warnings and propagates errors as exceptions
243 -- (of type 'SourceError').
244 --
245 -- This function assumes the following invariants:
246 --
247 -- 1. If the second result indicates success (is of the form 'Just x'),
248 -- there must be no error messages in the first result.
249 --
250 -- 2. If there are no error messages, but the second result indicates failure
251 -- there should be warnings in the first result. That is, if the action
252 -- failed, it must have been due to the warnings (i.e., @-Werror@).
253 ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
254 ioMsgMaybe ioA = do
255 ((warns,errs), mb_r) <- liftIO ioA
256 logWarnings warns
257 case mb_r of
258 Nothing -> throwErrors errs
259 Just r -> ASSERT( isEmptyBag errs ) return r
260
261 -- | like ioMsgMaybe, except that we ignore error messages and return
262 -- 'Nothing' instead.
263 ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
264 ioMsgMaybe' ioA = do
265 ((warns,_errs), mb_r) <- liftIO $ ioA
266 logWarnings warns
267 return mb_r
268
269 -- -----------------------------------------------------------------------------
270 -- | Lookup things in the compiler's environment
271
272 #ifdef GHCI
273 hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
274 hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do
275 hsc_env <- getHscEnv
276 ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
277 #endif
278
279 hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
280 hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
281 hsc_env <- getHscEnv
282 ioMsgMaybe' $ tcRnLookupName hsc_env name
283 -- ignore errors: the only error we're likely to get is
284 -- "name not found", and the Maybe in the return type
285 -- is used to indicate that.
286
287 hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
288 hscTcRnGetInfo hsc_env0 name
289 = runInteractiveHsc hsc_env0 $
290 do { hsc_env <- getHscEnv
291 ; ioMsgMaybe' $ tcRnGetInfo hsc_env name }
292
293 #ifdef GHCI
294 hscIsGHCiMonad :: HscEnv -> String -> IO Name
295 hscIsGHCiMonad hsc_env name
296 = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name
297
298 hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
299 hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
300 hsc_env <- getHscEnv
301 ioMsgMaybe $ getModuleInterface hsc_env mod
302
303 -- -----------------------------------------------------------------------------
304 -- | Rename some import declarations
305 hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
306 hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
307 hsc_env <- getHscEnv
308 ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
309 #endif
310
311 -- -----------------------------------------------------------------------------
312 -- | parse a file, returning the abstract syntax
313
314 hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
315 hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary
316
317 -- internal version, that doesn't fail due to -Werror
318 hscParse' :: ModSummary -> Hsc HsParsedModule
319 hscParse' mod_summary = do
320 dflags <- getDynFlags
321 let src_filename = ms_hspp_file mod_summary
322 maybe_src_buf = ms_hspp_buf mod_summary
323
324 -------------------------- Parser ----------------
325 liftIO $ showPass dflags "Parser"
326 {-# SCC "Parser" #-} do
327
328 -- sometimes we already have the buffer in memory, perhaps
329 -- because we needed to parse the imports out of it, or get the
330 -- module name.
331 buf <- case maybe_src_buf of
332 Just b -> return b
333 Nothing -> liftIO $ hGetStringBuffer src_filename
334
335 let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
336
337 case unP parseModule (mkPState dflags buf loc) of
338 PFailed span err ->
339 liftIO $ throwOneError (mkPlainErrMsg dflags span err)
340
341 POk pst rdr_module -> do
342 logWarningsReportErrors (getMessages pst)
343 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
344 ppr rdr_module
345 liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
346 ppSourceStats False rdr_module
347
348 -- To get the list of extra source files, we take the list
349 -- that the parser gave us,
350 -- - eliminate files beginning with '<'. gcc likes to use
351 -- pseudo-filenames like "<built-in>" and "<command-line>"
352 -- - normalise them (elimiante differences between ./f and f)
353 -- - filter out the preprocessed source file
354 -- - filter out anything beginning with tmpdir
355 -- - remove duplicates
356 -- - filter out the .hs/.lhs source filename if we have one
357 --
358 let n_hspp = FilePath.normalise src_filename
359 srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`))
360 $ filter (not . (== n_hspp))
361 $ map FilePath.normalise
362 $ filter (not . (isPrefixOf "<"))
363 $ map unpackFS
364 $ srcfiles pst
365 srcs1 = case ml_hs_file (ms_location mod_summary) of
366 Just f -> filter (/= FilePath.normalise f) srcs0
367 Nothing -> srcs0
368
369 -- sometimes we see source files from earlier
370 -- preprocessing stages that cannot be found, so just
371 -- filter them out:
372 srcs2 <- liftIO $ filterM doesFileExist srcs1
373
374 return HsParsedModule {
375 hpm_module = rdr_module,
376 hpm_src_files = srcs2,
377 hpm_annotations
378 = (Map.fromListWith (++) $ annotations pst,
379 Map.fromList $ ((noSrcSpan,comment_q pst)
380 :(annotations_comments pst)))
381 }
382
383 -- XXX: should this really be a Maybe X? Check under which circumstances this
384 -- can become a Nothing and decide whether this should instead throw an
385 -- exception/signal an error.
386 type RenamedStuff =
387 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
388 Maybe LHsDocString))
389
390 -- | Rename and typecheck a module, additionally returning the renamed syntax
391 hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
392 -> IO (TcGblEnv, RenamedStuff)
393 hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
394 tc_result <- tcRnModule' hsc_env mod_summary True rdr_module
395
396 -- This 'do' is in the Maybe monad!
397 let rn_info = do decl <- tcg_rn_decls tc_result
398 let imports = tcg_rn_imports tc_result
399 exports = tcg_rn_exports tc_result
400 doc_hdr = tcg_doc_hdr tc_result
401 return (decl,imports,exports,doc_hdr)
402
403 return (tc_result, rn_info)
404
405 -- wrapper around tcRnModule to handle safe haskell extras
406 tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule
407 -> Hsc TcGblEnv
408 tcRnModule' hsc_env sum save_rn_syntax mod = do
409 tcg_res <- {-# SCC "Typecheck-Rename" #-}
410 ioMsgMaybe $
411 tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod
412
413 tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_res)
414 dflags <- getDynFlags
415 let allSafeOK = safeInferred dflags && tcSafeOK
416
417 -- end of the safe haskell line, how to respond to user?
418 if not (safeHaskellOn dflags) || (safeInferOn dflags && not allSafeOK)
419 -- if safe Haskell off or safe infer failed, mark unsafe
420 then markUnsafeInfer tcg_res emptyBag
421
422 -- module (could be) safe, throw warning if needed
423 else do
424 tcg_res' <- hscCheckSafeImports tcg_res
425 safe <- liftIO $ readIORef (tcg_safeInfer tcg_res')
426 when safe $ do
427 case wopt Opt_WarnSafe dflags of
428 True -> (logWarnings $ unitBag $ mkPlainWarnMsg dflags
429 (warnSafeOnLoc dflags) $ errSafe tcg_res')
430 False | safeHaskell dflags == Sf_Trustworthy &&
431 wopt Opt_WarnTrustworthySafe dflags ->
432 (logWarnings $ unitBag $ mkPlainWarnMsg dflags
433 (trustworthyOnLoc dflags) $ errTwthySafe tcg_res')
434 False -> return ()
435 return tcg_res'
436 where
437 pprMod t = ppr $ moduleName $ tcg_mod t
438 errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
439 errTwthySafe t = quotes (pprMod t)
440 <+> text "is marked as Trustworthy but has been inferred as safe!"
441
442 -- | Convert a typechecked module to Core
443 hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
444 hscDesugar hsc_env mod_summary tc_result =
445 runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
446
447 hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
448 hscDesugar' mod_location tc_result = do
449 hsc_env <- getHscEnv
450 r <- ioMsgMaybe $
451 {-# SCC "deSugar" #-}
452 deSugar hsc_env mod_location tc_result
453
454 -- always check -Werror after desugaring, this is the last opportunity for
455 -- warnings to arise before the backend.
456 handleWarnings
457 return r
458
459 -- | Make a 'ModIface' from the results of typechecking. Used when
460 -- not optimising, and the interface doesn't need to contain any
461 -- unfoldings or other cross-module optimisation info.
462 -- ToDo: the old interface is only needed to get the version numbers,
463 -- we should use fingerprint versions instead.
464 makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
465 -> IO (ModIface,Bool)
466 makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do
467 safe_mode <- hscGetSafeMode tc_result
468 ioMsgMaybe $ do
469 mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode
470 details tc_result
471
472 -- | Make a 'ModDetails' from the results of typechecking. Used when
473 -- typechecking only, as opposed to full compilation.
474 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
475 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
476
477
478 {- **********************************************************************
479 %* *
480 The main compiler pipeline
481 %* *
482 %********************************************************************* -}
483
484 {-
485 --------------------------------
486 The compilation proper
487 --------------------------------
488
489 It's the task of the compilation proper to compile Haskell, hs-boot and core
490 files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
491 (the module is still parsed and type-checked. This feature is mostly used by
492 IDE's and the likes). Compilation can happen in either 'one-shot', 'batch',
493 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch'
494 mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
495 targets byte-code.
496
497 The modes are kept separate because of their different types and meanings:
498
499 * In 'one-shot' mode, we're only compiling a single file and can therefore
500 discard the new ModIface and ModDetails. This is also the reason it only
501 targets hard-code; compiling to byte-code or nothing doesn't make sense when
502 we discard the result.
503
504 * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
505 and ModDetails. 'Batch' mode doesn't target byte-code since that require us to
506 return the newly compiled byte-code.
507
508 * 'Nothing' mode has exactly the same type as 'batch' mode but they're still
509 kept separate. This is because compiling to nothing is fairly special: We
510 don't output any interface files, we don't run the simplifier and we don't
511 generate any code.
512
513 * 'Interactive' mode is similar to 'batch' mode except that we return the
514 compiled byte-code together with the ModIface and ModDetails.
515
516 Trying to compile a hs-boot file to byte-code will result in a run-time error.
517 This is the only thing that isn't caught by the type-system.
518 -}
519
520
521 type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()
522
523 genericHscCompileGetFrontendResult ::
524 Bool -- always do basic recompilation check?
525 -> Maybe TcGblEnv
526 -> Maybe Messager
527 -> HscEnv
528 -> ModSummary
529 -> SourceModified
530 -> Maybe ModIface -- Old interface, if available
531 -> (Int,Int) -- (i,n) = module i of n (for msgs)
532 -> IO (Either ModIface (TcGblEnv, Maybe Fingerprint))
533
534 genericHscCompileGetFrontendResult
535 always_do_basic_recompilation_check m_tc_result
536 mHscMessage hsc_env mod_summary source_modified mb_old_iface mod_index
537 = do
538
539 let msg what = case mHscMessage of
540 Just hscMessage -> hscMessage hsc_env mod_index what mod_summary
541 Nothing -> return ()
542
543 skip iface = do
544 msg UpToDate
545 return $ Left iface
546
547 compile mb_old_hash reason = do
548 msg reason
549 tc_result <- runHsc hsc_env $ genericHscFrontend mod_summary
550 return $ Right (tc_result, mb_old_hash)
551
552 stable = case source_modified of
553 SourceUnmodifiedAndStable -> True
554 _ -> False
555
556 case m_tc_result of
557 Just tc_result
558 | not always_do_basic_recompilation_check ->
559 return $ Right (tc_result, Nothing)
560 _ -> do
561 (recomp_reqd, mb_checked_iface)
562 <- {-# SCC "checkOldIface" #-}
563 checkOldIface hsc_env mod_summary
564 source_modified mb_old_iface
565 -- save the interface that comes back from checkOldIface.
566 -- In one-shot mode we don't have the old iface until this
567 -- point, when checkOldIface reads it from the disk.
568 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
569
570 case mb_checked_iface of
571 Just iface | not (recompileRequired recomp_reqd) ->
572 -- If the module used TH splices when it was last
573 -- compiled, then the recompilation check is not
574 -- accurate enough (#481) and we must ignore
575 -- it. However, if the module is stable (none of
576 -- the modules it depends on, directly or
577 -- indirectly, changed), then we *can* skip
578 -- recompilation. This is why the SourceModified
579 -- type contains SourceUnmodifiedAndStable, and
580 -- it's pretty important: otherwise ghc --make
581 -- would always recompile TH modules, even if
582 -- nothing at all has changed. Stability is just
583 -- the same check that make is doing for us in
584 -- one-shot mode.
585 case m_tc_result of
586 Nothing
587 | mi_used_th iface && not stable ->
588 compile mb_old_hash (RecompBecause "TH")
589 _ ->
590 skip iface
591 _ ->
592 case m_tc_result of
593 Nothing -> compile mb_old_hash recomp_reqd
594 Just tc_result ->
595 return $ Right (tc_result, mb_old_hash)
596
597 genericHscFrontend :: ModSummary -> Hsc TcGblEnv
598 genericHscFrontend mod_summary =
599 getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)
600
601 genericHscFrontend' :: ModSummary -> Hsc TcGblEnv
602 genericHscFrontend' mod_summary = hscFileFrontEnd mod_summary
603
604 --------------------------------------------------------------
605 -- Compilers
606 --------------------------------------------------------------
607
608 hscCompileOneShot :: HscEnv
609 -> ModSummary
610 -> SourceModified
611 -> IO HscStatus
612 hscCompileOneShot env =
613 lookupHook hscCompileOneShotHook hscCompileOneShot' (hsc_dflags env) env
614
615 -- Compile Haskell/boot in OneShot mode.
616 hscCompileOneShot' :: HscEnv
617 -> ModSummary
618 -> SourceModified
619 -> IO HscStatus
620 hscCompileOneShot' hsc_env mod_summary src_changed
621 = do
622 -- One-shot mode needs a knot-tying mutable variable for interface
623 -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
624 type_env_var <- newIORef emptyNameEnv
625 let mod = ms_mod mod_summary
626 hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
627
628 msg what = oneShotMsg hsc_env' what
629
630 skip = do msg UpToDate
631 dumpIfaceStats hsc_env'
632 return HscUpToDate
633
634 compile mb_old_hash reason = runHsc hsc_env' $ do
635 liftIO $ msg reason
636 tc_result <- genericHscFrontend mod_summary
637 guts0 <- hscDesugar' (ms_location mod_summary) tc_result
638 dflags <- getDynFlags
639 case hscTarget dflags of
640 HscNothing -> do
641 when (gopt Opt_WriteInterface dflags) $ liftIO $ do
642 (iface, changed, _details) <- hscSimpleIface hsc_env tc_result mb_old_hash
643 hscWriteIface dflags iface changed mod_summary
644 return HscNotGeneratingCode
645 _ ->
646 case ms_hsc_src mod_summary of
647 t | isHsBootOrSig t ->
648 do (iface, changed, _) <- hscSimpleIface' tc_result mb_old_hash
649 liftIO $ hscWriteIface dflags iface changed mod_summary
650 return (case t of
651 HsBootFile -> HscUpdateBoot
652 HsigFile -> HscUpdateSig
653 HsSrcFile -> panic "hscCompileOneShot Src")
654 _ ->
655 do guts <- hscSimplify' guts0
656 (iface, changed, _details, cgguts) <- hscNormalIface' guts mb_old_hash
657 liftIO $ hscWriteIface dflags iface changed mod_summary
658 return $ HscRecomp cgguts mod_summary
659
660 -- XXX This is always False, because in one-shot mode the
661 -- concept of stability does not exist. The driver never
662 -- passes SourceUnmodifiedAndStable in here.
663 stable = case src_changed of
664 SourceUnmodifiedAndStable -> True
665 _ -> False
666
667 (recomp_reqd, mb_checked_iface)
668 <- {-# SCC "checkOldIface" #-}
669 checkOldIface hsc_env' mod_summary src_changed Nothing
670 -- save the interface that comes back from checkOldIface.
671 -- In one-shot mode we don't have the old iface until this
672 -- point, when checkOldIface reads it from the disk.
673 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
674
675 case mb_checked_iface of
676 Just iface | not (recompileRequired recomp_reqd) ->
677 -- If the module used TH splices when it was last compiled,
678 -- then the recompilation check is not accurate enough (#481)
679 -- and we must ignore it. However, if the module is stable
680 -- (none of the modules it depends on, directly or indirectly,
681 -- changed), then we *can* skip recompilation. This is why
682 -- the SourceModified type contains SourceUnmodifiedAndStable,
683 -- and it's pretty important: otherwise ghc --make would
684 -- always recompile TH modules, even if nothing at all has
685 -- changed. Stability is just the same check that make is
686 -- doing for us in one-shot mode.
687 if mi_used_th iface && not stable
688 then compile mb_old_hash (RecompBecause "TH")
689 else skip
690 _ ->
691 compile mb_old_hash recomp_reqd
692
693 --------------------------------------------------------------
694 -- NoRecomp handlers
695 --------------------------------------------------------------
696
697 genModDetails :: HscEnv -> ModIface -> IO ModDetails
698 genModDetails hsc_env old_iface
699 = do
700 new_details <- {-# SCC "tcRnIface" #-}
701 initIfaceCheck hsc_env (typecheckIface old_iface)
702 dumpIfaceStats hsc_env
703 return new_details
704
705 --------------------------------------------------------------
706 -- Progress displayers.
707 --------------------------------------------------------------
708
709 oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
710 oneShotMsg hsc_env recomp =
711 case recomp of
712 UpToDate ->
713 compilationProgressMsg (hsc_dflags hsc_env) $
714 "compilation IS NOT required"
715 _ ->
716 return ()
717
718 batchMsg :: Messager
719 batchMsg hsc_env mod_index recomp mod_summary =
720 case recomp of
721 MustCompile -> showMsg "Compiling " ""
722 UpToDate
723 | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " ""
724 | otherwise -> return ()
725 RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
726 where
727 dflags = hsc_dflags hsc_env
728 showMsg msg reason =
729 compilationProgressMsg dflags $
730 (showModuleIndex mod_index ++
731 msg ++ showModMsg dflags (hscTarget dflags)
732 (recompileRequired recomp) mod_summary)
733 ++ reason
734
735 --------------------------------------------------------------
736 -- FrontEnds
737 --------------------------------------------------------------
738
739 hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
740 hscFileFrontEnd mod_summary = do
741 hpm <- hscParse' mod_summary
742 hsc_env <- getHscEnv
743 tcg_env <- tcRnModule' hsc_env mod_summary False hpm
744 return tcg_env
745
746 --------------------------------------------------------------
747 -- Safe Haskell
748 --------------------------------------------------------------
749
750 -- Note [Safe Haskell Trust Check]
751 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
752 -- Safe Haskell checks that an import is trusted according to the following
753 -- rules for an import of module M that resides in Package P:
754 --
755 -- * If M is recorded as Safe and all its trust dependencies are OK
756 -- then M is considered safe.
757 -- * If M is recorded as Trustworthy and P is considered trusted and
758 -- all M's trust dependencies are OK then M is considered safe.
759 --
760 -- By trust dependencies we mean that the check is transitive. So if
761 -- a module M that is Safe relies on a module N that is trustworthy,
762 -- importing module M will first check (according to the second case)
763 -- that N is trusted before checking M is trusted.
764 --
765 -- This is a minimal description, so please refer to the user guide
766 -- for more details. The user guide is also considered the authoritative
767 -- source in this matter, not the comments or code.
768
769
770 -- Note [Safe Haskell Inference]
771 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
772 -- Safe Haskell does Safe inference on modules that don't have any specific
773 -- safe haskell mode flag. The basic aproach to this is:
774 -- * When deciding if we need to do a Safe language check, treat
775 -- an unmarked module as having -XSafe mode specified.
776 -- * For checks, don't throw errors but return them to the caller.
777 -- * Caller checks if there are errors:
778 -- * For modules explicitly marked -XSafe, we throw the errors.
779 -- * For unmarked modules (inference mode), we drop the errors
780 -- and mark the module as being Unsafe.
781 --
782 -- It used to be that we only did safe inference on modules that had no Safe
783 -- Haskell flags, but now we perform safe inference on all modules as we want
784 -- to allow users to set the `--fwarn-safe`, `--fwarn-unsafe` and
785 -- `--fwarn-trustworthy-safe` flags on Trustworthy and Unsafe modules so that a
786 -- user can ensure their assumptions are correct and see reasons for why a
787 -- module is safe or unsafe.
788 --
789 -- This is tricky as we must be careful when we should throw an error compared
790 -- to just warnings. For checking safe imports we manage it as two steps. First
791 -- we check any imports that are required to be safe, then we check all other
792 -- imports to see if we can infer them to be safe.
793
794
795 -- | Check that the safe imports of the module being compiled are valid.
796 -- If not we either issue a compilation error if the module is explicitly
797 -- using Safe Haskell, or mark the module as unsafe if we're in safe
798 -- inference mode.
799 hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv
800 hscCheckSafeImports tcg_env = do
801 dflags <- getDynFlags
802 tcg_env' <- checkSafeImports dflags tcg_env
803 checkRULES dflags tcg_env'
804
805 where
806 checkRULES dflags tcg_env' = do
807 case safeLanguageOn dflags of
808 True -> do
809 -- XSafe: we nuke user written RULES
810 logWarnings $ warns dflags (tcg_rules tcg_env')
811 return tcg_env' { tcg_rules = [] }
812 False
813 -- SafeInferred: user defined RULES, so not safe
814 | safeInferOn dflags && not (null $ tcg_rules tcg_env')
815 -> markUnsafeInfer tcg_env' $ warns dflags (tcg_rules tcg_env')
816
817 -- Trustworthy OR SafeInferred: with no RULES
818 | otherwise
819 -> return tcg_env'
820
821 warns dflags rules = listToBag $ map (warnRules dflags) rules
822 warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
823 mkPlainWarnMsg dflags loc $
824 text "Rule \"" <> ftext (unLoc n) <> text "\" ignored" $+$
825 text "User defined rules are disabled under Safe Haskell"
826
827 -- | Validate that safe imported modules are actually safe. For modules in the
828 -- HomePackage (the package the module we are compiling in resides) this just
829 -- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules
830 -- that reside in another package we also must check that the external pacakge
831 -- is trusted. See the Note [Safe Haskell Trust Check] above for more
832 -- information.
833 --
834 -- The code for this is quite tricky as the whole algorithm is done in a few
835 -- distinct phases in different parts of the code base. See
836 -- RnNames.rnImportDecl for where package trust dependencies for a module are
837 -- collected and unioned. Specifically see the Note [RnNames . Tracking Trust
838 -- Transitively] and the Note [RnNames . Trust Own Package].
839 checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
840 checkSafeImports dflags tcg_env
841 = do
842 imps <- mapM condense imports'
843 let (safeImps, regImps) = partition (\(_,_,s) -> s) imps
844
845 -- We want to use the warning state specifically for detecting if safe
846 -- inference has failed, so store and clear any existing warnings.
847 oldErrs <- getWarnings
848 clearWarnings
849
850 -- Check safe imports are correct
851 safePkgs <- mapM checkSafe safeImps
852 safeErrs <- getWarnings
853 clearWarnings
854
855 -- Check non-safe imports are correct if inferring safety
856 -- See the Note [Safe Haskell Inference]
857 (infErrs, infPkgs) <- case (safeInferOn dflags) of
858 False -> return (emptyBag, [])
859 True -> do infPkgs <- mapM checkSafe regImps
860 infErrs <- getWarnings
861 clearWarnings
862 return (infErrs, infPkgs)
863
864 -- restore old errors
865 logWarnings oldErrs
866
867 case (isEmptyBag safeErrs) of
868 -- Failed safe check
869 False -> liftIO . throwIO . mkSrcErr $ safeErrs
870
871 -- Passed safe check
872 True -> do
873 let infPassed = isEmptyBag infErrs
874 tcg_env' <- case (not infPassed) of
875 True -> markUnsafeInfer tcg_env infErrs
876 False -> return tcg_env
877 when (packageTrustOn dflags) $ checkPkgTrust dflags pkgReqs
878 let newTrust = pkgTrustReqs safePkgs infPkgs infPassed
879 return tcg_env' { tcg_imports = impInfo `plusImportAvails` newTrust }
880
881 where
882 impInfo = tcg_imports tcg_env -- ImportAvails
883 imports = imp_mods impInfo -- ImportedMods
884 imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
885 pkgReqs = imp_trust_pkgs impInfo -- [PackageKey]
886
887 condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
888 condense (_, []) = panic "HscMain.condense: Pattern match failure!"
889 condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs
890 return (m, l, s)
891
892 -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
893 cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
894 cond' v1@(m1,_,l1,s1) (_,_,_,s2)
895 | s1 /= s2
896 = throwErrors $ unitBag $ mkPlainErrMsg dflags l1
897 (text "Module" <+> ppr m1 <+>
898 (text $ "is imported both as a safe and unsafe import!"))
899 | otherwise
900 = return v1
901
902 -- easier interface to work with
903 checkSafe (m, l, _) = fst `fmap` hscCheckSafe' dflags m l
904
905 -- what pkg's to add to our trust requirements
906 pkgTrustReqs req inf infPassed | safeInferOn dflags
907 && safeHaskell dflags == Sf_None && infPassed
908 = emptyImportAvails {
909 imp_trust_pkgs = catMaybes req ++ catMaybes inf
910 }
911 pkgTrustReqs _ _ _ | safeHaskell dflags == Sf_Unsafe
912 = emptyImportAvails
913 pkgTrustReqs req _ _ = emptyImportAvails { imp_trust_pkgs = catMaybes req }
914
915 -- | Check that a module is safe to import.
916 --
917 -- We return True to indicate the import is safe and False otherwise
918 -- although in the False case an exception may be thrown first.
919 hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool
920 hscCheckSafe hsc_env m l = runHsc hsc_env $ do
921 dflags <- getDynFlags
922 pkgs <- snd `fmap` hscCheckSafe' dflags m l
923 when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs
924 errs <- getWarnings
925 return $ isEmptyBag errs
926
927 -- | Return if a module is trusted and the pkgs it depends on to be trusted.
928 hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageKey])
929 hscGetSafe hsc_env m l = runHsc hsc_env $ do
930 dflags <- getDynFlags
931 (self, pkgs) <- hscCheckSafe' dflags m l
932 good <- isEmptyBag `fmap` getWarnings
933 clearWarnings -- don't want them printed...
934 let pkgs' | Just p <- self = p:pkgs
935 | otherwise = pkgs
936 return (good, pkgs')
937
938 -- | Is a module trusted? If not, throw or log errors depending on the type.
939 -- Return (regardless of trusted or not) if the trust type requires the modules
940 -- own package be trusted and a list of other packages required to be trusted
941 -- (these later ones haven't been checked) but the own package trust has been.
942 hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageKey, [PackageKey])
943 hscCheckSafe' dflags m l = do
944 (tw, pkgs) <- isModSafe m l
945 case tw of
946 False -> return (Nothing, pkgs)
947 True | isHomePkg m -> return (Nothing, pkgs)
948 | otherwise -> return (Just $ modulePackageKey m, pkgs)
949 where
950 isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey])
951 isModSafe m l = do
952 iface <- lookup' m
953 case iface of
954 -- can't load iface to check trust!
955 Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l
956 $ text "Can't load the interface file for" <+> ppr m
957 <> text ", to check that it can be safely imported"
958
959 -- got iface, check trust
960 Just iface' ->
961 let trust = getSafeMode $ mi_trust iface'
962 trust_own_pkg = mi_trust_pkg iface'
963 -- check module is trusted
964 safeM = trust `elem` [Sf_Safe, Sf_Trustworthy]
965 -- check package is trusted
966 safeP = packageTrusted trust trust_own_pkg m
967 -- pkg trust reqs
968 pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface'
969 -- General errors we throw but Safe errors we log
970 errs = case (safeM, safeP) of
971 (True, True ) -> emptyBag
972 (True, False) -> pkgTrustErr
973 (False, _ ) -> modTrustErr
974 in do
975 logWarnings errs
976 return (trust == Sf_Trustworthy, pkgRs)
977
978 where
979 pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
980 sep [ ppr (moduleName m)
981 <> text ": Can't be safely imported!"
982 , text "The package (" <> ppr (modulePackageKey m)
983 <> text ") the module resides in isn't trusted."
984 ]
985 modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
986 sep [ ppr (moduleName m)
987 <> text ": Can't be safely imported!"
988 , text "The module itself isn't safe." ]
989
990 -- | Check the package a module resides in is trusted. Safe compiled
991 -- modules are trusted without requiring that their package is trusted. For
992 -- trustworthy modules, modules in the home package are trusted but
993 -- otherwise we check the package trust flag.
994 packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
995 packageTrusted Sf_None _ _ = False -- shouldn't hit these cases
996 packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness.
997 packageTrusted _ _ _
998 | not (packageTrustOn dflags) = True
999 packageTrusted Sf_Safe False _ = True
1000 packageTrusted _ _ m
1001 | isHomePkg m = True
1002 | otherwise = trusted $ getPackageDetails dflags (modulePackageKey m)
1003
1004 lookup' :: Module -> Hsc (Maybe ModIface)
1005 lookup' m = do
1006 hsc_env <- getHscEnv
1007 hsc_eps <- liftIO $ hscEPS hsc_env
1008 let pkgIfaceT = eps_PIT hsc_eps
1009 homePkgT = hsc_HPT hsc_env
1010 iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
1011 #ifdef GHCI
1012 -- the 'lookupIfaceByModule' method will always fail when calling from GHCi
1013 -- as the compiler hasn't filled in the various module tables
1014 -- so we need to call 'getModuleInterface' to load from disk
1015 iface' <- case iface of
1016 Just _ -> return iface
1017 Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m)
1018 return iface'
1019 #else
1020 return iface
1021 #endif
1022
1023
1024 isHomePkg :: Module -> Bool
1025 isHomePkg m
1026 | thisPackage dflags == modulePackageKey m = True
1027 | otherwise = False
1028
1029 -- | Check the list of packages are trusted.
1030 checkPkgTrust :: DynFlags -> [PackageKey] -> Hsc ()
1031 checkPkgTrust dflags pkgs =
1032 case errors of
1033 [] -> return ()
1034 _ -> (liftIO . throwIO . mkSrcErr . listToBag) errors
1035 where
1036 errors = catMaybes $ map go pkgs
1037 go pkg
1038 | trusted $ getPackageDetails dflags pkg
1039 = Nothing
1040 | otherwise
1041 = Just $ mkErrMsg dflags noSrcSpan (pkgQual dflags)
1042 $ text "The package (" <> ppr pkg <> text ") is required" <>
1043 text " to be trusted but it isn't!"
1044
1045 -- | Set module to unsafe and (potentially) wipe trust information.
1046 --
1047 -- Make sure to call this method to set a module to inferred unsafe, it should
1048 -- be a central and single failure method. We only wipe the trust information
1049 -- when we aren't in a specific Safe Haskell mode.
1050 --
1051 -- While we only use this for recording that a module was inferred unsafe, we
1052 -- may call it on modules using Trustworthy or Unsafe flags so as to allow
1053 -- warning flags for safety to function correctly. See Note [Safe Haskell
1054 -- Inference].
1055 markUnsafeInfer :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv
1056 markUnsafeInfer tcg_env whyUnsafe = do
1057 dflags <- getDynFlags
1058
1059 when (wopt Opt_WarnUnsafe dflags)
1060 (logWarnings $ unitBag $
1061 mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags))
1062
1063 liftIO $ writeIORef (tcg_safeInfer tcg_env) False
1064 -- NOTE: Only wipe trust when not in an explicity safe haskell mode. Other
1065 -- times inference may be on but we are in Trustworthy mode -- so we want
1066 -- to record safe-inference failed but not wipe the trust dependencies.
1067 case safeHaskell dflags == Sf_None of
1068 True -> return $ tcg_env { tcg_imports = wiped_trust }
1069 False -> return tcg_env
1070
1071 where
1072 wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] }
1073 pprMod = ppr $ moduleName $ tcg_mod tcg_env
1074 whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!"
1075 , text "Reason:"
1076 , nest 4 $ (vcat $ badFlags df) $+$
1077 (vcat $ pprErrMsgBagWithLoc whyUnsafe) $+$
1078 (vcat $ badInsts $ tcg_insts tcg_env)
1079 ]
1080 badFlags df = concat $ map (badFlag df) unsafeFlagsForInfer
1081 badFlag df (str,loc,on,_)
1082 | on df = [mkLocMessage SevOutput (loc df) $
1083 text str <+> text "is not allowed in Safe Haskell"]
1084 | otherwise = []
1085 badInsts insts = concat $ map badInst insts
1086 badInst ins | overlapMode (is_flag ins) /= NoOverlap
1087 = [mkLocMessage SevOutput (nameSrcSpan $ getName $ is_dfun ins) $
1088 ppr (overlapMode $ is_flag ins) <+>
1089 text "overlap mode isn't allowed in Safe Haskell"]
1090 | otherwise = []
1091
1092
1093 -- | Figure out the final correct safe haskell mode
1094 hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode
1095 hscGetSafeMode tcg_env = do
1096 dflags <- getDynFlags
1097 liftIO $ finalSafeMode dflags tcg_env
1098
1099 --------------------------------------------------------------
1100 -- Simplifiers
1101 --------------------------------------------------------------
1102
1103 hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
1104 hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts
1105
1106 hscSimplify' :: ModGuts -> Hsc ModGuts
1107 hscSimplify' ds_result = do
1108 hsc_env <- getHscEnv
1109 {-# SCC "Core2Core" #-}
1110 liftIO $ core2core hsc_env ds_result
1111
1112 --------------------------------------------------------------
1113 -- Interface generators
1114 --------------------------------------------------------------
1115
1116 hscSimpleIface :: HscEnv
1117 -> TcGblEnv
1118 -> Maybe Fingerprint
1119 -> IO (ModIface, Bool, ModDetails)
1120 hscSimpleIface hsc_env tc_result mb_old_iface
1121 = runHsc hsc_env $ hscSimpleIface' tc_result mb_old_iface
1122
1123 hscSimpleIface' :: TcGblEnv
1124 -> Maybe Fingerprint
1125 -> Hsc (ModIface, Bool, ModDetails)
1126 hscSimpleIface' tc_result mb_old_iface = do
1127 hsc_env <- getHscEnv
1128 details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
1129 safe_mode <- hscGetSafeMode tc_result
1130 (new_iface, no_change)
1131 <- {-# SCC "MkFinalIface" #-}
1132 ioMsgMaybe $
1133 mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result
1134 -- And the answer is ...
1135 liftIO $ dumpIfaceStats hsc_env
1136 return (new_iface, no_change, details)
1137
1138 hscNormalIface :: HscEnv
1139 -> ModGuts
1140 -> Maybe Fingerprint
1141 -> IO (ModIface, Bool, ModDetails, CgGuts)
1142 hscNormalIface hsc_env simpl_result mb_old_iface =
1143 runHsc hsc_env $ hscNormalIface' simpl_result mb_old_iface
1144
1145 hscNormalIface' :: ModGuts
1146 -> Maybe Fingerprint
1147 -> Hsc (ModIface, Bool, ModDetails, CgGuts)
1148 hscNormalIface' simpl_result mb_old_iface = do
1149 hsc_env <- getHscEnv
1150 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
1151 liftIO $ tidyProgram hsc_env simpl_result
1152
1153 -- BUILD THE NEW ModIface and ModDetails
1154 -- and emit external core if necessary
1155 -- This has to happen *after* code gen so that the back-end
1156 -- info has been set. Not yet clear if it matters waiting
1157 -- until after code output
1158 (new_iface, no_change)
1159 <- {-# SCC "MkFinalIface" #-}
1160 ioMsgMaybe $
1161 mkIface hsc_env mb_old_iface details simpl_result
1162
1163 liftIO $ dumpIfaceStats hsc_env
1164
1165 -- Return the prepared code.
1166 return (new_iface, no_change, details, cg_guts)
1167
1168 --------------------------------------------------------------
1169 -- BackEnd combinators
1170 --------------------------------------------------------------
1171
1172 hscWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO ()
1173 hscWriteIface dflags iface no_change mod_summary = do
1174 let ifaceFile = ml_hi_file (ms_location mod_summary)
1175 unless no_change $
1176 {-# SCC "writeIface" #-}
1177 writeIfaceFile dflags ifaceFile iface
1178 whenGeneratingDynamicToo dflags $ do
1179 -- TODO: We should do a no_change check for the dynamic
1180 -- interface file too
1181 -- TODO: Should handle the dynamic hi filename properly
1182 let dynIfaceFile = replaceExtension ifaceFile (dynHiSuf dflags)
1183 dynIfaceFile' = addBootSuffix_maybe (mi_boot iface) dynIfaceFile
1184 dynDflags = dynamicTooMkDynamicDynFlags dflags
1185 writeIfaceFile dynDflags dynIfaceFile' iface
1186
1187 -- | Compile to hard-code.
1188 hscGenHardCode :: HscEnv -> CgGuts -> ModSummary -> FilePath
1189 -> IO (FilePath, Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
1190 hscGenHardCode hsc_env cgguts mod_summary output_filename = do
1191 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
1192 -- From now on, we just use the bits we need.
1193 cg_module = this_mod,
1194 cg_binds = core_binds,
1195 cg_tycons = tycons,
1196 cg_foreign = foreign_stubs0,
1197 cg_dep_pkgs = dependencies,
1198 cg_hpc_info = hpc_info } = cgguts
1199 dflags = hsc_dflags hsc_env
1200 location = ms_location mod_summary
1201 data_tycons = filter isDataTyCon tycons
1202 -- cg_tycons includes newtypes, for the benefit of External Core,
1203 -- but we don't generate any code for newtypes
1204
1205 -------------------
1206 -- PREPARE FOR CODE GENERATION
1207 -- Do saturation and convert to A-normal form
1208 prepd_binds <- {-# SCC "CorePrep" #-}
1209 corePrepPgm dflags hsc_env core_binds data_tycons ;
1210 ----------------- Convert to STG ------------------
1211 (stg_binds, cost_centre_info)
1212 <- {-# SCC "CoreToStg" #-}
1213 myCoreToStg dflags this_mod prepd_binds
1214
1215 let prof_init = profilingInitCode this_mod cost_centre_info
1216 foreign_stubs = foreign_stubs0 `appendStubC` prof_init
1217
1218 ------------------ Code generation ------------------
1219
1220 -- The back-end is streamed: each top-level function goes
1221 -- from Stg all the way to asm before dealing with the next
1222 -- top-level function, so showPass isn't very useful here.
1223 -- Hence we have one showPass for the whole backend, the
1224 -- next showPass after this will be "Assembler".
1225 showPass dflags "CodeGen"
1226
1227 cmms <- {-# SCC "StgCmm" #-}
1228 doCodeGen hsc_env this_mod data_tycons
1229 cost_centre_info
1230 stg_binds hpc_info
1231
1232 ------------------ Code output -----------------------
1233 rawcmms0 <- {-# SCC "cmmToRawCmm" #-}
1234 cmmToRawCmm dflags cmms
1235
1236 let dump a = do dumpIfSet_dyn dflags Opt_D_dump_cmm_raw "Raw Cmm"
1237 (ppr a)
1238 return a
1239 rawcmms1 = Stream.mapM dump rawcmms0
1240
1241 (output_filename, (_stub_h_exists, stub_c_exists))
1242 <- {-# SCC "codeOutput" #-}
1243 codeOutput dflags this_mod output_filename location
1244 foreign_stubs dependencies rawcmms1
1245 return (output_filename, stub_c_exists)
1246
1247
1248 hscInteractive :: HscEnv
1249 -> CgGuts
1250 -> ModSummary
1251 -> IO (Maybe FilePath, CompiledByteCode, ModBreaks)
1252 #ifdef GHCI
1253 hscInteractive hsc_env cgguts mod_summary = do
1254 let dflags = hsc_dflags hsc_env
1255 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
1256 -- From now on, we just use the bits we need.
1257 cg_module = this_mod,
1258 cg_binds = core_binds,
1259 cg_tycons = tycons,
1260 cg_foreign = foreign_stubs,
1261 cg_modBreaks = mod_breaks } = cgguts
1262
1263 location = ms_location mod_summary
1264 data_tycons = filter isDataTyCon tycons
1265 -- cg_tycons includes newtypes, for the benefit of External Core,
1266 -- but we don't generate any code for newtypes
1267
1268 -------------------
1269 -- PREPARE FOR CODE GENERATION
1270 -- Do saturation and convert to A-normal form
1271 prepd_binds <- {-# SCC "CorePrep" #-}
1272 corePrepPgm dflags hsc_env core_binds data_tycons
1273 ----------------- Generate byte code ------------------
1274 comp_bc <- byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks
1275 ------------------ Create f-x-dynamic C-side stuff ---
1276 (_istub_h_exists, istub_c_exists)
1277 <- outputForeignStubs dflags this_mod location foreign_stubs
1278 return (istub_c_exists, comp_bc, mod_breaks)
1279 #else
1280 hscInteractive _ _ = panic "GHC not compiled with interpreter"
1281 #endif
1282
1283 ------------------------------
1284
1285 hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO ()
1286 hscCompileCmmFile hsc_env filename output_filename = runHsc hsc_env $ do
1287 let dflags = hsc_dflags hsc_env
1288 cmm <- ioMsgMaybe $ parseCmmFile dflags filename
1289 liftIO $ do
1290 us <- mkSplitUniqSupply 'S'
1291 let initTopSRT = initUs_ us emptySRT
1292 dumpIfSet_dyn dflags Opt_D_dump_cmm "Parsed Cmm" (ppr cmm)
1293 (_, cmmgroup) <- cmmPipeline hsc_env initTopSRT cmm
1294 rawCmms <- cmmToRawCmm dflags (Stream.yield cmmgroup)
1295 _ <- codeOutput dflags no_mod output_filename no_loc NoStubs [] rawCmms
1296 return ()
1297 where
1298 no_mod = panic "hscCmmFile: no_mod"
1299 no_loc = ModLocation{ ml_hs_file = Just filename,
1300 ml_hi_file = panic "hscCmmFile: no hi file",
1301 ml_obj_file = panic "hscCmmFile: no obj file" }
1302
1303 -------------------- Stuff for new code gen ---------------------
1304
1305 doCodeGen :: HscEnv -> Module -> [TyCon]
1306 -> CollectedCCs
1307 -> [StgBinding]
1308 -> HpcInfo
1309 -> IO (Stream IO CmmGroup ())
1310 -- Note we produce a 'Stream' of CmmGroups, so that the
1311 -- backend can be run incrementally. Otherwise it generates all
1312 -- the C-- up front, which has a significant space cost.
1313 doCodeGen hsc_env this_mod data_tycons
1314 cost_centre_info stg_binds hpc_info = do
1315 let dflags = hsc_dflags hsc_env
1316
1317 let cmm_stream :: Stream IO CmmGroup ()
1318 cmm_stream = {-# SCC "StgCmm" #-}
1319 StgCmm.codeGen dflags this_mod data_tycons
1320 cost_centre_info stg_binds hpc_info
1321
1322 -- codegen consumes a stream of CmmGroup, and produces a new
1323 -- stream of CmmGroup (not necessarily synchronised: one
1324 -- CmmGroup on input may produce many CmmGroups on output due
1325 -- to proc-point splitting).
1326
1327 let dump1 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm
1328 "Cmm produced by new codegen" (ppr a)
1329 return a
1330
1331 ppr_stream1 = Stream.mapM dump1 cmm_stream
1332
1333 -- We are building a single SRT for the entire module, so
1334 -- we must thread it through all the procedures as we cps-convert them.
1335 us <- mkSplitUniqSupply 'S'
1336
1337 -- When splitting, we generate one SRT per split chunk, otherwise
1338 -- we generate one SRT for the whole module.
1339 let
1340 pipeline_stream
1341 | gopt Opt_SplitObjs dflags
1342 = {-# SCC "cmmPipeline" #-}
1343 let run_pipeline us cmmgroup = do
1344 let (topSRT', us') = initUs us emptySRT
1345 (topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT' cmmgroup
1346 let srt | isEmptySRT topSRT = []
1347 | otherwise = srtToData topSRT
1348 return (us', srt ++ cmmgroup)
1349
1350 in do _ <- Stream.mapAccumL run_pipeline us ppr_stream1
1351 return ()
1352
1353 | otherwise
1354 = {-# SCC "cmmPipeline" #-}
1355 let initTopSRT = initUs_ us emptySRT
1356 run_pipeline = cmmPipeline hsc_env
1357 in do topSRT <- Stream.mapAccumL run_pipeline initTopSRT ppr_stream1
1358 Stream.yield (srtToData topSRT)
1359
1360 let
1361 dump2 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm "Output Cmm" $ ppr a
1362 return a
1363
1364 ppr_stream2 = Stream.mapM dump2 pipeline_stream
1365
1366 return ppr_stream2
1367
1368
1369
1370 myCoreToStg :: DynFlags -> Module -> CoreProgram
1371 -> IO ( [StgBinding] -- output program
1372 , CollectedCCs) -- cost centre info (declared and used)
1373 myCoreToStg dflags this_mod prepd_binds = do
1374 stg_binds
1375 <- {-# SCC "Core2Stg" #-}
1376 coreToStg dflags this_mod prepd_binds
1377
1378 (stg_binds2, cost_centre_info)
1379 <- {-# SCC "Stg2Stg" #-}
1380 stg2stg dflags this_mod stg_binds
1381
1382 return (stg_binds2, cost_centre_info)
1383
1384
1385 {- **********************************************************************
1386 %* *
1387 \subsection{Compiling a do-statement}
1388 %* *
1389 %********************************************************************* -}
1390
1391 {-
1392 When the UnlinkedBCOExpr is linked you get an HValue of type *IO [HValue]* When
1393 you run it you get a list of HValues that should be the same length as the list
1394 of names; add them to the ClosureEnv.
1395
1396 A naked expression returns a singleton Name [it]. The stmt is lifted into the
1397 IO monad as explained in Note [Interactively-bound Ids in GHCi] in HscTypes
1398 -}
1399
1400 #ifdef GHCI
1401 -- | Compile a stmt all the way to an HValue, but don't run it
1402 --
1403 -- We return Nothing to indicate an empty statement (or comment only), not a
1404 -- parse error.
1405 hscStmt :: HscEnv -> String -> IO (Maybe ([Id], IO [HValue], FixityEnv))
1406 hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1
1407
1408 -- | Compile a stmt all the way to an HValue, but don't run it
1409 --
1410 -- We return Nothing to indicate an empty statement (or comment only), not a
1411 -- parse error.
1412 hscStmtWithLocation :: HscEnv
1413 -> String -- ^ The statement
1414 -> String -- ^ The source
1415 -> Int -- ^ Starting line
1416 -> IO (Maybe ([Id], IO [HValue], FixityEnv))
1417 hscStmtWithLocation hsc_env0 stmt source linenumber =
1418 runInteractiveHsc hsc_env0 $ do
1419 maybe_stmt <- hscParseStmtWithLocation source linenumber stmt
1420 case maybe_stmt of
1421 Nothing -> return Nothing
1422
1423 Just parsed_stmt -> do
1424 -- Rename and typecheck it
1425 hsc_env <- getHscEnv
1426 (ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env parsed_stmt
1427
1428 -- Desugar it
1429 ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env tc_expr
1430 liftIO (lintInteractiveExpr "desugar expression" hsc_env ds_expr)
1431 handleWarnings
1432
1433 -- Then code-gen, and link it
1434 -- It's important NOT to have package 'interactive' as thisPackageKey
1435 -- for linking, else we try to link 'main' and can't find it.
1436 -- Whereas the linker already knows to ignore 'interactive'
1437 let src_span = srcLocSpan interactiveSrcLoc
1438 hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr
1439 let hval_io = unsafeCoerce# hval :: IO [HValue]
1440
1441 return $ Just (ids, hval_io, fix_env)
1442
1443 -- | Compile a decls
1444 hscDecls :: HscEnv
1445 -> String -- ^ The statement
1446 -> IO ([TyThing], InteractiveContext)
1447 hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1
1448
1449 -- | Compile a decls
1450 hscDeclsWithLocation :: HscEnv
1451 -> String -- ^ The statement
1452 -> String -- ^ The source
1453 -> Int -- ^ Starting line
1454 -> IO ([TyThing], InteractiveContext)
1455 hscDeclsWithLocation hsc_env0 str source linenumber =
1456 runInteractiveHsc hsc_env0 $ do
1457 L _ (HsModule{ hsmodDecls = decls }) <-
1458 hscParseThingWithLocation source linenumber parseModule str
1459
1460 {- Rename and typecheck it -}
1461 hsc_env <- getHscEnv
1462 tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env decls
1463
1464 {- Grab the new instances -}
1465 -- We grab the whole environment because of the overlapping that may have
1466 -- been done. See the notes at the definition of InteractiveContext
1467 -- (ic_instances) for more details.
1468 let finsts = tcg_fam_insts tc_gblenv
1469 insts = tcg_insts tc_gblenv
1470
1471 let defaults = tcg_default tc_gblenv
1472
1473 {- Desugar it -}
1474 -- We use a basically null location for iNTERACTIVE
1475 let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing,
1476 ml_hi_file = panic "hsDeclsWithLocation:ml_hi_file",
1477 ml_obj_file = panic "hsDeclsWithLocation:ml_hi_file"}
1478 ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv
1479
1480 {- Simplify -}
1481 simpl_mg <- liftIO $ hscSimplify hsc_env ds_result
1482
1483 {- Tidy -}
1484 (tidy_cg, _mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg
1485
1486 let dflags = hsc_dflags hsc_env
1487 !CgGuts{ cg_module = this_mod,
1488 cg_binds = core_binds,
1489 cg_tycons = tycons,
1490 cg_modBreaks = mod_breaks } = tidy_cg
1491 data_tycons = filter isDataTyCon tycons
1492
1493 {- Prepare For Code Generation -}
1494 -- Do saturation and convert to A-normal form
1495 prepd_binds <- {-# SCC "CorePrep" #-}
1496 liftIO $ corePrepPgm dflags hsc_env core_binds data_tycons
1497
1498 {- Generate byte code -}
1499 cbc <- liftIO $ byteCodeGen dflags this_mod
1500 prepd_binds data_tycons mod_breaks
1501
1502 let src_span = srcLocSpan interactiveSrcLoc
1503 liftIO $ linkDecls hsc_env src_span cbc
1504
1505 let tcs = filterOut isImplicitTyCon (mg_tcs simpl_mg)
1506
1507 ext_ids = [ id | id <- bindersOfBinds core_binds
1508 , isExternalName (idName id)
1509 , not (isDFunId id || isImplicitId id) ]
1510 -- We only need to keep around the external bindings
1511 -- (as decided by TidyPgm), since those are the only ones
1512 -- that might be referenced elsewhere.
1513 -- The DFunIds are in 'insts' (see Note [ic_tythings] in HscTypes
1514 -- Implicit Ids are implicit in tcs
1515
1516 tythings = map AnId ext_ids ++ map ATyCon tcs
1517
1518 let icontext = hsc_IC hsc_env
1519 ictxt1 = extendInteractiveContext icontext tythings
1520 ictxt = ictxt1 { ic_instances = (insts, finsts)
1521 , ic_default = defaults }
1522
1523 return (tythings, ictxt)
1524
1525 hscImport :: HscEnv -> String -> IO (ImportDecl RdrName)
1526 hscImport hsc_env str = runInteractiveHsc hsc_env $ do
1527 (L _ (HsModule{hsmodImports=is})) <-
1528 hscParseThing parseModule str
1529 case is of
1530 [L _ i] -> return i
1531 _ -> liftIO $ throwOneError $
1532 mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan $
1533 ptext (sLit "parse error in import declaration")
1534
1535 -- | Typecheck an expression (but don't run it)
1536 -- Returns its most general type
1537 hscTcExpr :: HscEnv
1538 -> String -- ^ The expression
1539 -> IO Type
1540 hscTcExpr hsc_env0 expr = runInteractiveHsc hsc_env0 $ do
1541 hsc_env <- getHscEnv
1542 maybe_stmt <- hscParseStmt expr
1543 case maybe_stmt of
1544 Just (L _ (BodyStmt expr _ _ _)) ->
1545 ioMsgMaybe $ tcRnExpr hsc_env expr
1546 _ ->
1547 throwErrors $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan
1548 (text "not an expression:" <+> quotes (text expr))
1549
1550 -- | Find the kind of a type
1551 -- Currently this does *not* generalise the kinds of the type
1552 hscKcType
1553 :: HscEnv
1554 -> Bool -- ^ Normalise the type
1555 -> String -- ^ The type as a string
1556 -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind
1557 hscKcType hsc_env0 normalise str = runInteractiveHsc hsc_env0 $ do
1558 hsc_env <- getHscEnv
1559 ty <- hscParseType str
1560 ioMsgMaybe $ tcRnType hsc_env normalise ty
1561
1562 hscParseStmt :: String -> Hsc (Maybe (GhciLStmt RdrName))
1563 hscParseStmt = hscParseThing parseStmt
1564
1565 hscParseStmtWithLocation :: String -> Int -> String
1566 -> Hsc (Maybe (GhciLStmt RdrName))
1567 hscParseStmtWithLocation source linenumber stmt =
1568 hscParseThingWithLocation source linenumber parseStmt stmt
1569
1570 hscParseType :: String -> Hsc (LHsType RdrName)
1571 hscParseType = hscParseThing parseType
1572 #endif
1573
1574 hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)
1575 hscParseIdentifier hsc_env str =
1576 runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str
1577
1578 hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing
1579 hscParseThing = hscParseThingWithLocation "<interactive>" 1
1580
1581 hscParseThingWithLocation :: (Outputable thing) => String -> Int
1582 -> Lexer.P thing -> String -> Hsc thing
1583 hscParseThingWithLocation source linenumber parser str
1584 = {-# SCC "Parser" #-} do
1585 dflags <- getDynFlags
1586 liftIO $ showPass dflags "Parser"
1587
1588 let buf = stringToStringBuffer str
1589 loc = mkRealSrcLoc (fsLit source) linenumber 1
1590
1591 case unP parser (mkPState dflags buf loc) of
1592 PFailed span err -> do
1593 let msg = mkPlainErrMsg dflags span err
1594 throwErrors $ unitBag msg
1595
1596 POk pst thing -> do
1597 logWarningsReportErrors (getMessages pst)
1598 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
1599 return thing
1600
1601 hscCompileCore :: HscEnv -> Bool -> SafeHaskellMode -> ModSummary
1602 -> CoreProgram -> FilePath -> IO ()
1603 hscCompileCore hsc_env simplify safe_mode mod_summary binds output_filename
1604 = runHsc hsc_env $ do
1605 guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) safe_mode binds)
1606 (iface, changed, _details, cgguts) <- hscNormalIface' guts Nothing
1607 liftIO $ hscWriteIface (hsc_dflags hsc_env) iface changed mod_summary
1608 _ <- liftIO $ hscGenHardCode hsc_env cgguts mod_summary output_filename
1609 return ()
1610
1611 where
1612 maybe_simplify mod_guts | simplify = hscSimplify' mod_guts
1613 | otherwise = return mod_guts
1614
1615 -- Makes a "vanilla" ModGuts.
1616 mkModGuts :: Module -> SafeHaskellMode -> CoreProgram -> ModGuts
1617 mkModGuts mod safe binds =
1618 ModGuts {
1619 mg_module = mod,
1620 mg_boot = False,
1621 mg_exports = [],
1622 mg_deps = noDependencies,
1623 mg_dir_imps = emptyModuleEnv,
1624 mg_used_names = emptyNameSet,
1625 mg_used_th = False,
1626 mg_rdr_env = emptyGlobalRdrEnv,
1627 mg_fix_env = emptyFixityEnv,
1628 mg_tcs = [],
1629 mg_insts = [],
1630 mg_fam_insts = [],
1631 mg_patsyns = [],
1632 mg_rules = [],
1633 mg_vect_decls = [],
1634 mg_binds = binds,
1635 mg_foreign = NoStubs,
1636 mg_warns = NoWarnings,
1637 mg_anns = [],
1638 mg_hpc_info = emptyHpcInfo False,
1639 mg_modBreaks = emptyModBreaks,
1640 mg_vect_info = noVectInfo,
1641 mg_inst_env = emptyInstEnv,
1642 mg_fam_inst_env = emptyFamInstEnv,
1643 mg_safe_haskell = safe,
1644 mg_trust_pkg = False,
1645 mg_dependent_files = []
1646 }
1647
1648
1649 {- **********************************************************************
1650 %* *
1651 Desugar, simplify, convert to bytecode, and link an expression
1652 %* *
1653 %********************************************************************* -}
1654
1655 #ifdef GHCI
1656 hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
1657 hscCompileCoreExpr hsc_env =
1658 lookupHook hscCompileCoreExprHook hscCompileCoreExpr' (hsc_dflags hsc_env) hsc_env
1659
1660 hscCompileCoreExpr' :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
1661 hscCompileCoreExpr' hsc_env srcspan ds_expr
1662 | rtsIsProfiled
1663 = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler")
1664 -- Otherwise you get a seg-fault when you run it
1665
1666 | otherwise
1667 = do { let dflags = hsc_dflags hsc_env
1668
1669 {- Simplify it -}
1670 ; simpl_expr <- simplifyExpr dflags ds_expr
1671
1672 {- Tidy it (temporary, until coreSat does cloning) -}
1673 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1674
1675 {- Prepare for codegen -}
1676 ; prepd_expr <- corePrepExpr dflags hsc_env tidy_expr
1677
1678 {- Lint if necessary -}
1679 ; lintInteractiveExpr "hscCompileExpr" hsc_env prepd_expr
1680
1681 {- Convert to BCOs -}
1682 ; bcos <- coreExprToBCOs dflags (icInteractiveModule (hsc_IC hsc_env)) prepd_expr
1683
1684 {- link it -}
1685 ; hval <- linkExpr hsc_env srcspan bcos
1686
1687 ; return hval }
1688 #endif
1689
1690
1691 {- **********************************************************************
1692 %* *
1693 Statistics on reading interfaces
1694 %* *
1695 %********************************************************************* -}
1696
1697 dumpIfaceStats :: HscEnv -> IO ()
1698 dumpIfaceStats hsc_env = do
1699 eps <- readIORef (hsc_EPS hsc_env)
1700 dumpIfSet dflags (dump_if_trace || dump_rn_stats)
1701 "Interface statistics"
1702 (ifaceStats eps)
1703 where
1704 dflags = hsc_dflags hsc_env
1705 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1706 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1707
1708
1709 {- **********************************************************************
1710 %* *
1711 Progress Messages: Module i of n
1712 %* *
1713 %********************************************************************* -}
1714
1715 showModuleIndex :: (Int, Int) -> String
1716 showModuleIndex (i,n) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1717 where
1718 n_str = show n
1719 i_str = show i
1720 padded = replicate (length n_str - length i_str) ' ' ++ i_str