2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
10 hscMain, newHscEnv, hscCmmFile,
14 hscStmt, hscTcExpr, hscKcType,
19 #include "HsVersions.h"
22 import HsSyn ( Stmt(..), LHsExpr, LStmt, LHsType )
23 import Module ( Module )
24 import CodeOutput ( outputForeignStubs )
25 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
26 import Linker ( HValue, linkExpr )
27 import CoreTidy ( tidyExpr )
28 import CorePrep ( corePrepExpr )
29 import Flattening ( flattenExpr )
30 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
32 import PrelNames ( iNTERACTIVE )
34 import CoreLint ( lintUnfolding )
35 import DsMeta ( templateHaskellNames )
36 import SrcLoc ( noSrcLoc )
37 import VarEnv ( emptyTidyEnv )
41 import Module ( emptyModuleEnv, ModLocation(..) )
42 import RdrName ( GlobalRdrEnv, RdrName )
43 import HsSyn ( HsModule, LHsBinds, HsGroup, LIE, LImportDecl )
44 import SrcLoc ( Located(..) )
45 import StringBuffer ( hGetStringBuffer, stringToStringBuffer )
47 import Lexer ( P(..), ParseResult(..), mkPState )
48 import SrcLoc ( mkSrcLoc )
49 import TcRnDriver ( tcRnModule, tcRnExtCore )
50 import TcIface ( typecheckIface )
51 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
52 import IfaceEnv ( initNameCache )
53 import LoadIface ( ifaceStats, initExternalPackageState )
54 import PrelInfo ( wiredInThings, basicKnownKeyNames )
55 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
57 import Flattening ( flatten )
59 import TidyPgm ( tidyProgram, mkBootModDetails )
60 import CorePrep ( corePrepPgm )
61 import CoreToStg ( coreToStg )
62 import TyCon ( isDataTyCon )
63 import Packages ( mkHomeModules )
64 import Name ( Name, NamedThing(..) )
65 import SimplStg ( stg2stg )
66 import CodeGen ( codeGen )
67 import CmmParse ( parseCmmFile )
68 import CodeOutput ( codeOutput )
73 import UniqSupply ( mkSplitUniqSupply )
76 import HscStats ( ppSourceStats )
78 import MkExternalCore ( emitExternalCore )
80 import ParserCoreUtils
82 import Maybes ( expectJust )
83 import Bag ( unitBag )
85 import Maybe ( isJust )
87 import DATA_IOREF ( newIORef, readIORef )
91 %************************************************************************
95 %************************************************************************
98 newHscEnv :: DynFlags -> IO HscEnv
100 = do { eps_var <- newIORef initExternalPackageState
101 ; us <- mkSplitUniqSupply 'r'
102 ; nc_var <- newIORef (initNameCache us knownKeyNames)
103 ; fc_var <- newIORef emptyModuleEnv
104 ; return (HscEnv { hsc_dflags = dflags,
107 hsc_IC = emptyInteractiveContext,
108 hsc_HPT = emptyHomePackageTable,
111 hsc_FC = fc_var } ) }
114 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
115 -- where templateHaskellNames are defined
116 knownKeyNames = map getName wiredInThings
117 ++ basicKnownKeyNames
119 ++ templateHaskellNames
124 %************************************************************************
126 The main compiler pipeline
128 %************************************************************************
130 --------------------------------
131 The compilation proper
132 --------------------------------
135 It's the task of the compilation proper to compile Haskell, hs-boot and
136 core files to either byte-code, hard-code (C, asm, Java, ect) or to
137 nothing at all (the module is still parsed and type-checked. This
138 feature is mostly used by IDE's and the likes).
139 Compilation can happen in either 'one-shot', 'make', or 'interactive'
140 mode. 'One-shot' mode targets hard-code, 'make' mode targets hard-code
141 and nothing, and 'interactive' mode targets byte-code. The modes are
142 kept separate because of their different types.
143 In 'one-shot' mode, we're only compiling a single file and can therefore
144 discard the new ModIface and ModDetails. This is also the reason it only
145 targets hard-code; compiling to byte-code or nothing doesn't make sense
146 when we discard the result. 'Make' mode is like 'one-shot' except that we
147 keep the resulting ModIface and ModDetails. 'Make' mode doesn't target
148 byte-code since that require us to return the newly compiled byte-code.
149 'Interactive' mode is similar to 'make' mode except that we return
150 the compiled byte-code together with the ModIface and ModDetails.
151 Trying to compile a hs-boot file to byte-code will result in a run-time
152 error. This is the only thing that isn't caught by the type-system.
156 -- Compilation failed
159 -- In IDE mode: we just do the static/dynamic checks
162 (Located (HsModule RdrName))
164 (Maybe (HsGroup Name,[LImportDecl Name],Maybe [LIE Name]))
166 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
168 -- Concluded that it wasn't necessary
169 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
170 ModIface -- new iface (if any compilation was done)
173 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
174 ModIface -- new iface (if any compilation was done)
175 Bool -- stub_h exists
176 Bool -- stub_c exists
177 (Maybe CompiledByteCode)
180 -- What to do when we have compiler error or warning messages
181 type MessageAction = Messages -> IO ()
184 --------------------------------------------------------------
185 -- Exterimental code start.
186 --------------------------------------------------------------
190 | NewHscRecomp Bool -- Has stub files.
191 -- This is a hack. We can't compile C files here
192 -- since it's done in DriverPipeline. For now we
193 -- just return True if we want the caller to compile
196 data InteractiveStatus
197 = InteractiveNoRecomp
198 | InteractiveRecomp Bool -- Same as HscStatus
201 type NoRecomp result = HscEnv -> ModSummary -> Bool -> ModIface -> Maybe (Int,Int) -> IO result
202 type FrontEnd core = HscEnv -> ModSummary -> Maybe (Int,Int) -> IO (Maybe core)
203 type BackEnd core prepCore = HscEnv -> ModSummary -> Maybe ModIface -> core -> IO prepCore
204 type CodeGen prepCore result = HscEnv -> ModSummary -> prepCore -> IO result
206 type Compiler result = HscEnv
208 -> Bool -- True <=> source unchanged
209 -> Bool -- True <=> have an object file (for msgs only)
210 -> Maybe ModIface -- Old interface, if available
211 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
215 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
217 -> BackEnd core prepCore
218 -> CodeGen prepCore result
220 hscMkCompiler norecomp frontend backend codegen
221 hsc_env mod_summary source_unchanged
222 have_object mbOldIface mbModIndex
223 = do (recomp_reqd, mbCheckedIface)
224 <- {-# SCC "checkOldIface" #-}
225 checkOldIface hsc_env mod_summary
226 source_unchanged mbOldIface
227 case mbCheckedIface of
228 Just iface | not recomp_reqd
229 -> do result <- norecomp hsc_env mod_summary have_object iface mbModIndex
232 -> do mbCore <- frontend hsc_env mod_summary mbModIndex
237 -> do prepCore <- backend hsc_env mod_summary
239 result <- codegen hsc_env mod_summary prepCore
242 -- Compile Haskell, boot and extCore in OneShot mode.
243 hscCompileOneShot :: Compiler HscStatus
244 hscCompileOneShot hsc_env mod_summary =
245 compiler hsc_env mod_summary
246 where mkComp = hscMkCompiler (norecompOneShot NewHscNoRecomp)
248 = case ms_hsc_src mod_summary of
250 -> mkComp hscCoreFrontEnd hscNewBackEnd hscCodeGenOneShot
253 -> mkComp hscFileFrontEnd hscNewBackEnd hscCodeGenOneShot
255 -> mkComp hscFileFrontEnd hscNewBootBackEnd
256 (hscCodeGenConst (NewHscRecomp False))
258 -- Compile Haskell, boot and extCore in --make mode.
259 hscCompileMake :: Compiler (HscStatus, ModIface, ModDetails)
260 hscCompileMake hsc_env mod_summary
261 = compiler hsc_env mod_summary
262 where mkComp = hscMkCompiler norecompMake
263 backend = case hscTarget (hsc_dflags hsc_env) of
264 HscNothing -> hscCodeGenSimple (\(i, d, g) -> (NewHscRecomp False, i, d))
265 _other -> hscCodeGenMake
267 = case ms_hsc_src mod_summary of
269 -> mkComp hscCoreFrontEnd hscNewBackEnd backend
271 -> mkComp hscFileFrontEnd hscNewBackEnd backend
273 -> mkComp hscFileFrontEnd hscNewBootBackEnd hscCodeGenIdentity
276 -- Compile Haskell, extCore to bytecode.
277 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
278 hscCompileInteractive hsc_env mod_summary =
279 hscMkCompiler norecompInteractive frontend hscNewBackEnd hscCodeGenInteractive
281 where frontend = case ms_hsc_src mod_summary of
282 ExtCoreFile -> hscCoreFrontEnd
283 HsSrcFile -> hscFileFrontEnd
284 HsBootFile -> panic bootErrorMsg
285 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
286 "Use 'hscCompileMake' instead."
288 norecompOneShot :: a -> NoRecomp a
289 norecompOneShot a hsc_env mod_summary
290 have_object old_iface
292 = do compilationProgressMsg (hsc_dflags hsc_env) $
293 "compilation IS NOT required"
294 dumpIfaceStats hsc_env
297 norecompMake :: NoRecomp (HscStatus, ModIface, ModDetails)
298 norecompMake = norecompWorker NewHscNoRecomp
300 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
301 norecompInteractive = norecompWorker InteractiveNoRecomp
303 norecompWorker :: a -> NoRecomp (a, ModIface, ModDetails)
304 norecompWorker a hsc_env mod_summary have_object
305 old_iface mb_mod_index
306 = do compilationProgressMsg (hsc_dflags hsc_env) $
307 (showModuleIndex mb_mod_index ++
308 "Skipping " ++ showModMsg have_object mod_summary)
309 new_details <- {-# SCC "tcRnIface" #-}
310 initIfaceCheck hsc_env $
311 typecheckIface old_iface
312 dumpIfaceStats hsc_env
313 return (a, old_iface, new_details)
315 hscNewBootBackEnd :: BackEnd ModGuts (HscStatus, ModIface, ModDetails)
316 hscNewBootBackEnd hsc_env mod_summary maybe_old_iface ds_result
317 = do details <- mkBootModDetails hsc_env ds_result
318 (new_iface, no_change)
319 <- {-# SCC "MkFinalIface" #-}
320 mkIface hsc_env maybe_old_iface ds_result details
321 writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
322 -- And the answer is ...
323 dumpIfaceStats hsc_env
324 return (NewHscRecomp False, new_iface, details)
326 hscNewBackEnd :: BackEnd ModGuts (ModIface, ModDetails, CgGuts)
327 hscNewBackEnd hsc_env mod_summary maybe_old_iface ds_result
329 -- ; seqList imported_modules (return ())
331 let dflags = hsc_dflags hsc_env
336 ; flat_result <- {-# SCC "Flattening" #-}
337 flatten hsc_env ds_result
340 {- TEMP: need to review space-leak fixing here
341 NB: even the code generator can force one of the
342 thunks for constructor arguments, for newtypes in particular
344 ; let -- Rule-base accumulated from imported packages
345 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
347 -- In one-shot mode, ZAP the external package state at
348 -- this point, because we aren't going to need it from
349 -- now on. We keep the name cache, however, because
350 -- tidyCore needs it.
352 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
355 ; pkg_rule_base `seq` pcs_middle `seq` return ()
358 -- alive at this point:
366 ; simpl_result <- {-# SCC "Core2Core" #-}
367 core2core hsc_env flat_result
372 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
373 tidyProgram hsc_env simpl_result
375 -- Alive at this point:
376 -- tidy_result, pcs_final
380 -- BUILD THE NEW ModIface and ModDetails
381 -- and emit external core if necessary
382 -- This has to happen *after* code gen so that the back-end
383 -- info has been set. Not yet clear if it matters waiting
384 -- until after code output
385 ; (new_iface, no_change)
386 <- {-# SCC "MkFinalIface" #-}
387 mkIface hsc_env maybe_old_iface simpl_result details
389 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
391 -- Emit external core
392 ; emitExternalCore dflags cg_guts
395 -- Return the prepared code.
396 ; return (new_iface, details, cg_guts)
399 -- Don't output any code.
400 hscCodeGenNothing :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
401 hscCodeGenNothing hsc_env mod_summary (iface, details, cgguts)
402 = return (NewHscRecomp False, iface, details)
404 -- Generate code and return both the new ModIface and the ModDetails.
405 hscCodeGenMake :: CodeGen (ModIface, ModDetails, CgGuts) (HscStatus, ModIface, ModDetails)
406 hscCodeGenMake hsc_env mod_summary (iface, details, cgguts)
407 = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
408 return (NewHscRecomp hasStub, iface, details)
410 -- Here we don't need the ModIface and ModDetails anymore.
411 hscCodeGenOneShot :: CodeGen (ModIface, ModDetails, CgGuts) HscStatus
412 hscCodeGenOneShot hsc_env mod_summary (_, _, cgguts)
413 = do hasStub <- hscCodeGenCompile hsc_env mod_summary cgguts
414 return (NewHscRecomp hasStub)
416 hscCodeGenCompile :: CodeGen CgGuts Bool
417 hscCodeGenCompile hsc_env mod_summary cgguts
418 = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
419 -- From now on, we just use the bits we need.
420 cg_module = this_mod,
421 cg_binds = core_binds,
423 cg_dir_imps = dir_imps,
424 cg_foreign = foreign_stubs,
425 cg_home_mods = home_mods,
426 cg_dep_pkgs = dependencies } = cgguts
427 dflags = hsc_dflags hsc_env
428 location = ms_location mod_summary
429 modName = ms_mod mod_summary
430 data_tycons = filter isDataTyCon tycons
431 -- cg_tycons includes newtypes, for the benefit of External Core,
432 -- but we don't generate any code for newtypes
435 -- PREPARE FOR CODE GENERATION
436 -- Do saturation and convert to A-normal form
437 prepd_binds <- {-# SCC "CorePrep" #-}
438 corePrepPgm dflags core_binds data_tycons ;
439 ----------------- Convert to STG ------------------
440 (stg_binds, cost_centre_info)
441 <- {-# SCC "CoreToStg" #-}
442 myCoreToStg dflags home_mods this_mod prepd_binds
443 ------------------ Code generation ------------------
444 abstractC <- {-# SCC "CodeGen" #-}
445 codeGen dflags home_mods this_mod data_tycons
446 foreign_stubs dir_imps cost_centre_info
448 ------------------ Code output -----------------------
449 (stub_h_exists,stub_c_exists)
450 <- codeOutput dflags this_mod location foreign_stubs
451 dependencies abstractC
454 hscCodeGenIdentity :: CodeGen a a
455 hscCodeGenIdentity hsc_env mod_summary a = return a
457 hscCodeGenSimple :: (a -> b) -> CodeGen a b
458 hscCodeGenSimple fn hsc_env mod_summary a = return (fn a)
460 hscCodeGenConst :: b -> CodeGen a b
461 hscCodeGenConst b hsc_env mod_summary a = return b
463 hscCodeGenInteractive :: CodeGen (ModIface, ModDetails, CgGuts)
464 (InteractiveStatus, ModIface, ModDetails)
465 hscCodeGenInteractive hsc_env mod_summary (iface, details, cgguts)
467 = do let CgGuts{ -- This is the last use of the ModGuts in a compilation.
468 -- From now on, we just use the bits we need.
469 cg_module = this_mod,
470 cg_binds = core_binds,
472 cg_foreign = foreign_stubs,
473 cg_home_mods = home_mods,
474 cg_dep_pkgs = dependencies } = cgguts
475 dflags = hsc_dflags hsc_env
476 location = ms_location mod_summary
477 modName = ms_mod mod_summary
478 data_tycons = filter isDataTyCon tycons
479 -- cg_tycons includes newtypes, for the benefit of External Core,
480 -- but we don't generate any code for newtypes
483 -- PREPARE FOR CODE GENERATION
484 -- Do saturation and convert to A-normal form
485 prepd_binds <- {-# SCC "CorePrep" #-}
486 corePrepPgm dflags core_binds data_tycons ;
487 ----------------- Generate byte code ------------------
488 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
489 ------------------ Create f-x-dynamic C-side stuff ---
490 (istub_h_exists, istub_c_exists)
491 <- outputForeignStubs dflags this_mod location foreign_stubs
492 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
494 = panic "GHC not compiled with interpreter"
499 --------------------------------------------------------------
500 -- Exterimental code end.
501 --------------------------------------------------------------
503 -- no errors or warnings; the individual passes
504 -- (parse/rename/typecheck) print messages themselves
509 -> Bool -- True <=> source unchanged
510 -> Bool -- True <=> have an object file (for msgs only)
511 -> Maybe ModIface -- Old interface, if available
512 -> Maybe (Int, Int) -- Just (i,n) <=> module i of n (for msgs)
515 hscMain hsc_env mod_summary
516 source_unchanged have_object maybe_old_iface
519 (recomp_reqd, maybe_checked_iface) <-
520 {-# SCC "checkOldIface" #-}
521 checkOldIface hsc_env mod_summary
522 source_unchanged maybe_old_iface;
524 let no_old_iface = not (isJust maybe_checked_iface)
525 what_next | recomp_reqd || no_old_iface = hscRecomp
526 | otherwise = hscNoRecomp
528 ; what_next hsc_env mod_summary have_object
534 ------------------------------
535 hscNoRecomp hsc_env mod_summary
536 have_object (Just old_iface)
538 | isOneShot (ghcMode (hsc_dflags hsc_env))
540 compilationProgressMsg (hsc_dflags hsc_env) $
541 "compilation IS NOT required";
542 dumpIfaceStats hsc_env ;
544 let { bomb = panic "hscNoRecomp:OneShot" };
545 return (HscNoRecomp bomb bomb)
548 = do { compilationProgressMsg (hsc_dflags hsc_env) $
549 (showModuleIndex mb_mod_index ++
550 "Skipping " ++ showModMsg have_object mod_summary)
552 ; new_details <- {-# SCC "tcRnIface" #-}
553 initIfaceCheck hsc_env $
554 typecheckIface old_iface ;
555 ; dumpIfaceStats hsc_env
557 ; return (HscNoRecomp new_details old_iface)
560 hscNoRecomp hsc_env mod_summary
563 = panic "hscNoRecomp" -- hscNoRecomp definitely expects to
564 -- have the old interface available
566 ------------------------------
567 hscRecomp hsc_env mod_summary
568 have_object maybe_old_iface
570 = case ms_hsc_src mod_summary of
572 front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
573 case ghcMode (hsc_dflags hsc_env) of
574 JustTypecheck -> hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
575 _ -> hscBackEnd hsc_env mod_summary maybe_old_iface front_res
578 front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
579 hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
582 front_res <- hscCoreFrontEnd hsc_env mod_summary mb_mod_index
583 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
585 hscCoreFrontEnd hsc_env mod_summary mb_mod_index = do {
589 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
590 ; case parseCore inp 1 of
591 FailP s -> errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-}) >> return Nothing
592 OkP rdr_module -> do {
595 -- RENAME and TYPECHECK
597 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
598 tcRnExtCore hsc_env rdr_module
599 ; printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
600 ; case maybe_tc_result of
601 Nothing -> return Nothing
602 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
606 hscFileFrontEnd hsc_env mod_summary mb_mod_index = do {
608 -- DISPLAY PROGRESS MESSAGE
610 ; let dflags = hsc_dflags hsc_env
611 one_shot = isOneShot (ghcMode dflags)
612 toInterp = hscTarget dflags == HscInterpreted
613 ; when (not one_shot) $
614 compilationProgressMsg dflags $
615 (showModuleIndex mb_mod_index ++
616 "Compiling " ++ showModMsg (not toInterp) mod_summary)
621 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
622 hspp_buf = ms_hspp_buf mod_summary
624 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
626 ; case maybe_parsed of {
627 Left err -> do { printBagOfErrors dflags (unitBag err)
629 Right rdr_module -> do {
632 -- RENAME and TYPECHECK
634 (tc_msgs, maybe_tc_result)
635 <- {-# SCC "Typecheck-Rename" #-}
636 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
638 ; printErrorsAndWarnings dflags tc_msgs
639 ; case maybe_tc_result of {
640 Nothing -> return Nothing ;
641 Just tc_result -> do {
646 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
647 deSugar hsc_env tc_result
648 ; printBagOfWarnings dflags warns
649 ; return maybe_ds_result
652 ------------------------------
654 hscFileCheck :: HscEnv -> ModSummary -> IO HscResult
655 hscFileCheck hsc_env mod_summary = do {
659 ; let dflags = hsc_dflags hsc_env
660 hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
661 hspp_buf = ms_hspp_buf mod_summary
663 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
665 ; case maybe_parsed of {
666 Left err -> do { printBagOfErrors dflags (unitBag err)
668 Right rdr_module -> do {
671 -- RENAME and TYPECHECK
673 (tc_msgs, maybe_tc_result)
674 <- _scc_ "Typecheck-Rename"
675 tcRnModule hsc_env (ms_hsc_src mod_summary)
676 True{-save renamed syntax-}
679 ; printErrorsAndWarnings dflags tc_msgs
680 ; case maybe_tc_result of {
681 Nothing -> return (HscChecked rdr_module Nothing Nothing);
683 let md = ModDetails {
684 md_types = tcg_type_env tc_result,
685 md_exports = tcg_exports tc_result,
686 md_insts = tcg_insts tc_result,
687 md_rules = [panic "no rules"] }
688 -- Rules are CoreRules, not the
689 -- RuleDecls we get out of the typechecker
690 rnInfo = do decl <- tcg_rn_decls tc_result
691 imports <- tcg_rn_imports tc_result
692 let exports = tcg_rn_exports tc_result
693 return (decl,imports,exports)
694 return (HscChecked rdr_module
696 (Just (tcg_binds tc_result,
697 tcg_rdr_env tc_result,
701 ------------------------------
702 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
703 -- For hs-boot files, there's no code generation to do
705 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing
707 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
708 = do { details <- mkBootModDetails hsc_env ds_result
710 ; (new_iface, no_change)
711 <- {-# SCC "MkFinalIface" #-}
712 mkIface hsc_env maybe_old_iface ds_result details
714 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
716 -- And the answer is ...
717 ; dumpIfaceStats hsc_env
719 ; return (HscRecomp details new_iface
723 ------------------------------
724 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
726 hscBackEnd hsc_env mod_summary maybe_old_iface Nothing
729 hscBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
731 -- ; seqList imported_modules (return ())
733 let one_shot = isOneShot (ghcMode dflags)
734 dflags = hsc_dflags hsc_env
739 ; flat_result <- {-# SCC "Flattening" #-}
740 flatten hsc_env ds_result
743 {- TEMP: need to review space-leak fixing here
744 NB: even the code generator can force one of the
745 thunks for constructor arguments, for newtypes in particular
747 ; let -- Rule-base accumulated from imported packages
748 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
750 -- In one-shot mode, ZAP the external package state at
751 -- this point, because we aren't going to need it from
752 -- now on. We keep the name cache, however, because
753 -- tidyCore needs it.
755 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
758 ; pkg_rule_base `seq` pcs_middle `seq` return ()
761 -- alive at this point:
769 ; simpl_result <- {-# SCC "Core2Core" #-}
770 core2core hsc_env flat_result
775 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
776 tidyProgram hsc_env simpl_result
778 -- Alive at this point:
779 -- tidy_result, pcs_final
783 -- BUILD THE NEW ModIface and ModDetails
784 -- and emit external core if necessary
785 -- This has to happen *after* code gen so that the back-end
786 -- info has been set. Not yet clear if it matters waiting
787 -- until after code output
788 ; (new_iface, no_change)
789 <- {-# SCC "MkFinalIface" #-}
790 mkIface hsc_env maybe_old_iface simpl_result details
792 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
794 -- Space leak reduction: throw away the new interface if
795 -- we're in one-shot mode; we won't be needing it any
797 ; final_iface <- if one_shot then return (error "no final iface")
798 else return new_iface
800 -- Build the final ModDetails (except in one-shot mode, where
801 -- we won't need this information after compilation).
802 ; final_details <- if one_shot then return (error "no final details")
803 else return $! details
805 -- Emit external core
806 ; emitExternalCore dflags cg_guts
809 -- CONVERT TO STG and COMPLETE CODE GENERATION
810 ; (stub_h_exists, stub_c_exists, maybe_bcos)
811 <- hscCodeGen dflags (ms_location mod_summary) cg_guts
813 -- And the answer is ...
814 ; dumpIfaceStats hsc_env
816 ; return (HscRecomp final_details
818 stub_h_exists stub_c_exists
824 hscCodeGen dflags location
825 CgGuts{ -- This is the last use of the ModGuts in a compilation.
826 -- From now on, we just use the bits we need.
827 cg_module = this_mod,
828 cg_binds = core_binds,
830 cg_dir_imps = dir_imps,
831 cg_foreign = foreign_stubs,
832 cg_home_mods = home_mods,
833 cg_dep_pkgs = dependencies } = do {
835 let { data_tycons = filter isDataTyCon tycons } ;
836 -- cg_tycons includes newtypes, for the benefit of External Core,
837 -- but we don't generate any code for newtypes
840 -- PREPARE FOR CODE GENERATION
841 -- Do saturation and convert to A-normal form
842 prepd_binds <- {-# SCC "CorePrep" #-}
843 corePrepPgm dflags core_binds data_tycons ;
845 case hscTarget dflags of
846 HscNothing -> return (False, False, Nothing)
850 do ----------------- Generate byte code ------------------
851 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
853 ------------------ Create f-x-dynamic C-side stuff ---
854 (istub_h_exists, istub_c_exists)
855 <- outputForeignStubs dflags this_mod location foreign_stubs
857 return ( istub_h_exists, istub_c_exists, Just comp_bc )
859 panic "GHC not compiled with interpreter"
864 ----------------- Convert to STG ------------------
865 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
866 myCoreToStg dflags home_mods this_mod prepd_binds
868 ------------------ Code generation ------------------
869 abstractC <- {-# SCC "CodeGen" #-}
870 codeGen dflags home_mods this_mod data_tycons
871 foreign_stubs dir_imps cost_centre_info
874 ------------------ Code output -----------------------
875 (stub_h_exists, stub_c_exists)
876 <- codeOutput dflags this_mod location foreign_stubs
877 dependencies abstractC
879 return (stub_h_exists, stub_c_exists, Nothing)
883 hscCmmFile :: DynFlags -> FilePath -> IO Bool
884 hscCmmFile dflags filename = do
885 maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
887 Nothing -> return False
889 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
892 no_mod = panic "hscCmmFile: no_mod"
893 no_loc = ModLocation{ ml_hs_file = Just filename,
894 ml_hi_file = panic "hscCmmFile: no hi file",
895 ml_obj_file = panic "hscCmmFile: no obj file" }
898 myParseModule dflags src_filename maybe_src_buf
899 = -------------------------- Parser ----------------
900 showPass dflags "Parser" >>
901 {-# SCC "Parser" #-} do
903 -- sometimes we already have the buffer in memory, perhaps
904 -- because we needed to parse the imports out of it, or get the
906 buf <- case maybe_src_buf of
908 Nothing -> hGetStringBuffer src_filename
910 let loc = mkSrcLoc (mkFastString src_filename) 1 0
912 case unP parseModule (mkPState buf loc dflags) of {
914 PFailed span err -> return (Left (mkPlainErrMsg span err));
916 POk _ rdr_module -> do {
918 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
920 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
921 (ppSourceStats False rdr_module) ;
923 return (Right rdr_module)
924 -- ToDo: free the string buffer later.
928 myCoreToStg dflags home_mods this_mod prepd_binds
930 stg_binds <- {-# SCC "Core2Stg" #-}
931 coreToStg home_mods prepd_binds
933 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
934 stg2stg dflags home_mods this_mod stg_binds
936 return (stg_binds2, cost_centre_info)
940 %************************************************************************
942 \subsection{Compiling a do-statement}
944 %************************************************************************
946 When the UnlinkedBCOExpr is linked you get an HValue of type
948 When you run it you get a list of HValues that should be
949 the same length as the list of names; add them to the ClosureEnv.
951 A naked expression returns a singleton Name [it].
953 What you type The IO [HValue] that hscStmt returns
954 ------------- ------------------------------------
955 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
958 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
961 expr (of IO type) ==> expr >>= \ v -> return [v]
962 [NB: result not printed] bindings: [it]
965 expr (of non-IO type,
966 result showable) ==> let v = expr in print v >> return [v]
969 expr (of non-IO type,
970 result not showable) ==> error
974 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
976 -> String -- The statement
977 -> IO (Maybe (HscEnv, [Name], HValue))
980 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
981 ; case maybe_stmt of {
982 Nothing -> return Nothing ; -- Parse error
983 Just Nothing -> return Nothing ; -- Empty line
984 Just (Just parsed_stmt) -> do { -- The real stuff
986 -- Rename and typecheck it
987 let icontext = hsc_IC hsc_env
988 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
990 ; case maybe_tc_result of {
991 Nothing -> return Nothing ;
992 Just (new_ic, bound_names, tc_expr) -> do {
994 -- Then desugar, code gen, and link it
995 ; hval <- compileExpr hsc_env iNTERACTIVE
996 (ic_rn_gbl_env new_ic)
1000 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
1003 hscTcExpr -- Typecheck an expression (but don't run it)
1005 -> String -- The expression
1008 hscTcExpr hsc_env expr
1009 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
1010 ; let icontext = hsc_IC hsc_env
1011 ; case maybe_stmt of {
1012 Nothing -> return Nothing ; -- Parse error
1013 Just (Just (L _ (ExprStmt expr _ _)))
1014 -> tcRnExpr hsc_env icontext expr ;
1015 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
1019 hscKcType -- Find the kind of a type
1021 -> String -- The type
1024 hscKcType hsc_env str
1025 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
1026 ; let icontext = hsc_IC hsc_env
1027 ; case maybe_type of {
1028 Just ty -> tcRnType hsc_env icontext ty ;
1029 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
1031 Nothing -> return Nothing } }
1037 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
1038 hscParseStmt = hscParseThing parseStmt
1040 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
1041 hscParseType = hscParseThing parseType
1044 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
1045 hscParseIdentifier = hscParseThing parseIdentifier
1047 hscParseThing :: Outputable thing
1049 -> DynFlags -> String
1051 -- Nothing => Parse error (message already printed)
1052 -- Just x => success
1053 hscParseThing parser dflags str
1054 = showPass dflags "Parser" >>
1055 {-# SCC "Parser" #-} do
1057 buf <- stringToStringBuffer str
1059 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
1061 case unP parser (mkPState buf loc dflags) of {
1063 PFailed span err -> do { printError span err;
1068 --ToDo: can't free the string buffer until we've finished this
1069 -- compilation sweep and all the identifiers have gone away.
1070 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
1075 %************************************************************************
1077 Desugar, simplify, convert to bytecode, and link an expression
1079 %************************************************************************
1083 compileExpr :: HscEnv
1084 -> Module -> GlobalRdrEnv -> TypeEnv
1088 compileExpr hsc_env this_mod rdr_env type_env tc_expr
1089 = do { let { dflags = hsc_dflags hsc_env ;
1090 lint_on = dopt Opt_DoCoreLinting dflags }
1093 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
1096 ; flat_expr <- flattenExpr hsc_env ds_expr
1099 ; simpl_expr <- simplifyExpr dflags flat_expr
1101 -- Tidy it (temporary, until coreSat does cloning)
1102 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1104 -- Prepare for codegen
1105 ; prepd_expr <- corePrepExpr dflags tidy_expr
1107 -- Lint if necessary
1108 -- ToDo: improve SrcLoc
1110 case lintUnfolding noSrcLoc [] prepd_expr of
1111 Just err -> pprPanic "compileExpr" err
1112 Nothing -> return ()
1117 ; bcos <- coreExprToBCOs dflags prepd_expr
1120 ; hval <- linkExpr hsc_env bcos
1128 %************************************************************************
1130 Statistics on reading interfaces
1132 %************************************************************************
1135 dumpIfaceStats :: HscEnv -> IO ()
1136 dumpIfaceStats hsc_env
1137 = do { eps <- readIORef (hsc_EPS hsc_env)
1138 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1139 "Interface statistics"
1142 dflags = hsc_dflags hsc_env
1143 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1144 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1147 %************************************************************************
1149 Progress Messages: Module i of n
1151 %************************************************************************
1154 showModuleIndex Nothing = ""
1155 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1159 padded = replicate (length n_str - length i_str) ' ' ++ i_str