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