2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 ( newHscEnv, hscCmmFile
13 , hscStmt, hscTcExpr, hscKcType
16 , hscCompileOneShot -- :: Compiler HscStatus
17 , hscCompileMake -- :: Compiler (HscStatus, ModIface, ModDetails)
18 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
20 , InteractiveStatus (..)
24 #include "HsVersions.h"
27 import HsSyn ( Stmt(..), LHsExpr, LStmt, LHsType )
28 import Module ( Module )
29 import CodeOutput ( outputForeignStubs )
30 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
31 import Linker ( HValue, linkExpr )
32 import CoreTidy ( tidyExpr )
33 import CorePrep ( corePrepExpr )
34 import Flattening ( flattenExpr )
35 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
37 import PrelNames ( iNTERACTIVE )
39 import CoreLint ( lintUnfolding )
40 import DsMeta ( templateHaskellNames )
41 import SrcLoc ( noSrcLoc )
42 import VarEnv ( emptyTidyEnv )
46 import Module ( emptyModuleEnv, ModLocation(..) )
47 import RdrName ( GlobalRdrEnv, RdrName )
48 import HsSyn ( HsModule, LHsBinds, HsGroup, LIE, LImportDecl )
49 import SrcLoc ( Located(..) )
50 import StringBuffer ( hGetStringBuffer, stringToStringBuffer )
52 import Lexer ( P(..), ParseResult(..), mkPState )
53 import SrcLoc ( mkSrcLoc )
54 import TcRnDriver ( tcRnModule, tcRnExtCore )
55 import TcIface ( typecheckIface )
56 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
57 import IfaceEnv ( initNameCache )
58 import LoadIface ( ifaceStats, initExternalPackageState )
59 import PrelInfo ( wiredInThings, basicKnownKeyNames )
60 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
61 import Desugar ( deSugar )
62 import Flattening ( flatten )
63 import SimplCore ( core2core )
64 import TidyPgm ( tidyProgram, mkBootModDetails )
65 import CorePrep ( corePrepPgm )
66 import CoreToStg ( coreToStg )
67 import TyCon ( isDataTyCon )
68 import Packages ( mkHomeModules )
69 import Name ( Name, NamedThing(..) )
70 import SimplStg ( stg2stg )
71 import CodeGen ( codeGen )
72 import CmmParse ( parseCmmFile )
73 import CodeOutput ( codeOutput )
77 import UniqSupply ( mkSplitUniqSupply )
80 import HscStats ( ppSourceStats )
82 import MkExternalCore ( emitExternalCore )
84 import ParserCoreUtils
86 import Maybes ( expectJust )
87 import Bag ( unitBag )
90 import DATA_IOREF ( newIORef, readIORef )
94 %************************************************************************
98 %************************************************************************
101 newHscEnv :: DynFlags -> IO HscEnv
103 = do { eps_var <- newIORef initExternalPackageState
104 ; us <- mkSplitUniqSupply 'r'
105 ; nc_var <- newIORef (initNameCache us knownKeyNames)
106 ; fc_var <- newIORef emptyModuleEnv
107 ; return (HscEnv { hsc_dflags = dflags,
110 hsc_IC = emptyInteractiveContext,
111 hsc_HPT = emptyHomePackageTable,
114 hsc_FC = fc_var } ) }
117 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
118 -- where templateHaskellNames are defined
119 knownKeyNames = map getName wiredInThings
120 ++ basicKnownKeyNames
122 ++ templateHaskellNames
127 %************************************************************************
129 The main compiler pipeline
131 %************************************************************************
133 --------------------------------
134 The compilation proper
135 --------------------------------
138 It's the task of the compilation proper to compile Haskell, hs-boot and
139 core files to either byte-code, hard-code (C, asm, Java, ect) or to
140 nothing at all (the module is still parsed and type-checked. This
141 feature is mostly used by IDE's and the likes).
142 Compilation can happen in either 'one-shot', 'make', or 'interactive'
143 mode. 'One-shot' mode targets hard-code, 'make' mode targets hard-code
144 and nothing, and 'interactive' mode targets byte-code. The modes are
145 kept separate because of their different types.
146 In 'one-shot' mode, we're only compiling a single file and can therefore
147 discard the new ModIface and ModDetails. This is also the reason it only
148 targets hard-code; compiling to byte-code or nothing doesn't make sense
149 when we discard the result. 'Make' mode is like 'one-shot' except that we
150 keep the resulting ModIface and ModDetails. 'Make' mode doesn't target
151 byte-code since that require us to return the newly compiled byte-code.
152 'Interactive' mode is similar to 'make' mode except that we return
153 the compiled byte-code together with the ModIface and ModDetails.
154 Trying to compile a hs-boot file to byte-code will result in a run-time
155 error. This is the only thing that isn't caught by the type-system.
162 (Located (HsModule RdrName))
164 (Maybe (HsGroup Name,[LImportDecl Name],Maybe [LIE Name]))
166 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
169 -- Status of a compilation to hard-code or nothing.
172 | HscRecomp Bool -- Has stub files.
173 -- This is a hack. We can't compile C files here
174 -- since it's done in DriverPipeline. For now we
175 -- just return True if we want the caller to compile
178 -- Status of a compilation to byte-code.
179 data InteractiveStatus
180 = InteractiveNoRecomp
181 | InteractiveRecomp Bool -- Same as HscStatus
184 type NoRecomp result = HscEnv -> ModSummary -> Bool -> ModIface -> Maybe (Int,Int) -> IO result
185 type FrontEnd core = HscEnv -> ModSummary -> Maybe (Int,Int) -> IO (Maybe core)
186 type BackEnd core prepCore = HscEnv -> ModSummary -> Maybe ModIface -> core -> IO prepCore
187 type CodeGen prepCore result = HscEnv -> ModSummary -> prepCore -> IO result
189 type Compiler result = HscEnv
191 -> Bool -- True <=> source unchanged
192 -> Bool -- True <=> have an object file (for msgs only)
193 -> Maybe ModIface -- Old interface, if available
194 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
198 -- This functions checks if recompilation is necessary and
199 -- then combines the FrontEnd, BackEnd and CodeGen to a
201 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
203 -> BackEnd core prepCore
204 -> CodeGen prepCore result
206 hscMkCompiler norecomp frontend backend codegen
207 hsc_env mod_summary source_unchanged
208 have_object mbOldIface mbModIndex
209 = do (recomp_reqd, mbCheckedIface)
210 <- {-# SCC "checkOldIface" #-}
211 checkOldIface hsc_env mod_summary
212 source_unchanged mbOldIface
213 case mbCheckedIface of
214 Just iface | not recomp_reqd
215 -> do result <- norecomp hsc_env mod_summary have_object iface mbModIndex
218 -> do mbCore <- frontend hsc_env mod_summary mbModIndex
223 -> do prepCore <- backend hsc_env mod_summary
225 result <- codegen hsc_env mod_summary prepCore
228 --------------------------------------------------------------
230 --------------------------------------------------------------
232 -- Compile Haskell, boot and extCore in OneShot mode.
233 hscCompileOneShot :: Compiler HscStatus
234 hscCompileOneShot hsc_env mod_summary =
235 compiler hsc_env mod_summary
236 where mkComp = hscMkCompiler (norecompOneShot HscNoRecomp)
238 = case ms_hsc_src mod_summary of
240 -> mkComp hscCoreFrontEnd hscNewBackEnd hscCodeGenOneShot
243 -> mkComp hscFileFrontEnd hscNewBackEnd hscCodeGenOneShot
245 -> mkComp hscFileFrontEnd hscNewBootBackEnd
246 (hscCodeGenConst (HscRecomp False))
248 -- Compile Haskell, boot and extCore in --make mode.
249 hscCompileMake :: Compiler (HscStatus, ModIface, ModDetails)
250 hscCompileMake hsc_env mod_summary
251 = compiler hsc_env mod_summary
252 where mkComp = hscMkCompiler norecompMake
253 backend = case hscTarget (hsc_dflags hsc_env) of
254 HscNothing -> hscCodeGenNothing
255 _other -> hscCodeGenMake
257 = case ms_hsc_src mod_summary of
259 -> mkComp hscCoreFrontEnd hscNewBackEnd backend
261 -> mkComp hscFileFrontEnd hscNewBackEnd backend
263 -> mkComp hscFileFrontEnd hscNewBootBackEnd hscCodeGenIdentity
266 -- Compile Haskell, extCore to bytecode.
267 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
268 hscCompileInteractive hsc_env mod_summary =
269 hscMkCompiler norecompInteractive frontend hscNewBackEnd hscCodeGenInteractive
271 where frontend = case ms_hsc_src mod_summary of
272 ExtCoreFile -> hscCoreFrontEnd
273 HsSrcFile -> hscFileFrontEnd
274 HsBootFile -> panic bootErrorMsg
275 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
276 "Use 'hscCompileMake' instead."
278 --------------------------------------------------------------
280 --------------------------------------------------------------
282 norecompOneShot :: a -> NoRecomp a
283 norecompOneShot a hsc_env mod_summary
284 have_object old_iface
286 = do compilationProgressMsg (hsc_dflags hsc_env) $
287 "compilation IS NOT required"
288 dumpIfaceStats hsc_env
291 norecompMake :: NoRecomp (HscStatus, ModIface, ModDetails)
292 norecompMake = norecompWorker HscNoRecomp
294 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
295 norecompInteractive = norecompWorker InteractiveNoRecomp
297 norecompWorker :: a -> NoRecomp (a, ModIface, ModDetails)
298 norecompWorker a hsc_env mod_summary have_object
299 old_iface mb_mod_index
300 = do compilationProgressMsg (hsc_dflags hsc_env) $
301 (showModuleIndex mb_mod_index ++
302 "Skipping " ++ showModMsg have_object mod_summary)
303 new_details <- {-# SCC "tcRnIface" #-}
304 initIfaceCheck hsc_env $
305 typecheckIface old_iface
306 dumpIfaceStats hsc_env
307 return (a, old_iface, new_details)
309 --------------------------------------------------------------
311 --------------------------------------------------------------
313 hscCoreFrontEnd :: FrontEnd ModGuts
314 hscCoreFrontEnd hsc_env mod_summary mb_mod_index = do {
318 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
319 ; case parseCore inp 1 of
320 FailP s -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
322 OkP rdr_module -> do {
325 -- RENAME and TYPECHECK
327 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
328 tcRnExtCore hsc_env rdr_module
329 ; printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
330 ; case maybe_tc_result of
331 Nothing -> return Nothing
332 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
335 hscFileFrontEnd :: FrontEnd ModGuts
336 hscFileFrontEnd hsc_env mod_summary mb_mod_index = do {
338 -- DISPLAY PROGRESS MESSAGE
340 ; let dflags = hsc_dflags hsc_env
341 one_shot = isOneShot (ghcMode dflags)
342 toInterp = hscTarget dflags == HscInterpreted
343 ; when (not one_shot) $
344 compilationProgressMsg dflags $
345 (showModuleIndex mb_mod_index ++
346 "Compiling " ++ showModMsg (not toInterp) mod_summary)
351 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
352 hspp_buf = ms_hspp_buf mod_summary
354 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
356 ; case maybe_parsed of {
357 Left err -> do { printBagOfErrors dflags (unitBag err)
359 Right rdr_module -> do {
362 -- RENAME and TYPECHECK
364 (tc_msgs, maybe_tc_result)
365 <- {-# SCC "Typecheck-Rename" #-}
366 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
368 ; printErrorsAndWarnings dflags tc_msgs
369 ; case maybe_tc_result of {
370 Nothing -> return Nothing ;
371 Just tc_result -> do {
376 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
377 deSugar hsc_env tc_result
378 ; printBagOfWarnings dflags warns
379 ; return maybe_ds_result
382 --------------------------------------------------------------
384 --------------------------------------------------------------
386 hscNewBootBackEnd :: BackEnd ModGuts (HscStatus, ModIface, ModDetails)
387 hscNewBootBackEnd hsc_env mod_summary maybe_old_iface ds_result
388 = do details <- mkBootModDetails hsc_env ds_result
389 (new_iface, no_change)
390 <- {-# SCC "MkFinalIface" #-}
391 mkIface hsc_env maybe_old_iface ds_result details
392 writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
393 -- And the answer is ...
394 dumpIfaceStats hsc_env
395 return (HscRecomp False, new_iface, details)
397 hscNewBackEnd :: BackEnd ModGuts (ModIface, ModDetails, CgGuts)
398 hscNewBackEnd hsc_env mod_summary maybe_old_iface ds_result
400 -- ; seqList imported_modules (return ())
402 let dflags = hsc_dflags hsc_env
407 ; flat_result <- {-# SCC "Flattening" #-}
408 flatten hsc_env ds_result
411 {- TEMP: need to review space-leak fixing here
412 NB: even the code generator can force one of the
413 thunks for constructor arguments, for newtypes in particular
415 ; let -- Rule-base accumulated from imported packages
416 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
418 -- In one-shot mode, ZAP the external package state at
419 -- this point, because we aren't going to need it from
420 -- now on. We keep the name cache, however, because
421 -- tidyCore needs it.
423 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
426 ; pkg_rule_base `seq` pcs_middle `seq` return ()
429 -- alive at this point:
437 ; simpl_result <- {-# SCC "Core2Core" #-}
438 core2core hsc_env flat_result
443 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
444 tidyProgram hsc_env simpl_result
446 -- Alive at this point:
447 -- tidy_result, pcs_final
451 -- BUILD THE NEW ModIface and ModDetails
452 -- and emit external core if necessary
453 -- This has to happen *after* code gen so that the back-end
454 -- info has been set. Not yet clear if it matters waiting
455 -- until after code output
456 ; (new_iface, no_change)
457 <- {-# SCC "MkFinalIface" #-}
458 mkIface hsc_env maybe_old_iface simpl_result details
460 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
462 -- Emit external core
463 ; emitExternalCore dflags cg_guts
466 -- Return the prepared code.
467 ; return (new_iface, details, cg_guts)
470 --------------------------------------------------------------
472 --------------------------------------------------------------
474 -- Don't output any code.
475 hscCodeGenNothing :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
476 hscCodeGenNothing hsc_env mod_summary (iface, details, cgguts)
477 = return (HscRecomp False, iface, details)
479 -- Generate code and return both the new ModIface and the ModDetails.
480 hscCodeGenMake :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
481 hscCodeGenMake hsc_env mod_summary (iface, details, cgguts)
482 = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
483 return (HscRecomp hasStub, iface, details)
485 -- Here we don't need the ModIface and ModDetails anymore.
486 hscCodeGenOneShot :: CodeGen (ModIface, ModDetails, CgGuts) HscStatus
487 hscCodeGenOneShot hsc_env mod_summary (_, _, cgguts)
488 = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
489 return (HscRecomp hasStub)
491 hscCodeGenCompile :: CodeGen CgGuts Bool
492 hscCodeGenCompile hsc_env mod_summary cgguts
493 = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
494 -- From now on, we just use the bits we need.
495 cg_module = this_mod,
496 cg_binds = core_binds,
498 cg_dir_imps = dir_imps,
499 cg_foreign = foreign_stubs,
500 cg_home_mods = home_mods,
501 cg_dep_pkgs = dependencies } = cgguts
502 dflags = hsc_dflags hsc_env
503 location = ms_location mod_summary
504 data_tycons = filter isDataTyCon tycons
505 -- cg_tycons includes newtypes, for the benefit of External Core,
506 -- but we don't generate any code for newtypes
509 -- PREPARE FOR CODE GENERATION
510 -- Do saturation and convert to A-normal form
511 prepd_binds <- {-# SCC "CorePrep" #-}
512 corePrepPgm dflags core_binds data_tycons ;
513 ----------------- Convert to STG ------------------
514 (stg_binds, cost_centre_info)
515 <- {-# SCC "CoreToStg" #-}
516 myCoreToStg dflags home_mods this_mod prepd_binds
517 ------------------ Code generation ------------------
518 abstractC <- {-# SCC "CodeGen" #-}
519 codeGen dflags home_mods this_mod data_tycons
520 foreign_stubs dir_imps cost_centre_info
522 ------------------ Code output -----------------------
523 (stub_h_exists,stub_c_exists)
524 <- codeOutput dflags this_mod location foreign_stubs
525 dependencies abstractC
528 hscCodeGenIdentity :: CodeGen a a
529 hscCodeGenIdentity hsc_env mod_summary a = return a
531 hscCodeGenConst :: b -> CodeGen a b
532 hscCodeGenConst b hsc_env mod_summary a = return b
534 hscCodeGenInteractive :: CodeGen (ModIface, ModDetails, CgGuts)
535 (InteractiveStatus, ModIface, ModDetails)
536 hscCodeGenInteractive hsc_env mod_summary (iface, details, cgguts)
538 = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
539 -- From now on, we just use the bits we need.
540 cg_module = this_mod,
541 cg_binds = core_binds,
543 cg_foreign = foreign_stubs,
544 cg_home_mods = home_mods,
545 cg_dep_pkgs = dependencies } = cgguts
546 dflags = hsc_dflags hsc_env
547 location = ms_location mod_summary
548 data_tycons = filter isDataTyCon tycons
549 -- cg_tycons includes newtypes, for the benefit of External Core,
550 -- but we don't generate any code for newtypes
553 -- PREPARE FOR CODE GENERATION
554 -- Do saturation and convert to A-normal form
555 prepd_binds <- {-# SCC "CorePrep" #-}
556 corePrepPgm dflags core_binds data_tycons ;
557 ----------------- Generate byte code ------------------
558 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
559 ------------------ Create f-x-dynamic C-side stuff ---
560 (istub_h_exists, istub_c_exists)
561 <- outputForeignStubs dflags this_mod location foreign_stubs
562 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
564 = panic "GHC not compiled with interpreter"
568 ------------------------------
570 hscFileCheck :: HscEnv -> ModSummary -> IO (Maybe HscChecked)
571 hscFileCheck hsc_env mod_summary = do {
575 ; let dflags = hsc_dflags hsc_env
576 hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
577 hspp_buf = ms_hspp_buf mod_summary
579 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
581 ; case maybe_parsed of {
582 Left err -> do { printBagOfErrors dflags (unitBag err)
584 Right rdr_module -> do {
587 -- RENAME and TYPECHECK
589 (tc_msgs, maybe_tc_result)
590 <- _scc_ "Typecheck-Rename"
591 tcRnModule hsc_env (ms_hsc_src mod_summary)
592 True{-save renamed syntax-}
595 ; printErrorsAndWarnings dflags tc_msgs
596 ; case maybe_tc_result of {
597 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing));
599 let md = ModDetails {
600 md_types = tcg_type_env tc_result,
601 md_exports = tcg_exports tc_result,
602 md_insts = tcg_insts tc_result,
603 md_rules = [panic "no rules"] }
604 -- Rules are CoreRules, not the
605 -- RuleDecls we get out of the typechecker
606 rnInfo = do decl <- tcg_rn_decls tc_result
607 imports <- tcg_rn_imports tc_result
608 let exports = tcg_rn_exports tc_result
609 return (decl,imports,exports)
610 return (Just (HscChecked rdr_module
612 (Just (tcg_binds tc_result,
613 tcg_rdr_env tc_result,
618 hscCmmFile :: DynFlags -> FilePath -> IO Bool
619 hscCmmFile dflags filename = do
620 maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
622 Nothing -> return False
624 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
627 no_mod = panic "hscCmmFile: no_mod"
628 no_loc = ModLocation{ ml_hs_file = Just filename,
629 ml_hi_file = panic "hscCmmFile: no hi file",
630 ml_obj_file = panic "hscCmmFile: no obj file" }
633 myParseModule dflags src_filename maybe_src_buf
634 = -------------------------- Parser ----------------
635 showPass dflags "Parser" >>
636 {-# SCC "Parser" #-} do
638 -- sometimes we already have the buffer in memory, perhaps
639 -- because we needed to parse the imports out of it, or get the
641 buf <- case maybe_src_buf of
643 Nothing -> hGetStringBuffer src_filename
645 let loc = mkSrcLoc (mkFastString src_filename) 1 0
647 case unP parseModule (mkPState buf loc dflags) of {
649 PFailed span err -> return (Left (mkPlainErrMsg span err));
651 POk _ rdr_module -> do {
653 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
655 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
656 (ppSourceStats False rdr_module) ;
658 return (Right rdr_module)
659 -- ToDo: free the string buffer later.
663 myCoreToStg dflags home_mods this_mod prepd_binds
665 stg_binds <- {-# SCC "Core2Stg" #-}
666 coreToStg home_mods prepd_binds
668 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
669 stg2stg dflags home_mods this_mod stg_binds
671 return (stg_binds2, cost_centre_info)
675 %************************************************************************
677 \subsection{Compiling a do-statement}
679 %************************************************************************
681 When the UnlinkedBCOExpr is linked you get an HValue of type
683 When you run it you get a list of HValues that should be
684 the same length as the list of names; add them to the ClosureEnv.
686 A naked expression returns a singleton Name [it].
688 What you type The IO [HValue] that hscStmt returns
689 ------------- ------------------------------------
690 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
693 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
696 expr (of IO type) ==> expr >>= \ v -> return [v]
697 [NB: result not printed] bindings: [it]
700 expr (of non-IO type,
701 result showable) ==> let v = expr in print v >> return [v]
704 expr (of non-IO type,
705 result not showable) ==> error
709 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
711 -> String -- The statement
712 -> IO (Maybe (HscEnv, [Name], HValue))
715 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
716 ; case maybe_stmt of {
717 Nothing -> return Nothing ; -- Parse error
718 Just Nothing -> return Nothing ; -- Empty line
719 Just (Just parsed_stmt) -> do { -- The real stuff
721 -- Rename and typecheck it
722 let icontext = hsc_IC hsc_env
723 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
725 ; case maybe_tc_result of {
726 Nothing -> return Nothing ;
727 Just (new_ic, bound_names, tc_expr) -> do {
729 -- Then desugar, code gen, and link it
730 ; hval <- compileExpr hsc_env iNTERACTIVE
731 (ic_rn_gbl_env new_ic)
735 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
738 hscTcExpr -- Typecheck an expression (but don't run it)
740 -> String -- The expression
743 hscTcExpr hsc_env expr
744 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
745 ; let icontext = hsc_IC hsc_env
746 ; case maybe_stmt of {
747 Nothing -> return Nothing ; -- Parse error
748 Just (Just (L _ (ExprStmt expr _ _)))
749 -> tcRnExpr hsc_env icontext expr ;
750 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
754 hscKcType -- Find the kind of a type
756 -> String -- The type
759 hscKcType hsc_env str
760 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
761 ; let icontext = hsc_IC hsc_env
762 ; case maybe_type of {
763 Just ty -> tcRnType hsc_env icontext ty ;
764 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
766 Nothing -> return Nothing } }
772 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
773 hscParseStmt = hscParseThing parseStmt
775 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
776 hscParseType = hscParseThing parseType
779 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
780 hscParseIdentifier = hscParseThing parseIdentifier
782 hscParseThing :: Outputable thing
784 -> DynFlags -> String
786 -- Nothing => Parse error (message already printed)
788 hscParseThing parser dflags str
789 = showPass dflags "Parser" >>
790 {-# SCC "Parser" #-} do
792 buf <- stringToStringBuffer str
794 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
796 case unP parser (mkPState buf loc dflags) of {
798 PFailed span err -> do { printError span err;
803 --ToDo: can't free the string buffer until we've finished this
804 -- compilation sweep and all the identifiers have gone away.
805 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
810 %************************************************************************
812 Desugar, simplify, convert to bytecode, and link an expression
814 %************************************************************************
818 compileExpr :: HscEnv
819 -> Module -> GlobalRdrEnv -> TypeEnv
823 compileExpr hsc_env this_mod rdr_env type_env tc_expr
824 = do { let { dflags = hsc_dflags hsc_env ;
825 lint_on = dopt Opt_DoCoreLinting dflags }
828 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
831 ; flat_expr <- flattenExpr hsc_env ds_expr
834 ; simpl_expr <- simplifyExpr dflags flat_expr
836 -- Tidy it (temporary, until coreSat does cloning)
837 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
839 -- Prepare for codegen
840 ; prepd_expr <- corePrepExpr dflags tidy_expr
843 -- ToDo: improve SrcLoc
845 case lintUnfolding noSrcLoc [] prepd_expr of
846 Just err -> pprPanic "compileExpr" err
852 ; bcos <- coreExprToBCOs dflags prepd_expr
855 ; hval <- linkExpr hsc_env bcos
863 %************************************************************************
865 Statistics on reading interfaces
867 %************************************************************************
870 dumpIfaceStats :: HscEnv -> IO ()
871 dumpIfaceStats hsc_env
872 = do { eps <- readIORef (hsc_EPS hsc_env)
873 ; dumpIfSet (dump_if_trace || dump_rn_stats)
874 "Interface statistics"
877 dflags = hsc_dflags hsc_env
878 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
879 dump_if_trace = dopt Opt_D_dump_if_trace dflags
882 %************************************************************************
884 Progress Messages: Module i of n
886 %************************************************************************
889 showModuleIndex Nothing = ""
890 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
894 padded = replicate (length n_str - length i_str) ' ' ++ i_str