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