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