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