Better error messages for new per-instance overlap flags and Safe
[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 let allSafeOK = safeInferred dflags && tcSafeOK
411
412 -- end of the safe haskell line, how to respond to user?
413 if not (safeHaskellOn dflags) || (safeInferOn dflags && not allSafeOK)
414 -- if safe Haskell off or safe infer failed, mark unsafe
415 then markUnsafe tcg_res emptyBag
416
417 -- module (could be) safe, throw warning if needed
418 else do
419 tcg_res' <- hscCheckSafeImports tcg_res
420 safe <- liftIO $ readIORef (tcg_safeInfer tcg_res')
421 when (safe && wopt Opt_WarnSafe dflags)
422 (logWarnings $ unitBag $ mkPlainWarnMsg dflags
423 (warnSafeOnLoc dflags) $ errSafe tcg_res')
424 return tcg_res'
425 where
426 pprMod t = ppr $ moduleName $ tcg_mod t
427 errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
428
429 -- | Convert a typechecked module to Core
430 hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
431 hscDesugar hsc_env mod_summary tc_result =
432 runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
433
434 hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
435 hscDesugar' mod_location tc_result = do
436 hsc_env <- getHscEnv
437 r <- ioMsgMaybe $
438 {-# SCC "deSugar" #-}
439 deSugar hsc_env mod_location tc_result
440
441 -- always check -Werror after desugaring, this is the last opportunity for
442 -- warnings to arise before the backend.
443 handleWarnings
444 return r
445
446 -- | Make a 'ModIface' from the results of typechecking. Used when
447 -- not optimising, and the interface doesn't need to contain any
448 -- unfoldings or other cross-module optimisation info.
449 -- ToDo: the old interface is only needed to get the version numbers,
450 -- we should use fingerprint versions instead.
451 makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
452 -> IO (ModIface,Bool)
453 makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do
454 safe_mode <- hscGetSafeMode tc_result
455 ioMsgMaybe $ do
456 mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode
457 details tc_result
458
459 -- | Make a 'ModDetails' from the results of typechecking. Used when
460 -- typechecking only, as opposed to full compilation.
461 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
462 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
463
464
465 {- **********************************************************************
466 %* *
467 The main compiler pipeline
468 %* *
469 %********************************************************************* -}
470
471 {-
472 --------------------------------
473 The compilation proper
474 --------------------------------
475
476 It's the task of the compilation proper to compile Haskell, hs-boot and core
477 files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
478 (the module is still parsed and type-checked. This feature is mostly used by
479 IDE's and the likes). Compilation can happen in either 'one-shot', 'batch',
480 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch'
481 mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
482 targets byte-code.
483
484 The modes are kept separate because of their different types and meanings:
485
486 * In 'one-shot' mode, we're only compiling a single file and can therefore
487 discard the new ModIface and ModDetails. This is also the reason it only
488 targets hard-code; compiling to byte-code or nothing doesn't make sense when
489 we discard the result.
490
491 * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
492 and ModDetails. 'Batch' mode doesn't target byte-code since that require us to
493 return the newly compiled byte-code.
494
495 * 'Nothing' mode has exactly the same type as 'batch' mode but they're still
496 kept separate. This is because compiling to nothing is fairly special: We
497 don't output any interface files, we don't run the simplifier and we don't
498 generate any code.
499
500 * 'Interactive' mode is similar to 'batch' mode except that we return the
501 compiled byte-code together with the ModIface and ModDetails.
502
503 Trying to compile a hs-boot file to byte-code will result in a run-time error.
504 This is the only thing that isn't caught by the type-system.
505 -}
506
507
508 type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()
509
510 genericHscCompileGetFrontendResult ::
511 Bool -- always do basic recompilation check?
512 -> Maybe TcGblEnv
513 -> Maybe Messager
514 -> HscEnv
515 -> ModSummary
516 -> SourceModified
517 -> Maybe ModIface -- Old interface, if available
518 -> (Int,Int) -- (i,n) = module i of n (for msgs)
519 -> IO (Either ModIface (TcGblEnv, Maybe Fingerprint))
520
521 genericHscCompileGetFrontendResult
522 always_do_basic_recompilation_check m_tc_result
523 mHscMessage hsc_env mod_summary source_modified mb_old_iface mod_index
524 = do
525
526 let msg what = case mHscMessage of
527 Just hscMessage -> hscMessage hsc_env mod_index what mod_summary
528 Nothing -> return ()
529
530 skip iface = do
531 msg UpToDate
532 return $ Left iface
533
534 compile mb_old_hash reason = do
535 msg reason
536 tc_result <- runHsc hsc_env $ genericHscFrontend mod_summary
537 return $ Right (tc_result, mb_old_hash)
538
539 stable = case source_modified of
540 SourceUnmodifiedAndStable -> True
541 _ -> False
542
543 case m_tc_result of
544 Just tc_result
545 | not always_do_basic_recompilation_check ->
546 return $ Right (tc_result, Nothing)
547 _ -> do
548 (recomp_reqd, mb_checked_iface)
549 <- {-# SCC "checkOldIface" #-}
550 checkOldIface hsc_env mod_summary
551 source_modified mb_old_iface
552 -- save the interface that comes back from checkOldIface.
553 -- In one-shot mode we don't have the old iface until this
554 -- point, when checkOldIface reads it from the disk.
555 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
556
557 case mb_checked_iface of
558 Just iface | not (recompileRequired recomp_reqd) ->
559 -- If the module used TH splices when it was last
560 -- compiled, then the recompilation check is not
561 -- accurate enough (#481) and we must ignore
562 -- it. However, if the module is stable (none of
563 -- the modules it depends on, directly or
564 -- indirectly, changed), then we *can* skip
565 -- recompilation. This is why the SourceModified
566 -- type contains SourceUnmodifiedAndStable, and
567 -- it's pretty important: otherwise ghc --make
568 -- would always recompile TH modules, even if
569 -- nothing at all has changed. Stability is just
570 -- the same check that make is doing for us in
571 -- one-shot mode.
572 case m_tc_result of
573 Nothing
574 | mi_used_th iface && not stable ->
575 compile mb_old_hash (RecompBecause "TH")
576 _ ->
577 skip iface
578 _ ->
579 case m_tc_result of
580 Nothing -> compile mb_old_hash recomp_reqd
581 Just tc_result ->
582 return $ Right (tc_result, mb_old_hash)
583
584 genericHscFrontend :: ModSummary -> Hsc TcGblEnv
585 genericHscFrontend mod_summary =
586 getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)
587
588 genericHscFrontend' :: ModSummary -> Hsc TcGblEnv
589 genericHscFrontend' mod_summary = hscFileFrontEnd mod_summary
590
591 --------------------------------------------------------------
592 -- Compilers
593 --------------------------------------------------------------
594
595 hscCompileOneShot :: HscEnv
596 -> ModSummary
597 -> SourceModified
598 -> IO HscStatus
599 hscCompileOneShot env =
600 lookupHook hscCompileOneShotHook hscCompileOneShot' (hsc_dflags env) env
601
602 -- Compile Haskell/boot in OneShot mode.
603 hscCompileOneShot' :: HscEnv
604 -> ModSummary
605 -> SourceModified
606 -> IO HscStatus
607 hscCompileOneShot' hsc_env mod_summary src_changed
608 = do
609 -- One-shot mode needs a knot-tying mutable variable for interface
610 -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
611 type_env_var <- newIORef emptyNameEnv
612 let mod = ms_mod mod_summary
613 hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
614
615 msg what = oneShotMsg hsc_env' what
616
617 skip = do msg UpToDate
618 dumpIfaceStats hsc_env'
619 return HscUpToDate
620
621 compile mb_old_hash reason = runHsc hsc_env' $ do
622 liftIO $ msg reason
623 tc_result <- genericHscFrontend mod_summary
624 guts0 <- hscDesugar' (ms_location mod_summary) tc_result
625 dflags <- getDynFlags
626 case hscTarget dflags of
627 HscNothing -> do
628 when (gopt Opt_WriteInterface dflags) $ liftIO $ do
629 (iface, changed, _details) <- hscSimpleIface hsc_env tc_result mb_old_hash
630 hscWriteIface dflags iface changed mod_summary
631 return HscNotGeneratingCode
632 _ ->
633 case ms_hsc_src mod_summary of
634 t | isHsBootOrSig t ->
635 do (iface, changed, _) <- hscSimpleIface' tc_result mb_old_hash
636 liftIO $ hscWriteIface dflags iface changed mod_summary
637 return HscUpdateBoot
638 _ ->
639 do guts <- hscSimplify' guts0
640 (iface, changed, _details, cgguts) <- hscNormalIface' guts mb_old_hash
641 liftIO $ hscWriteIface dflags iface changed mod_summary
642 return $ HscRecomp cgguts mod_summary
643
644 -- XXX This is always False, because in one-shot mode the
645 -- concept of stability does not exist. The driver never
646 -- passes SourceUnmodifiedAndStable in here.
647 stable = case src_changed of
648 SourceUnmodifiedAndStable -> True
649 _ -> False
650
651 (recomp_reqd, mb_checked_iface)
652 <- {-# SCC "checkOldIface" #-}
653 checkOldIface hsc_env' mod_summary src_changed Nothing
654 -- save the interface that comes back from checkOldIface.
655 -- In one-shot mode we don't have the old iface until this
656 -- point, when checkOldIface reads it from the disk.
657 let mb_old_hash = fmap mi_iface_hash mb_checked_iface
658
659 case mb_checked_iface of
660 Just iface | not (recompileRequired recomp_reqd) ->
661 -- If the module used TH splices when it was last compiled,
662 -- then the recompilation check is not accurate enough (#481)
663 -- and we must ignore it. However, if the module is stable
664 -- (none of the modules it depends on, directly or indirectly,
665 -- changed), then we *can* skip recompilation. This is why
666 -- the SourceModified type contains SourceUnmodifiedAndStable,
667 -- and it's pretty important: otherwise ghc --make would
668 -- always recompile TH modules, even if nothing at all has
669 -- changed. Stability is just the same check that make is
670 -- doing for us in one-shot mode.
671 if mi_used_th iface && not stable
672 then compile mb_old_hash (RecompBecause "TH")
673 else skip
674 _ ->
675 compile mb_old_hash recomp_reqd
676
677 --------------------------------------------------------------
678 -- NoRecomp handlers
679 --------------------------------------------------------------
680
681 genModDetails :: HscEnv -> ModIface -> IO ModDetails
682 genModDetails hsc_env old_iface
683 = do
684 new_details <- {-# SCC "tcRnIface" #-}
685 initIfaceCheck hsc_env (typecheckIface old_iface)
686 dumpIfaceStats hsc_env
687 return new_details
688
689 --------------------------------------------------------------
690 -- Progress displayers.
691 --------------------------------------------------------------
692
693 oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
694 oneShotMsg hsc_env recomp =
695 case recomp of
696 UpToDate ->
697 compilationProgressMsg (hsc_dflags hsc_env) $
698 "compilation IS NOT required"
699 _ ->
700 return ()
701
702 batchMsg :: Messager
703 batchMsg hsc_env mod_index recomp mod_summary =
704 case recomp of
705 MustCompile -> showMsg "Compiling " ""
706 UpToDate
707 | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " ""
708 | otherwise -> return ()
709 RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
710 where
711 dflags = hsc_dflags hsc_env
712 showMsg msg reason =
713 compilationProgressMsg dflags $
714 (showModuleIndex mod_index ++
715 msg ++ showModMsg dflags (hscTarget dflags)
716 (recompileRequired recomp) mod_summary)
717 ++ reason
718
719 --------------------------------------------------------------
720 -- FrontEnds
721 --------------------------------------------------------------
722
723 hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
724 hscFileFrontEnd mod_summary = do
725 hpm <- hscParse' mod_summary
726 hsc_env <- getHscEnv
727 tcg_env <- tcRnModule' hsc_env mod_summary False hpm
728 return tcg_env
729
730 --------------------------------------------------------------
731 -- Safe Haskell
732 --------------------------------------------------------------
733
734 -- Note [Safe Haskell Trust Check]
735 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736 -- Safe Haskell checks that an import is trusted according to the following
737 -- rules for an import of module M that resides in Package P:
738 --
739 -- * If M is recorded as Safe and all its trust dependencies are OK
740 -- then M is considered safe.
741 -- * If M is recorded as Trustworthy and P is considered trusted and
742 -- all M's trust dependencies are OK then M is considered safe.
743 --
744 -- By trust dependencies we mean that the check is transitive. So if
745 -- a module M that is Safe relies on a module N that is trustworthy,
746 -- importing module M will first check (according to the second case)
747 -- that N is trusted before checking M is trusted.
748 --
749 -- This is a minimal description, so please refer to the user guide
750 -- for more details. The user guide is also considered the authoritative
751 -- source in this matter, not the comments or code.
752
753
754 -- Note [Safe Haskell Inference]
755 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
756 -- Safe Haskell does Safe inference on modules that don't have any specific
757 -- safe haskell mode flag. The basic aproach to this is:
758 -- * When deciding if we need to do a Safe language check, treat
759 -- an unmarked module as having -XSafe mode specified.
760 -- * For checks, don't throw errors but return them to the caller.
761 -- * Caller checks if there are errors:
762 -- * For modules explicitly marked -XSafe, we throw the errors.
763 -- * For unmarked modules (inference mode), we drop the errors
764 -- and mark the module as being Unsafe.
765
766
767 -- | Check that the safe imports of the module being compiled are valid.
768 -- If not we either issue a compilation error if the module is explicitly
769 -- using Safe Haskell, or mark the module as unsafe if we're in safe
770 -- inference mode.
771 hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv
772 hscCheckSafeImports tcg_env = do
773 dflags <- getDynFlags
774 tcg_env' <- checkSafeImports dflags tcg_env
775 case safeLanguageOn dflags of
776 True -> do
777 -- XSafe: we nuke user written RULES
778 logWarnings $ warns dflags (tcg_rules tcg_env')
779 return tcg_env' { tcg_rules = [] }
780 False
781 -- SafeInferred: user defined RULES, so not safe
782 | safeInferOn dflags && not (null $ tcg_rules tcg_env')
783 -> markUnsafe tcg_env' $ warns dflags (tcg_rules tcg_env')
784
785 -- Trustworthy OR SafeInferred: 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 -> markUnsafe 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 -- [PackageKey]
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 &&
853 safeHaskell dflags == Sf_None
854 then True else s
855 return (m, l, s')
856
857 -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
858 cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
859 cond' v1@(m1,_,l1,s1) (_,_,_,s2)
860 | s1 /= s2
861 = throwErrors $ unitBag $ mkPlainErrMsg dflags l1
862 (text "Module" <+> ppr m1 <+>
863 (text $ "is imported both as a safe and unsafe import!"))
864 | otherwise
865 = return v1
866
867 -- easier interface to work with
868 checkSafe (_, _, False) = return Nothing
869 checkSafe (m, l, True ) = fst `fmap` hscCheckSafe' dflags m l
870
871 -- | Check that a module is safe to import.
872 --
873 -- We return True to indicate the import is safe and False otherwise
874 -- although in the False case an exception may be thrown first.
875 hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool
876 hscCheckSafe hsc_env m l = runHsc hsc_env $ do
877 dflags <- getDynFlags
878 pkgs <- snd `fmap` hscCheckSafe' dflags m l
879 when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs
880 errs <- getWarnings
881 return $ isEmptyBag errs
882
883 -- | Return if a module is trusted and the pkgs it depends on to be trusted.
884 hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageKey])
885 hscGetSafe hsc_env m l = runHsc hsc_env $ do
886 dflags <- getDynFlags
887 (self, pkgs) <- hscCheckSafe' dflags m l
888 good <- isEmptyBag `fmap` getWarnings
889 clearWarnings -- don't want them printed...
890 let pkgs' | Just p <- self = p:pkgs
891 | otherwise = pkgs
892 return (good, pkgs')
893
894 -- | Is a module trusted? If not, throw or log errors depending on the type.
895 -- Return (regardless of trusted or not) if the trust type requires the modules
896 -- own package be trusted and a list of other packages required to be trusted
897 -- (these later ones haven't been checked) but the own package trust has been.
898 hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageKey, [PackageKey])
899 hscCheckSafe' dflags m l = do
900 (tw, pkgs) <- isModSafe m l
901 case tw of
902 False -> return (Nothing, pkgs)
903 True | isHomePkg m -> return (Nothing, pkgs)
904 | otherwise -> return (Just $ modulePackageKey m, pkgs)
905 where
906 isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey])
907 isModSafe m l = do
908 iface <- lookup' m
909 case iface of
910 -- can't load iface to check trust!
911 Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l
912 $ text "Can't load the interface file for" <+> ppr m
913 <> text ", to check that it can be safely imported"
914
915 -- got iface, check trust
916 Just iface' ->
917 let trust = getSafeMode $ mi_trust iface'
918 trust_own_pkg = mi_trust_pkg iface'
919 -- check module is trusted
920 safeM = trust `elem` [Sf_Safe, Sf_Trustworthy]
921 -- check package is trusted
922 safeP = packageTrusted trust trust_own_pkg m
923 -- pkg trust reqs
924 pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface'
925 -- General errors we throw but Safe errors we log
926 errs = case (safeM, safeP) of
927 (True, True ) -> emptyBag
928 (True, False) -> pkgTrustErr
929 (False, _ ) -> modTrustErr
930 in do
931 logWarnings errs
932 return (trust == Sf_Trustworthy, pkgRs)
933
934 where
935 pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
936 sep [ ppr (moduleName m)
937 <> text ": Can't be safely imported!"
938 , text "The package (" <> ppr (modulePackageKey m)
939 <> text ") the module resides in isn't trusted."
940 ]
941 modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
942 sep [ ppr (moduleName m)
943 <> text ": Can't be safely imported!"
944 , text "The module itself isn't safe." ]
945
946 -- | Check the package a module resides in is trusted. Safe compiled
947 -- modules are trusted without requiring that their package is trusted. For
948 -- trustworthy modules, modules in the home package are trusted but
949 -- otherwise we check the package trust flag.
950 packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
951 packageTrusted Sf_None _ _ = False -- shouldn't hit these cases
952 packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness.
953 packageTrusted _ _ _
954 | not (packageTrustOn dflags) = True
955 packageTrusted Sf_Safe False _ = True
956 packageTrusted _ _ m
957 | isHomePkg m = True
958 | otherwise = trusted $ getPackageDetails dflags (modulePackageKey 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 == modulePackageKey m = True
983 | otherwise = False
984
985 -- | Check the list of packages are trusted.
986 checkPkgTrust :: DynFlags -> [PackageKey] -> 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 dflags pkg
995 = Nothing
996 | otherwise
997 = Just $ mkErrMsg dflags noSrcSpan (pkgQual dflags)
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 (potentially) 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. We only wipe the trust
1005 -- information when we aren't in a specific Safe Haskell mode.
1006 markUnsafe :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv
1007 markUnsafe tcg_env whyUnsafe = do
1008 dflags <- getDynFlags
1009
1010 when (wopt Opt_WarnUnsafe dflags)
1011 (logWarnings $ unitBag $
1012 mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags))
1013
1014 liftIO $ writeIORef (tcg_safeInfer tcg_env) False
1015 -- NOTE: Only wipe trust when not in an explicity safe haskell mode. Other
1016 -- times inference may be on but we are in Trustworthy mode -- so we want
1017 -- to record safe-inference failed but not wipe the trust dependencies.
1018 case safeHaskell dflags == Sf_None of
1019 True -> return $ tcg_env { tcg_imports = wiped_trust }
1020 False -> return tcg_env
1021
1022 where
1023 wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] }
1024 pprMod = ppr $ moduleName $ tcg_mod tcg_env
1025 whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!"
1026 , text "Reason:"
1027 , nest 4 $ (vcat $ badFlags df) $+$
1028 (vcat $ pprErrMsgBagWithLoc whyUnsafe) $+$
1029 (vcat $ badInsts $ tcg_insts tcg_env)
1030 ]
1031 badFlags df = concat $ map (badFlag df) unsafeFlagsForInfer
1032 badFlag df (str,loc,on,_)
1033 | on df = [mkLocMessage SevOutput (loc df) $
1034 text str <+> text "is not allowed in Safe Haskell"]
1035 | otherwise = []
1036 badInsts insts = concat $ map badInst insts
1037 badInst ins | overlapMode (is_flag ins) /= NoOverlap
1038 = [mkLocMessage SevOutput (nameSrcSpan $ getName $ is_dfun ins) $
1039 ppr (overlapMode $ is_flag ins) <+>
1040 text "overlap mode isn't allowed in Safe Haskell"]
1041 | otherwise = []
1042
1043
1044 -- | Figure out the final correct safe haskell mode
1045 hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode
1046 hscGetSafeMode tcg_env = do
1047 dflags <- getDynFlags
1048 liftIO $ finalSafeMode dflags tcg_env
1049
1050 --------------------------------------------------------------
1051 -- Simplifiers
1052 --------------------------------------------------------------
1053
1054 hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
1055 hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts
1056
1057 hscSimplify' :: ModGuts -> Hsc ModGuts
1058 hscSimplify' ds_result = do
1059 hsc_env <- getHscEnv
1060 {-# SCC "Core2Core" #-}
1061 liftIO $ core2core hsc_env ds_result
1062
1063 --------------------------------------------------------------
1064 -- Interface generators
1065 --------------------------------------------------------------
1066
1067 hscSimpleIface :: HscEnv
1068 -> TcGblEnv
1069 -> Maybe Fingerprint
1070 -> IO (ModIface, Bool, ModDetails)
1071 hscSimpleIface hsc_env tc_result mb_old_iface
1072 = runHsc hsc_env $ hscSimpleIface' tc_result mb_old_iface
1073
1074 hscSimpleIface' :: TcGblEnv
1075 -> Maybe Fingerprint
1076 -> Hsc (ModIface, Bool, ModDetails)
1077 hscSimpleIface' tc_result mb_old_iface = do
1078 hsc_env <- getHscEnv
1079 details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
1080 safe_mode <- hscGetSafeMode tc_result
1081 (new_iface, no_change)
1082 <- {-# SCC "MkFinalIface" #-}
1083 ioMsgMaybe $
1084 mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result
1085 -- And the answer is ...
1086 liftIO $ dumpIfaceStats hsc_env
1087 return (new_iface, no_change, details)
1088
1089 hscNormalIface :: HscEnv
1090 -> ModGuts
1091 -> Maybe Fingerprint
1092 -> IO (ModIface, Bool, ModDetails, CgGuts)
1093 hscNormalIface hsc_env simpl_result mb_old_iface =
1094 runHsc hsc_env $ hscNormalIface' simpl_result mb_old_iface
1095
1096 hscNormalIface' :: ModGuts
1097 -> Maybe Fingerprint
1098 -> Hsc (ModIface, Bool, ModDetails, CgGuts)
1099 hscNormalIface' simpl_result mb_old_iface = do
1100 hsc_env <- getHscEnv
1101 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
1102 liftIO $ tidyProgram hsc_env simpl_result
1103
1104 -- BUILD THE NEW ModIface and ModDetails
1105 -- and emit external core if necessary
1106 -- This has to happen *after* code gen so that the back-end
1107 -- info has been set. Not yet clear if it matters waiting
1108 -- until after code output
1109 (new_iface, no_change)
1110 <- {-# SCC "MkFinalIface" #-}
1111 ioMsgMaybe $
1112 mkIface hsc_env mb_old_iface details simpl_result
1113
1114 liftIO $ dumpIfaceStats hsc_env
1115
1116 -- Return the prepared code.
1117 return (new_iface, no_change, details, cg_guts)
1118
1119 --------------------------------------------------------------
1120 -- BackEnd combinators
1121 --------------------------------------------------------------
1122
1123 hscWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO ()
1124 hscWriteIface dflags iface no_change mod_summary = do
1125 let ifaceFile = ml_hi_file (ms_location mod_summary)
1126 unless no_change $
1127 {-# SCC "writeIface" #-}
1128 writeIfaceFile dflags ifaceFile iface
1129 whenGeneratingDynamicToo dflags $ do
1130 -- TODO: We should do a no_change check for the dynamic
1131 -- interface file too
1132 -- TODO: Should handle the dynamic hi filename properly
1133 let dynIfaceFile = replaceExtension ifaceFile (dynHiSuf dflags)
1134 dynIfaceFile' = addBootSuffix_maybe (mi_boot iface) dynIfaceFile
1135 dynDflags = dynamicTooMkDynamicDynFlags dflags
1136 writeIfaceFile dynDflags dynIfaceFile' iface
1137
1138 -- | Compile to hard-code.
1139 hscGenHardCode :: HscEnv -> CgGuts -> ModSummary -> FilePath
1140 -> IO (FilePath, Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
1141 hscGenHardCode hsc_env cgguts mod_summary output_filename = do
1142 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
1143 -- From now on, we just use the bits we need.
1144 cg_module = this_mod,
1145 cg_binds = core_binds,
1146 cg_tycons = tycons,
1147 cg_foreign = foreign_stubs0,
1148 cg_dep_pkgs = dependencies,
1149 cg_hpc_info = hpc_info } = cgguts
1150 dflags = hsc_dflags hsc_env
1151 location = ms_location mod_summary
1152 data_tycons = filter isDataTyCon tycons
1153 -- cg_tycons includes newtypes, for the benefit of External Core,
1154 -- but we don't generate any code for newtypes
1155
1156 -------------------
1157 -- PREPARE FOR CODE GENERATION
1158 -- Do saturation and convert to A-normal form
1159 prepd_binds <- {-# SCC "CorePrep" #-}
1160 corePrepPgm dflags hsc_env core_binds data_tycons ;
1161 ----------------- Convert to STG ------------------
1162 (stg_binds, cost_centre_info)
1163 <- {-# SCC "CoreToStg" #-}
1164 myCoreToStg dflags this_mod prepd_binds
1165
1166 let prof_init = profilingInitCode this_mod cost_centre_info
1167 foreign_stubs = foreign_stubs0 `appendStubC` prof_init
1168
1169 ------------------ Code generation ------------------
1170
1171 -- The back-end is streamed: each top-level function goes
1172 -- from Stg all the way to asm before dealing with the next
1173 -- top-level function, so showPass isn't very useful here.
1174 -- Hence we have one showPass for the whole backend, the
1175 -- next showPass after this will be "Assembler".
1176 showPass dflags "CodeGen"
1177
1178 cmms <- {-# SCC "StgCmm" #-}
1179 doCodeGen hsc_env this_mod data_tycons
1180 cost_centre_info
1181 stg_binds hpc_info
1182
1183 ------------------ Code output -----------------------
1184 rawcmms0 <- {-# SCC "cmmToRawCmm" #-}
1185 cmmToRawCmm dflags cmms
1186
1187 let dump a = do dumpIfSet_dyn dflags Opt_D_dump_cmm_raw "Raw Cmm"
1188 (ppr a)
1189 return a
1190 rawcmms1 = Stream.mapM dump rawcmms0
1191
1192 (output_filename, (_stub_h_exists, stub_c_exists))
1193 <- {-# SCC "codeOutput" #-}
1194 codeOutput dflags this_mod output_filename location
1195 foreign_stubs dependencies rawcmms1
1196 return (output_filename, stub_c_exists)
1197
1198
1199 hscInteractive :: HscEnv
1200 -> CgGuts
1201 -> ModSummary
1202 -> IO (Maybe FilePath, CompiledByteCode, ModBreaks)
1203 #ifdef GHCI
1204 hscInteractive hsc_env cgguts mod_summary = do
1205 let dflags = hsc_dflags hsc_env
1206 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
1207 -- From now on, we just use the bits we need.
1208 cg_module = this_mod,
1209 cg_binds = core_binds,
1210 cg_tycons = tycons,
1211 cg_foreign = foreign_stubs,
1212 cg_modBreaks = mod_breaks } = cgguts
1213
1214 location = ms_location mod_summary
1215 data_tycons = filter isDataTyCon tycons
1216 -- cg_tycons includes newtypes, for the benefit of External Core,
1217 -- but we don't generate any code for newtypes
1218
1219 -------------------
1220 -- PREPARE FOR CODE GENERATION
1221 -- Do saturation and convert to A-normal form
1222 prepd_binds <- {-# SCC "CorePrep" #-}
1223 corePrepPgm dflags hsc_env core_binds data_tycons
1224 ----------------- Generate byte code ------------------
1225 comp_bc <- byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks
1226 ------------------ Create f-x-dynamic C-side stuff ---
1227 (_istub_h_exists, istub_c_exists)
1228 <- outputForeignStubs dflags this_mod location foreign_stubs
1229 return (istub_c_exists, comp_bc, mod_breaks)
1230 #else
1231 hscInteractive _ _ = panic "GHC not compiled with interpreter"
1232 #endif
1233
1234 ------------------------------
1235
1236 hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO ()
1237 hscCompileCmmFile hsc_env filename output_filename = runHsc hsc_env $ do
1238 let dflags = hsc_dflags hsc_env
1239 cmm <- ioMsgMaybe $ parseCmmFile dflags filename
1240 liftIO $ do
1241 us <- mkSplitUniqSupply 'S'
1242 let initTopSRT = initUs_ us emptySRT
1243 dumpIfSet_dyn dflags Opt_D_dump_cmm "Parsed Cmm" (ppr cmm)
1244 (_, cmmgroup) <- cmmPipeline hsc_env initTopSRT cmm
1245 rawCmms <- cmmToRawCmm dflags (Stream.yield cmmgroup)
1246 _ <- codeOutput dflags no_mod output_filename no_loc NoStubs [] rawCmms
1247 return ()
1248 where
1249 no_mod = panic "hscCmmFile: no_mod"
1250 no_loc = ModLocation{ ml_hs_file = Just filename,
1251 ml_hi_file = panic "hscCmmFile: no hi file",
1252 ml_obj_file = panic "hscCmmFile: no obj file" }
1253
1254 -------------------- Stuff for new code gen ---------------------
1255
1256 doCodeGen :: HscEnv -> Module -> [TyCon]
1257 -> CollectedCCs
1258 -> [StgBinding]
1259 -> HpcInfo
1260 -> IO (Stream IO CmmGroup ())
1261 -- Note we produce a 'Stream' of CmmGroups, so that the
1262 -- backend can be run incrementally. Otherwise it generates all
1263 -- the C-- up front, which has a significant space cost.
1264 doCodeGen hsc_env this_mod data_tycons
1265 cost_centre_info stg_binds hpc_info = do
1266 let dflags = hsc_dflags hsc_env
1267
1268 let cmm_stream :: Stream IO CmmGroup ()
1269 cmm_stream = {-# SCC "StgCmm" #-}
1270 StgCmm.codeGen dflags this_mod data_tycons
1271 cost_centre_info stg_binds hpc_info
1272
1273 -- codegen consumes a stream of CmmGroup, and produces a new
1274 -- stream of CmmGroup (not necessarily synchronised: one
1275 -- CmmGroup on input may produce many CmmGroups on output due
1276 -- to proc-point splitting).
1277
1278 let dump1 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm
1279 "Cmm produced by new codegen" (ppr a)
1280 return a
1281
1282 ppr_stream1 = Stream.mapM dump1 cmm_stream
1283
1284 -- We are building a single SRT for the entire module, so
1285 -- we must thread it through all the procedures as we cps-convert them.
1286 us <- mkSplitUniqSupply 'S'
1287
1288 -- When splitting, we generate one SRT per split chunk, otherwise
1289 -- we generate one SRT for the whole module.
1290 let
1291 pipeline_stream
1292 | gopt Opt_SplitObjs dflags
1293 = {-# SCC "cmmPipeline" #-}
1294 let run_pipeline us cmmgroup = do
1295 let (topSRT', us') = initUs us emptySRT
1296 (topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT' cmmgroup
1297 let srt | isEmptySRT topSRT = []
1298 | otherwise = srtToData topSRT
1299 return (us', srt ++ cmmgroup)
1300
1301 in do _ <- Stream.mapAccumL run_pipeline us ppr_stream1
1302 return ()
1303
1304 | otherwise
1305 = {-# SCC "cmmPipeline" #-}
1306 let initTopSRT = initUs_ us emptySRT
1307 run_pipeline = cmmPipeline hsc_env
1308 in do topSRT <- Stream.mapAccumL run_pipeline initTopSRT ppr_stream1
1309 Stream.yield (srtToData topSRT)
1310
1311 let
1312 dump2 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm "Output Cmm" $ ppr a
1313 return a
1314
1315 ppr_stream2 = Stream.mapM dump2 pipeline_stream
1316
1317 return ppr_stream2
1318
1319
1320
1321 myCoreToStg :: DynFlags -> Module -> CoreProgram
1322 -> IO ( [StgBinding] -- output program
1323 , CollectedCCs) -- cost centre info (declared and used)
1324 myCoreToStg dflags this_mod prepd_binds = do
1325 stg_binds
1326 <- {-# SCC "Core2Stg" #-}
1327 coreToStg dflags this_mod prepd_binds
1328
1329 (stg_binds2, cost_centre_info)
1330 <- {-# SCC "Stg2Stg" #-}
1331 stg2stg dflags this_mod stg_binds
1332
1333 return (stg_binds2, cost_centre_info)
1334
1335
1336 {- **********************************************************************
1337 %* *
1338 \subsection{Compiling a do-statement}
1339 %* *
1340 %********************************************************************* -}
1341
1342 {-
1343 When the UnlinkedBCOExpr is linked you get an HValue of type *IO [HValue]* When
1344 you run it you get a list of HValues that should be the same length as the list
1345 of names; add them to the ClosureEnv.
1346
1347 A naked expression returns a singleton Name [it]. The stmt is lifted into the
1348 IO monad as explained in Note [Interactively-bound Ids in GHCi] in HscTypes
1349 -}
1350
1351 #ifdef GHCI
1352 -- | Compile a stmt all the way to an HValue, but don't run it
1353 --
1354 -- We return Nothing to indicate an empty statement (or comment only), not a
1355 -- parse error.
1356 hscStmt :: HscEnv -> String -> IO (Maybe ([Id], IO [HValue], FixityEnv))
1357 hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1
1358
1359 -- | Compile a stmt all the way to an HValue, but don't run it
1360 --
1361 -- We return Nothing to indicate an empty statement (or comment only), not a
1362 -- parse error.
1363 hscStmtWithLocation :: HscEnv
1364 -> String -- ^ The statement
1365 -> String -- ^ The source
1366 -> Int -- ^ Starting line
1367 -> IO (Maybe ([Id], IO [HValue], FixityEnv))
1368 hscStmtWithLocation hsc_env0 stmt source linenumber =
1369 runInteractiveHsc hsc_env0 $ do
1370 maybe_stmt <- hscParseStmtWithLocation source linenumber stmt
1371 case maybe_stmt of
1372 Nothing -> return Nothing
1373
1374 Just parsed_stmt -> do
1375 -- Rename and typecheck it
1376 hsc_env <- getHscEnv
1377 (ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env parsed_stmt
1378
1379 -- Desugar it
1380 ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env tc_expr
1381 liftIO (lintInteractiveExpr "desugar expression" hsc_env ds_expr)
1382 handleWarnings
1383
1384 -- Then code-gen, and link it
1385 -- It's important NOT to have package 'interactive' as thisPackageKey
1386 -- for linking, else we try to link 'main' and can't find it.
1387 -- Whereas the linker already knows to ignore 'interactive'
1388 let src_span = srcLocSpan interactiveSrcLoc
1389 hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr
1390 let hval_io = unsafeCoerce# hval :: IO [HValue]
1391
1392 return $ Just (ids, hval_io, fix_env)
1393
1394 -- | Compile a decls
1395 hscDecls :: HscEnv
1396 -> String -- ^ The statement
1397 -> IO ([TyThing], InteractiveContext)
1398 hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1
1399
1400 -- | Compile a decls
1401 hscDeclsWithLocation :: HscEnv
1402 -> String -- ^ The statement
1403 -> String -- ^ The source
1404 -> Int -- ^ Starting line
1405 -> IO ([TyThing], InteractiveContext)
1406 hscDeclsWithLocation hsc_env0 str source linenumber =
1407 runInteractiveHsc hsc_env0 $ do
1408 L _ (HsModule{ hsmodDecls = decls }) <-
1409 hscParseThingWithLocation source linenumber parseModule str
1410
1411 {- Rename and typecheck it -}
1412 hsc_env <- getHscEnv
1413 tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env decls
1414
1415 {- Grab the new instances -}
1416 -- We grab the whole environment because of the overlapping that may have
1417 -- been done. See the notes at the definition of InteractiveContext
1418 -- (ic_instances) for more details.
1419 let finsts = tcg_fam_insts tc_gblenv
1420 insts = tcg_insts tc_gblenv
1421
1422 let defaults = tcg_default tc_gblenv
1423
1424 {- Desugar it -}
1425 -- We use a basically null location for iNTERACTIVE
1426 let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing,
1427 ml_hi_file = panic "hsDeclsWithLocation:ml_hi_file",
1428 ml_obj_file = panic "hsDeclsWithLocation:ml_hi_file"}
1429 ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv
1430
1431 {- Simplify -}
1432 simpl_mg <- liftIO $ hscSimplify hsc_env ds_result
1433
1434 {- Tidy -}
1435 (tidy_cg, _mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg
1436
1437 let dflags = hsc_dflags hsc_env
1438 !CgGuts{ cg_module = this_mod,
1439 cg_binds = core_binds,
1440 cg_tycons = tycons,
1441 cg_modBreaks = mod_breaks } = tidy_cg
1442 data_tycons = filter isDataTyCon tycons
1443
1444 {- Prepare For Code Generation -}
1445 -- Do saturation and convert to A-normal form
1446 prepd_binds <- {-# SCC "CorePrep" #-}
1447 liftIO $ corePrepPgm dflags hsc_env core_binds data_tycons
1448
1449 {- Generate byte code -}
1450 cbc <- liftIO $ byteCodeGen dflags this_mod
1451 prepd_binds data_tycons mod_breaks
1452
1453 let src_span = srcLocSpan interactiveSrcLoc
1454 liftIO $ linkDecls hsc_env src_span cbc
1455
1456 let tcs = filterOut isImplicitTyCon (mg_tcs simpl_mg)
1457
1458 ext_ids = [ id | id <- bindersOfBinds core_binds
1459 , isExternalName (idName id)
1460 , not (isDFunId id || isImplicitId id) ]
1461 -- We only need to keep around the external bindings
1462 -- (as decided by TidyPgm), since those are the only ones
1463 -- that might be referenced elsewhere.
1464 -- The DFunIds are in 'insts' (see Note [ic_tythings] in HscTypes
1465 -- Implicit Ids are implicit in tcs
1466
1467 tythings = map AnId ext_ids ++ map ATyCon tcs
1468
1469 let icontext = hsc_IC hsc_env
1470 ictxt1 = extendInteractiveContext icontext tythings
1471 ictxt = ictxt1 { ic_instances = (insts, finsts)
1472 , ic_default = defaults }
1473
1474 return (tythings, ictxt)
1475
1476 hscImport :: HscEnv -> String -> IO (ImportDecl RdrName)
1477 hscImport hsc_env str = runInteractiveHsc hsc_env $ do
1478 (L _ (HsModule{hsmodImports=is})) <-
1479 hscParseThing parseModule str
1480 case is of
1481 [i] -> return (unLoc i)
1482 _ -> liftIO $ throwOneError $
1483 mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan $
1484 ptext (sLit "parse error in import declaration")
1485
1486 -- | Typecheck an expression (but don't run it)
1487 -- Returns its most general type
1488 hscTcExpr :: HscEnv
1489 -> String -- ^ The expression
1490 -> IO Type
1491 hscTcExpr hsc_env0 expr = runInteractiveHsc hsc_env0 $ do
1492 hsc_env <- getHscEnv
1493 maybe_stmt <- hscParseStmt expr
1494 case maybe_stmt of
1495 Just (L _ (BodyStmt expr _ _ _)) ->
1496 ioMsgMaybe $ tcRnExpr hsc_env expr
1497 _ ->
1498 throwErrors $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan
1499 (text "not an expression:" <+> quotes (text expr))
1500
1501 -- | Find the kind of a type
1502 -- Currently this does *not* generalise the kinds of the type
1503 hscKcType
1504 :: HscEnv
1505 -> Bool -- ^ Normalise the type
1506 -> String -- ^ The type as a string
1507 -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind
1508 hscKcType hsc_env0 normalise str = runInteractiveHsc hsc_env0 $ do
1509 hsc_env <- getHscEnv
1510 ty <- hscParseType str
1511 ioMsgMaybe $ tcRnType hsc_env normalise ty
1512
1513 hscParseStmt :: String -> Hsc (Maybe (GhciLStmt RdrName))
1514 hscParseStmt = hscParseThing parseStmt
1515
1516 hscParseStmtWithLocation :: String -> Int -> String
1517 -> Hsc (Maybe (GhciLStmt RdrName))
1518 hscParseStmtWithLocation source linenumber stmt =
1519 hscParseThingWithLocation source linenumber parseStmt stmt
1520
1521 hscParseType :: String -> Hsc (LHsType RdrName)
1522 hscParseType = hscParseThing parseType
1523 #endif
1524
1525 hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)
1526 hscParseIdentifier hsc_env str =
1527 runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str
1528
1529 hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing
1530 hscParseThing = hscParseThingWithLocation "<interactive>" 1
1531
1532 hscParseThingWithLocation :: (Outputable thing) => String -> Int
1533 -> Lexer.P thing -> String -> Hsc thing
1534 hscParseThingWithLocation source linenumber parser str
1535 = {-# SCC "Parser" #-} do
1536 dflags <- getDynFlags
1537 liftIO $ showPass dflags "Parser"
1538
1539 let buf = stringToStringBuffer str
1540 loc = mkRealSrcLoc (fsLit source) linenumber 1
1541
1542 case unP parser (mkPState dflags buf loc) of
1543 PFailed span err -> do
1544 let msg = mkPlainErrMsg dflags span err
1545 throwErrors $ unitBag msg
1546
1547 POk pst thing -> do
1548 logWarningsReportErrors (getMessages pst)
1549 liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
1550 return thing
1551
1552 hscCompileCore :: HscEnv -> Bool -> SafeHaskellMode -> ModSummary
1553 -> CoreProgram -> FilePath -> IO ()
1554 hscCompileCore hsc_env simplify safe_mode mod_summary binds output_filename
1555 = runHsc hsc_env $ do
1556 guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) safe_mode binds)
1557 (iface, changed, _details, cgguts) <- hscNormalIface' guts Nothing
1558 liftIO $ hscWriteIface (hsc_dflags hsc_env) iface changed mod_summary
1559 _ <- liftIO $ hscGenHardCode hsc_env cgguts mod_summary output_filename
1560 return ()
1561
1562 where
1563 maybe_simplify mod_guts | simplify = hscSimplify' mod_guts
1564 | otherwise = return mod_guts
1565
1566 -- Makes a "vanilla" ModGuts.
1567 mkModGuts :: Module -> SafeHaskellMode -> CoreProgram -> ModGuts
1568 mkModGuts mod safe binds =
1569 ModGuts {
1570 mg_module = mod,
1571 mg_boot = False,
1572 mg_exports = [],
1573 mg_deps = noDependencies,
1574 mg_dir_imps = emptyModuleEnv,
1575 mg_used_names = emptyNameSet,
1576 mg_used_th = False,
1577 mg_rdr_env = emptyGlobalRdrEnv,
1578 mg_fix_env = emptyFixityEnv,
1579 mg_tcs = [],
1580 mg_insts = [],
1581 mg_fam_insts = [],
1582 mg_patsyns = [],
1583 mg_rules = [],
1584 mg_vect_decls = [],
1585 mg_binds = binds,
1586 mg_foreign = NoStubs,
1587 mg_warns = NoWarnings,
1588 mg_anns = [],
1589 mg_hpc_info = emptyHpcInfo False,
1590 mg_modBreaks = emptyModBreaks,
1591 mg_vect_info = noVectInfo,
1592 mg_inst_env = emptyInstEnv,
1593 mg_fam_inst_env = emptyFamInstEnv,
1594 mg_safe_haskell = safe,
1595 mg_trust_pkg = False,
1596 mg_dependent_files = []
1597 }
1598
1599
1600 {- **********************************************************************
1601 %* *
1602 Desugar, simplify, convert to bytecode, and link an expression
1603 %* *
1604 %********************************************************************* -}
1605
1606 #ifdef GHCI
1607 hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
1608 hscCompileCoreExpr hsc_env =
1609 lookupHook hscCompileCoreExprHook hscCompileCoreExpr' (hsc_dflags hsc_env) hsc_env
1610
1611 hscCompileCoreExpr' :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
1612 hscCompileCoreExpr' hsc_env srcspan ds_expr
1613 | rtsIsProfiled
1614 = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler")
1615 -- Otherwise you get a seg-fault when you run it
1616
1617 | otherwise
1618 = do { let dflags = hsc_dflags hsc_env
1619
1620 {- Simplify it -}
1621 ; simpl_expr <- simplifyExpr dflags ds_expr
1622
1623 {- Tidy it (temporary, until coreSat does cloning) -}
1624 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1625
1626 {- Prepare for codegen -}
1627 ; prepd_expr <- corePrepExpr dflags hsc_env tidy_expr
1628
1629 {- Lint if necessary -}
1630 ; lintInteractiveExpr "hscCompileExpr" hsc_env prepd_expr
1631
1632 {- Convert to BCOs -}
1633 ; bcos <- coreExprToBCOs dflags (icInteractiveModule (hsc_IC hsc_env)) prepd_expr
1634
1635 {- link it -}
1636 ; hval <- linkExpr hsc_env srcspan bcos
1637
1638 ; return hval }
1639 #endif
1640
1641
1642 {- **********************************************************************
1643 %* *
1644 Statistics on reading interfaces
1645 %* *
1646 %********************************************************************* -}
1647
1648 dumpIfaceStats :: HscEnv -> IO ()
1649 dumpIfaceStats hsc_env = do
1650 eps <- readIORef (hsc_EPS hsc_env)
1651 dumpIfSet dflags (dump_if_trace || dump_rn_stats)
1652 "Interface statistics"
1653 (ifaceStats eps)
1654 where
1655 dflags = hsc_dflags hsc_env
1656 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1657 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1658
1659
1660 {- **********************************************************************
1661 %* *
1662 Progress Messages: Module i of n
1663 %* *
1664 %********************************************************************* -}
1665
1666 showModuleIndex :: (Int, Int) -> String
1667 showModuleIndex (i,n) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1668 where
1669 n_str = show n
1670 i_str = show i
1671 padded = replicate (length n_str - length i_str) ' ' ++ i_str