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 -> 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 -- FIXME: The old interface and module index are only using in 'make' and
190 -- 'interactive' mode. They should be removed from 'oneshot' mode.
191 type Compiler result = HscEnv
193 -> Bool -- True <=> source unchanged
194 -> Maybe ModIface -- Old interface, if available
195 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
199 -- This functions checks if recompilation is necessary and
200 -- then combines the FrontEnd, BackEnd and CodeGen to a
202 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
204 -> BackEnd core prepCore
205 -> CodeGen prepCore result
207 hscMkCompiler norecomp frontend backend codegen
208 hsc_env mod_summary source_unchanged
209 mbOldIface mbModIndex
210 = do (recomp_reqd, mbCheckedIface)
211 <- {-# SCC "checkOldIface" #-}
212 checkOldIface hsc_env mod_summary
213 source_unchanged mbOldIface
214 case mbCheckedIface of
215 Just iface | not recomp_reqd
216 -> do result <- norecomp hsc_env mod_summary iface mbModIndex
219 -> do mbCore <- frontend hsc_env mod_summary mbModIndex
224 -> do prepCore <- backend hsc_env mod_summary
226 result <- codegen hsc_env mod_summary prepCore
229 --------------------------------------------------------------
231 --------------------------------------------------------------
233 -- Compile Haskell, boot and extCore in OneShot mode.
234 hscCompileOneShot :: Compiler HscStatus
235 hscCompileOneShot hsc_env mod_summary =
236 compiler hsc_env mod_summary
237 where mkComp = hscMkCompiler (norecompOneShot HscNoRecomp)
239 = case ms_hsc_src mod_summary of
241 -> mkComp hscCoreFrontEnd hscNewBackEnd hscCodeGenOneShot
244 -> mkComp hscFileFrontEnd hscNewBackEnd hscCodeGenOneShot
246 -> mkComp hscFileFrontEnd hscNewBootBackEnd
247 (hscCodeGenConst (HscRecomp False))
249 -- Compile Haskell, boot and extCore in --make mode.
250 hscCompileMake :: Compiler (HscStatus, ModIface, ModDetails)
251 hscCompileMake hsc_env mod_summary
252 = compiler hsc_env mod_summary
253 where mkComp = hscMkCompiler norecompMake
254 backend = case hscTarget (hsc_dflags hsc_env) of
255 HscNothing -> hscCodeGenNothing
256 _other -> hscCodeGenMake
258 = case ms_hsc_src mod_summary of
260 -> mkComp hscCoreFrontEnd hscNewBackEnd backend
262 -> mkComp hscFileFrontEnd hscNewBackEnd backend
264 -> mkComp hscFileFrontEnd hscNewBootBackEnd hscCodeGenIdentity
267 -- Compile Haskell, extCore to bytecode.
268 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
269 hscCompileInteractive hsc_env mod_summary =
270 hscMkCompiler norecompInteractive frontend hscNewBackEnd hscCodeGenInteractive
272 where frontend = case ms_hsc_src mod_summary of
273 ExtCoreFile -> hscCoreFrontEnd
274 HsSrcFile -> hscFileFrontEnd
275 HsBootFile -> panic bootErrorMsg
276 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
277 "Use 'hscCompileMake' instead."
279 --------------------------------------------------------------
281 --------------------------------------------------------------
283 norecompOneShot :: a -> NoRecomp a
284 norecompOneShot a hsc_env mod_summary
287 = do compilationProgressMsg (hsc_dflags hsc_env) $
288 "compilation IS NOT required"
289 dumpIfaceStats hsc_env
292 norecompMake :: NoRecomp (HscStatus, ModIface, ModDetails)
293 norecompMake = norecompWorker HscNoRecomp False
295 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
296 norecompInteractive = norecompWorker InteractiveNoRecomp True
298 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
299 norecompWorker a isInterp hsc_env mod_summary
300 old_iface mb_mod_index
301 = do compilationProgressMsg (hsc_dflags hsc_env) $
302 (showModuleIndex mb_mod_index ++
303 "Skipping " ++ showModMsg isInterp mod_summary)
304 new_details <- {-# SCC "tcRnIface" #-}
305 initIfaceCheck hsc_env $
306 typecheckIface old_iface
307 dumpIfaceStats hsc_env
308 return (a, old_iface, new_details)
310 --------------------------------------------------------------
312 --------------------------------------------------------------
314 hscCoreFrontEnd :: FrontEnd ModGuts
315 hscCoreFrontEnd hsc_env mod_summary mb_mod_index = do {
319 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
320 ; case parseCore inp 1 of
321 FailP s -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
323 OkP rdr_module -> do {
326 -- RENAME and TYPECHECK
328 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
329 tcRnExtCore hsc_env rdr_module
330 ; printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
331 ; case maybe_tc_result of
332 Nothing -> return Nothing
333 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
337 hscFileFrontEnd :: FrontEnd ModGuts
338 hscFileFrontEnd hsc_env mod_summary mb_mod_index = do {
339 -- FIXME: Move 'DISPLAY PROGRESS MESSAGE' out of the frontend.
341 -- DISPLAY PROGRESS MESSAGE
343 ; let dflags = hsc_dflags hsc_env
344 one_shot = isOneShot (ghcMode dflags)
345 toInterp = hscTarget dflags == HscInterpreted
346 ; when (not one_shot) $
347 compilationProgressMsg dflags $
348 (showModuleIndex mb_mod_index ++
349 "Compiling " ++ showModMsg (not toInterp) mod_summary)
354 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
355 hspp_buf = ms_hspp_buf mod_summary
357 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
359 ; case maybe_parsed of {
360 Left err -> do { printBagOfErrors dflags (unitBag err)
362 Right rdr_module -> do {
365 -- RENAME and TYPECHECK
367 (tc_msgs, maybe_tc_result)
368 <- {-# SCC "Typecheck-Rename" #-}
369 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
371 ; printErrorsAndWarnings dflags tc_msgs
372 ; case maybe_tc_result of {
373 Nothing -> return Nothing ;
374 Just tc_result -> do {
379 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
380 deSugar hsc_env tc_result
381 ; printBagOfWarnings dflags warns
382 ; return maybe_ds_result
385 --------------------------------------------------------------
387 --------------------------------------------------------------
389 -- FIXME: Rename backend to simplifier, and codegen to backend.
391 hscNewBootBackEnd :: BackEnd ModGuts (HscStatus, ModIface, ModDetails)
392 hscNewBootBackEnd hsc_env mod_summary maybe_old_iface ds_result
393 = do details <- mkBootModDetails hsc_env ds_result
394 (new_iface, no_change)
395 <- {-# SCC "MkFinalIface" #-}
396 mkIface hsc_env maybe_old_iface ds_result details
397 writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
398 -- And the answer is ...
399 dumpIfaceStats hsc_env
400 return (HscRecomp False, new_iface, details)
402 hscNewBackEnd :: BackEnd ModGuts (ModIface, ModDetails, CgGuts)
403 hscNewBackEnd hsc_env mod_summary maybe_old_iface ds_result
405 -- ; seqList imported_modules (return ())
407 let dflags = hsc_dflags hsc_env
412 ; flat_result <- {-# SCC "Flattening" #-}
413 flatten hsc_env ds_result
416 {- TEMP: need to review space-leak fixing here
417 NB: even the code generator can force one of the
418 thunks for constructor arguments, for newtypes in particular
420 ; let -- Rule-base accumulated from imported packages
421 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
423 -- In one-shot mode, ZAP the external package state at
424 -- this point, because we aren't going to need it from
425 -- now on. We keep the name cache, however, because
426 -- tidyCore needs it.
428 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
431 ; pkg_rule_base `seq` pcs_middle `seq` return ()
434 -- alive at this point:
442 ; simpl_result <- {-# SCC "Core2Core" #-}
443 core2core hsc_env flat_result
448 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
449 tidyProgram hsc_env simpl_result
451 -- Alive at this point:
452 -- tidy_result, pcs_final
456 -- BUILD THE NEW ModIface and ModDetails
457 -- and emit external core if necessary
458 -- This has to happen *after* code gen so that the back-end
459 -- info has been set. Not yet clear if it matters waiting
460 -- until after code output
461 ; (new_iface, no_change)
462 <- {-# SCC "MkFinalIface" #-}
463 mkIface hsc_env maybe_old_iface simpl_result details
465 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
467 -- Emit external core
468 ; emitExternalCore dflags cg_guts
471 -- Return the prepared code.
472 ; return (new_iface, details, cg_guts)
475 --------------------------------------------------------------
477 --------------------------------------------------------------
479 -- Don't output any code.
480 hscCodeGenNothing :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
481 hscCodeGenNothing hsc_env mod_summary (iface, details, cgguts)
482 = return (HscRecomp False, iface, details)
484 -- Generate code and return both the new ModIface and the ModDetails.
485 hscCodeGenMake :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
486 hscCodeGenMake hsc_env mod_summary (iface, details, cgguts)
487 = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
488 return (HscRecomp hasStub, iface, details)
490 -- Here we don't need the ModIface and ModDetails anymore.
491 hscCodeGenOneShot :: CodeGen (ModIface, ModDetails, CgGuts) HscStatus
492 hscCodeGenOneShot hsc_env mod_summary (_, _, cgguts)
493 = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
494 return (HscRecomp hasStub)
496 hscCodeGenCompile :: CodeGen CgGuts Bool
497 hscCodeGenCompile hsc_env mod_summary cgguts
498 = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
499 -- From now on, we just use the bits we need.
500 cg_module = this_mod,
501 cg_binds = core_binds,
503 cg_dir_imps = dir_imps,
504 cg_foreign = foreign_stubs,
505 cg_home_mods = home_mods,
506 cg_dep_pkgs = dependencies } = cgguts
507 dflags = hsc_dflags hsc_env
508 location = ms_location mod_summary
509 data_tycons = filter isDataTyCon tycons
510 -- cg_tycons includes newtypes, for the benefit of External Core,
511 -- but we don't generate any code for newtypes
514 -- PREPARE FOR CODE GENERATION
515 -- Do saturation and convert to A-normal form
516 prepd_binds <- {-# SCC "CorePrep" #-}
517 corePrepPgm dflags core_binds data_tycons ;
518 ----------------- Convert to STG ------------------
519 (stg_binds, cost_centre_info)
520 <- {-# SCC "CoreToStg" #-}
521 myCoreToStg dflags home_mods this_mod prepd_binds
522 ------------------ Code generation ------------------
523 abstractC <- {-# SCC "CodeGen" #-}
524 codeGen dflags home_mods this_mod data_tycons
525 foreign_stubs dir_imps cost_centre_info
527 ------------------ Code output -----------------------
528 (stub_h_exists,stub_c_exists)
529 <- codeOutput dflags this_mod location foreign_stubs
530 dependencies abstractC
533 hscCodeGenIdentity :: CodeGen a a
534 hscCodeGenIdentity hsc_env mod_summary a = return a
536 hscCodeGenConst :: b -> CodeGen a b
537 hscCodeGenConst b hsc_env mod_summary a = return b
539 hscCodeGenInteractive :: CodeGen (ModIface, ModDetails, CgGuts)
540 (InteractiveStatus, ModIface, ModDetails)
541 hscCodeGenInteractive hsc_env mod_summary (iface, details, cgguts)
543 = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
544 -- From now on, we just use the bits we need.
545 cg_module = this_mod,
546 cg_binds = core_binds,
548 cg_foreign = foreign_stubs,
549 cg_home_mods = home_mods,
550 cg_dep_pkgs = dependencies } = cgguts
551 dflags = hsc_dflags hsc_env
552 location = ms_location mod_summary
553 data_tycons = filter isDataTyCon tycons
554 -- cg_tycons includes newtypes, for the benefit of External Core,
555 -- but we don't generate any code for newtypes
558 -- PREPARE FOR CODE GENERATION
559 -- Do saturation and convert to A-normal form
560 prepd_binds <- {-# SCC "CorePrep" #-}
561 corePrepPgm dflags core_binds data_tycons ;
562 ----------------- Generate byte code ------------------
563 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
564 ------------------ Create f-x-dynamic C-side stuff ---
565 (istub_h_exists, istub_c_exists)
566 <- outputForeignStubs dflags this_mod location foreign_stubs
567 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
569 = panic "GHC not compiled with interpreter"
573 ------------------------------
575 hscFileCheck :: HscEnv -> ModSummary -> IO (Maybe HscChecked)
576 hscFileCheck hsc_env mod_summary = do {
580 ; let dflags = hsc_dflags hsc_env
581 hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
582 hspp_buf = ms_hspp_buf mod_summary
584 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
586 ; case maybe_parsed of {
587 Left err -> do { printBagOfErrors dflags (unitBag err)
589 Right rdr_module -> do {
592 -- RENAME and TYPECHECK
594 (tc_msgs, maybe_tc_result)
595 <- _scc_ "Typecheck-Rename"
596 tcRnModule hsc_env (ms_hsc_src mod_summary)
597 True{-save renamed syntax-}
600 ; printErrorsAndWarnings dflags tc_msgs
601 ; case maybe_tc_result of {
602 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing));
604 let md = ModDetails {
605 md_types = tcg_type_env tc_result,
606 md_exports = tcg_exports tc_result,
607 md_insts = tcg_insts tc_result,
608 md_rules = [panic "no rules"] }
609 -- Rules are CoreRules, not the
610 -- RuleDecls we get out of the typechecker
611 rnInfo = do decl <- tcg_rn_decls tc_result
612 imports <- tcg_rn_imports tc_result
613 let exports = tcg_rn_exports tc_result
614 return (decl,imports,exports)
615 return (Just (HscChecked rdr_module
617 (Just (tcg_binds tc_result,
618 tcg_rdr_env tc_result,
623 hscCmmFile :: DynFlags -> FilePath -> IO Bool
624 hscCmmFile dflags filename = do
625 maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
627 Nothing -> return False
629 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
632 no_mod = panic "hscCmmFile: no_mod"
633 no_loc = ModLocation{ ml_hs_file = Just filename,
634 ml_hi_file = panic "hscCmmFile: no hi file",
635 ml_obj_file = panic "hscCmmFile: no obj file" }
638 myParseModule dflags src_filename maybe_src_buf
639 = -------------------------- Parser ----------------
640 showPass dflags "Parser" >>
641 {-# SCC "Parser" #-} do
643 -- sometimes we already have the buffer in memory, perhaps
644 -- because we needed to parse the imports out of it, or get the
646 buf <- case maybe_src_buf of
648 Nothing -> hGetStringBuffer src_filename
650 let loc = mkSrcLoc (mkFastString src_filename) 1 0
652 case unP parseModule (mkPState buf loc dflags) of {
654 PFailed span err -> return (Left (mkPlainErrMsg span err));
656 POk _ rdr_module -> do {
658 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
660 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
661 (ppSourceStats False rdr_module) ;
663 return (Right rdr_module)
664 -- ToDo: free the string buffer later.
668 myCoreToStg dflags home_mods this_mod prepd_binds
670 stg_binds <- {-# SCC "Core2Stg" #-}
671 coreToStg home_mods prepd_binds
673 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
674 stg2stg dflags home_mods this_mod stg_binds
676 return (stg_binds2, cost_centre_info)
680 %************************************************************************
682 \subsection{Compiling a do-statement}
684 %************************************************************************
686 When the UnlinkedBCOExpr is linked you get an HValue of type
688 When you run it you get a list of HValues that should be
689 the same length as the list of names; add them to the ClosureEnv.
691 A naked expression returns a singleton Name [it].
693 What you type The IO [HValue] that hscStmt returns
694 ------------- ------------------------------------
695 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
698 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
701 expr (of IO type) ==> expr >>= \ v -> return [v]
702 [NB: result not printed] bindings: [it]
705 expr (of non-IO type,
706 result showable) ==> let v = expr in print v >> return [v]
709 expr (of non-IO type,
710 result not showable) ==> error
714 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
716 -> String -- The statement
717 -> IO (Maybe (HscEnv, [Name], HValue))
720 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
721 ; case maybe_stmt of {
722 Nothing -> return Nothing ; -- Parse error
723 Just Nothing -> return Nothing ; -- Empty line
724 Just (Just parsed_stmt) -> do { -- The real stuff
726 -- Rename and typecheck it
727 let icontext = hsc_IC hsc_env
728 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
730 ; case maybe_tc_result of {
731 Nothing -> return Nothing ;
732 Just (new_ic, bound_names, tc_expr) -> do {
734 -- Then desugar, code gen, and link it
735 ; hval <- compileExpr hsc_env iNTERACTIVE
736 (ic_rn_gbl_env new_ic)
740 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
743 hscTcExpr -- Typecheck an expression (but don't run it)
745 -> String -- The expression
748 hscTcExpr hsc_env expr
749 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
750 ; let icontext = hsc_IC hsc_env
751 ; case maybe_stmt of {
752 Nothing -> return Nothing ; -- Parse error
753 Just (Just (L _ (ExprStmt expr _ _)))
754 -> tcRnExpr hsc_env icontext expr ;
755 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
759 hscKcType -- Find the kind of a type
761 -> String -- The type
764 hscKcType hsc_env str
765 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
766 ; let icontext = hsc_IC hsc_env
767 ; case maybe_type of {
768 Just ty -> tcRnType hsc_env icontext ty ;
769 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
771 Nothing -> return Nothing } }
777 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
778 hscParseStmt = hscParseThing parseStmt
780 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
781 hscParseType = hscParseThing parseType
784 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
785 hscParseIdentifier = hscParseThing parseIdentifier
787 hscParseThing :: Outputable thing
789 -> DynFlags -> String
791 -- Nothing => Parse error (message already printed)
793 hscParseThing parser dflags str
794 = showPass dflags "Parser" >>
795 {-# SCC "Parser" #-} do
797 buf <- stringToStringBuffer str
799 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
801 case unP parser (mkPState buf loc dflags) of {
803 PFailed span err -> do { printError span err;
808 --ToDo: can't free the string buffer until we've finished this
809 -- compilation sweep and all the identifiers have gone away.
810 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
815 %************************************************************************
817 Desugar, simplify, convert to bytecode, and link an expression
819 %************************************************************************
823 compileExpr :: HscEnv
824 -> Module -> GlobalRdrEnv -> TypeEnv
828 compileExpr hsc_env this_mod rdr_env type_env tc_expr
829 = do { let { dflags = hsc_dflags hsc_env ;
830 lint_on = dopt Opt_DoCoreLinting dflags }
833 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
836 ; flat_expr <- flattenExpr hsc_env ds_expr
839 ; simpl_expr <- simplifyExpr dflags flat_expr
841 -- Tidy it (temporary, until coreSat does cloning)
842 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
844 -- Prepare for codegen
845 ; prepd_expr <- corePrepExpr dflags tidy_expr
848 -- ToDo: improve SrcLoc
850 case lintUnfolding noSrcLoc [] prepd_expr of
851 Just err -> pprPanic "compileExpr" err
857 ; bcos <- coreExprToBCOs dflags prepd_expr
860 ; hval <- linkExpr hsc_env bcos
868 %************************************************************************
870 Statistics on reading interfaces
872 %************************************************************************
875 dumpIfaceStats :: HscEnv -> IO ()
876 dumpIfaceStats hsc_env
877 = do { eps <- readIORef (hsc_EPS hsc_env)
878 ; dumpIfSet (dump_if_trace || dump_rn_stats)
879 "Interface statistics"
882 dflags = hsc_dflags hsc_env
883 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
884 dump_if_trace = dopt Opt_D_dump_if_trace dflags
887 %************************************************************************
889 Progress Messages: Module i of n
891 %************************************************************************
894 showModuleIndex Nothing = ""
895 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
899 padded = replicate (length n_str - length i_str) ' ' ++ i_str