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