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