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