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 )
42 import RdrName ( GlobalRdrEnv, RdrName )
43 import HsSyn ( HsModule, LHsBinds, HsGroup )
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 Name ( Name, NamedThing(..) )
64 import SimplStg ( stg2stg )
65 import CodeGen ( codeGen )
66 import CmmParse ( parseCmmFile )
67 import CodeOutput ( codeOutput )
71 import UniqSupply ( mkSplitUniqSupply )
74 import HscStats ( ppSourceStats )
76 import MkExternalCore ( emitExternalCore )
78 import ParserCoreUtils
80 import Maybes ( expectJust )
81 import Bag ( unitBag, emptyBag )
83 import Maybe ( isJust )
85 import DATA_IOREF ( newIORef, readIORef )
89 %************************************************************************
93 %************************************************************************
96 newHscEnv :: DynFlags -> IO HscEnv
98 = do { eps_var <- newIORef initExternalPackageState
99 ; us <- mkSplitUniqSupply 'r'
100 ; nc_var <- newIORef (initNameCache us knownKeyNames)
101 ; fc_var <- newIORef emptyModuleEnv
102 ; return (HscEnv { hsc_dflags = dflags,
105 hsc_IC = emptyInteractiveContext,
106 hsc_HPT = emptyHomePackageTable,
109 hsc_FC = fc_var } ) }
112 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
113 -- where templateHaskellNames are defined
114 knownKeyNames = map getName wiredInThings
115 ++ basicKnownKeyNames
117 ++ templateHaskellNames
122 %************************************************************************
124 The main compiler pipeline
126 %************************************************************************
130 -- Compilation failed
133 -- In IDE mode: we just do the static/dynamic checks
135 (Located (HsModule RdrName)) -- parsed
136 (Maybe (HsGroup Name)) -- renamed
137 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails)) -- typechecked
139 -- Concluded that it wasn't necessary
140 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
141 ModIface -- new iface (if any compilation was done)
144 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
145 ModIface -- new iface (if any compilation was done)
146 Bool -- stub_h exists
147 Bool -- stub_c exists
148 (Maybe CompiledByteCode)
151 -- What to do when we have compiler error or warning messages
152 type MessageAction = Messages -> IO ()
154 -- no errors or warnings; the individual passes
155 -- (parse/rename/typecheck) print messages themselves
159 -> MessageAction -- What to do with errors/warnings
161 -> Bool -- True <=> source unchanged
162 -> Bool -- True <=> have an object file (for msgs only)
163 -> Maybe ModIface -- Old interface, if available
164 -> Maybe (Int, Int) -- Just (i,n) <=> module i of n (for msgs)
167 hscMain hsc_env msg_act mod_summary
168 source_unchanged have_object maybe_old_iface
171 (recomp_reqd, maybe_checked_iface) <-
172 {-# SCC "checkOldIface" #-}
173 checkOldIface hsc_env mod_summary
174 source_unchanged maybe_old_iface;
176 let no_old_iface = not (isJust maybe_checked_iface)
177 what_next | recomp_reqd || no_old_iface = hscRecomp
178 | otherwise = hscNoRecomp
180 ; what_next hsc_env msg_act mod_summary have_object
186 ------------------------------
187 hscNoRecomp hsc_env msg_act mod_summary
188 have_object (Just old_iface)
190 | isOneShot (ghcMode (hsc_dflags hsc_env))
192 compilationProgressMsg (hsc_dflags hsc_env) $
193 "compilation IS NOT required";
194 dumpIfaceStats hsc_env ;
196 let { bomb = panic "hscNoRecomp:OneShot" };
197 return (HscNoRecomp bomb bomb)
200 = do { compilationProgressMsg (hsc_dflags hsc_env) $
201 (showModuleIndex mb_mod_index ++
202 "Skipping " ++ showModMsg have_object mod_summary)
204 ; new_details <- {-# SCC "tcRnIface" #-}
205 initIfaceCheck hsc_env $
206 typecheckIface old_iface ;
207 ; dumpIfaceStats hsc_env
209 ; return (HscNoRecomp new_details old_iface)
212 hscNoRecomp hsc_env msg_act mod_summary
215 = panic "hscNoRecomp" -- hscNoRecomp definitely expects to
216 -- have the old interface available
218 ------------------------------
219 hscRecomp hsc_env msg_act mod_summary
220 have_object maybe_old_iface
222 = case ms_hsc_src mod_summary of
224 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index
225 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
228 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index
229 hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
232 front_res <- hscCoreFrontEnd hsc_env msg_act mod_summary
233 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
235 hscCoreFrontEnd hsc_env msg_act mod_summary = do {
239 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
240 ; case parseCore inp 1 of
241 FailP s -> putMsg s{-ToDo: wrong-} >> return Nothing
242 OkP rdr_module -> do {
245 -- RENAME and TYPECHECK
247 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
248 tcRnExtCore hsc_env rdr_module
250 ; case maybe_tc_result of
251 Nothing -> return Nothing
252 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
256 hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index = do {
258 -- DISPLAY PROGRESS MESSAGE
260 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
261 ; let dflags = hsc_dflags hsc_env
262 ; let toInterp = hscTarget dflags == HscInterpreted
263 ; when (not one_shot) $
264 compilationProgressMsg dflags $
265 (showModuleIndex mb_mod_index ++
266 "Compiling " ++ showModMsg (not toInterp) mod_summary)
271 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
272 hspp_buf = ms_hspp_buf mod_summary
274 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
276 ; case maybe_parsed of {
277 Left err -> do { msg_act (unitBag err, emptyBag)
279 Right rdr_module -> do {
282 -- RENAME and TYPECHECK
284 (tc_msgs, maybe_tc_result)
285 <- {-# SCC "Typecheck-Rename" #-}
286 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
289 ; case maybe_tc_result of {
290 Nothing -> return Nothing ;
291 Just tc_result -> do {
296 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
297 deSugar hsc_env tc_result
298 ; msg_act (warns, emptyBag)
299 ; return maybe_ds_result
302 ------------------------------
304 hscFileCheck :: HscEnv -> MessageAction -> ModSummary -> IO HscResult
305 hscFileCheck hsc_env msg_act mod_summary = do {
309 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
310 hspp_buf = ms_hspp_buf mod_summary
312 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
314 ; case maybe_parsed of {
315 Left err -> do { msg_act (unitBag err, emptyBag)
317 Right rdr_module -> do {
320 -- RENAME and TYPECHECK
322 (tc_msgs, maybe_tc_result)
323 <- _scc_ "Typecheck-Rename"
324 tcRnModule hsc_env (ms_hsc_src mod_summary)
325 True{-save renamed syntax-}
329 ; case maybe_tc_result of {
330 Nothing -> return (HscChecked rdr_module Nothing Nothing);
332 let md = ModDetails {
333 md_types = tcg_type_env tc_result,
334 md_exports = tcg_exports tc_result,
335 md_insts = tcg_insts tc_result,
336 md_rules = [panic "no rules"] }
337 -- Rules are CoreRules, not the
338 -- RuleDecls we get out of the typechecker
339 return (HscChecked rdr_module
340 (tcg_rn_decls tc_result)
341 (Just (tcg_binds tc_result,
342 tcg_rdr_env tc_result,
346 ------------------------------
347 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
348 -- For hs-boot files, there's no code generation to do
350 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing
352 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
353 = do { details <- mkBootModDetails hsc_env ds_result
355 ; (new_iface, no_change)
356 <- {-# SCC "MkFinalIface" #-}
357 mkIface hsc_env maybe_old_iface ds_result details
359 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
361 -- And the answer is ...
362 ; dumpIfaceStats hsc_env
364 ; return (HscRecomp details new_iface
368 ------------------------------
369 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
371 hscBackEnd hsc_env mod_summary maybe_old_iface Nothing
374 hscBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
376 -- ; seqList imported_modules (return ())
378 let one_shot = isOneShot (ghcMode dflags)
379 dflags = hsc_dflags hsc_env
384 ; flat_result <- {-# SCC "Flattening" #-}
385 flatten hsc_env ds_result
388 {- TEMP: need to review space-leak fixing here
389 NB: even the code generator can force one of the
390 thunks for constructor arguments, for newtypes in particular
392 ; let -- Rule-base accumulated from imported packages
393 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
395 -- In one-shot mode, ZAP the external package state at
396 -- this point, because we aren't going to need it from
397 -- now on. We keep the name cache, however, because
398 -- tidyCore needs it.
400 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
403 ; pkg_rule_base `seq` pcs_middle `seq` return ()
406 -- alive at this point:
414 ; simpl_result <- {-# SCC "Core2Core" #-}
415 core2core hsc_env flat_result
420 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
421 tidyProgram hsc_env simpl_result
423 -- Alive at this point:
424 -- tidy_result, pcs_final
428 -- BUILD THE NEW ModIface and ModDetails
429 -- and emit external core if necessary
430 -- This has to happen *after* code gen so that the back-end
431 -- info has been set. Not yet clear if it matters waiting
432 -- until after code output
433 ; (new_iface, no_change)
434 <- {-# SCC "MkFinalIface" #-}
435 mkIface hsc_env maybe_old_iface simpl_result details
437 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
439 -- Space leak reduction: throw away the new interface if
440 -- we're in one-shot mode; we won't be needing it any
442 ; final_iface <- if one_shot then return (error "no final iface")
443 else return new_iface
445 -- Build the final ModDetails (except in one-shot mode, where
446 -- we won't need this information after compilation).
447 ; final_details <- if one_shot then return (error "no final details")
448 else return $! details
450 -- Emit external core
451 ; emitExternalCore dflags cg_guts
454 -- CONVERT TO STG and COMPLETE CODE GENERATION
455 ; (stub_h_exists, stub_c_exists, maybe_bcos)
456 <- hscCodeGen dflags cg_guts
458 -- And the answer is ...
459 ; dumpIfaceStats hsc_env
461 ; return (HscRecomp final_details
463 stub_h_exists stub_c_exists
470 CgGuts{ -- This is the last use of the ModGuts in a compilation.
471 -- From now on, we just use the bits we need.
472 cg_module = this_mod,
473 cg_binds = core_binds,
475 cg_dir_imps = dir_imps,
476 cg_foreign = foreign_stubs,
477 cg_dep_pkgs = dependencies } = do {
479 let { data_tycons = filter isDataTyCon tycons } ;
480 -- cg_tycons includes newtypes, for the benefit of External Core,
481 -- but we don't generate any code for newtypes
484 -- PREPARE FOR CODE GENERATION
485 -- Do saturation and convert to A-normal form
486 prepd_binds <- {-# SCC "CorePrep" #-}
487 corePrepPgm dflags core_binds data_tycons ;
489 case hscTarget dflags of
490 HscNothing -> return (False, False, Nothing)
494 do ----------------- Generate byte code ------------------
495 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
497 ------------------ Create f-x-dynamic C-side stuff ---
498 (istub_h_exists, istub_c_exists)
499 <- outputForeignStubs dflags foreign_stubs
501 return ( istub_h_exists, istub_c_exists, Just comp_bc )
503 panic "GHC not compiled with interpreter"
508 ----------------- Convert to STG ------------------
509 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
510 myCoreToStg dflags this_mod prepd_binds
512 ------------------ Code generation ------------------
513 abstractC <- {-# SCC "CodeGen" #-}
514 codeGen dflags this_mod data_tycons foreign_stubs
515 dir_imps cost_centre_info stg_binds
517 ------------------ Code output -----------------------
518 (stub_h_exists, stub_c_exists)
519 <- codeOutput dflags this_mod foreign_stubs
520 dependencies abstractC
522 return (stub_h_exists, stub_c_exists, Nothing)
526 hscCmmFile :: DynFlags -> FilePath -> IO Bool
527 hscCmmFile dflags filename = do
528 maybe_cmm <- parseCmmFile dflags filename
530 Nothing -> return False
532 codeOutput dflags no_mod NoStubs [] [cmm]
535 no_mod = panic "hscCmmFile: no_mod"
538 myParseModule dflags src_filename maybe_src_buf
539 = -------------------------- Parser ----------------
540 showPass dflags "Parser" >>
541 {-# SCC "Parser" #-} do
543 -- sometimes we already have the buffer in memory, perhaps
544 -- because we needed to parse the imports out of it, or get the
546 buf <- case maybe_src_buf of
548 Nothing -> hGetStringBuffer src_filename
550 let loc = mkSrcLoc (mkFastString src_filename) 1 0
552 case unP parseModule (mkPState buf loc dflags) of {
554 PFailed span err -> return (Left (mkPlainErrMsg span err));
556 POk _ rdr_module -> do {
558 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
560 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
561 (ppSourceStats False rdr_module) ;
563 return (Right rdr_module)
564 -- ToDo: free the string buffer later.
568 myCoreToStg dflags this_mod prepd_binds
570 stg_binds <- {-# SCC "Core2Stg" #-}
571 coreToStg dflags prepd_binds
573 (stg_binds2, cost_centre_info) <- {-# SCC "Core2Stg" #-}
574 stg2stg dflags this_mod stg_binds
576 return (stg_binds2, cost_centre_info)
580 %************************************************************************
582 \subsection{Compiling a do-statement}
584 %************************************************************************
586 When the UnlinkedBCOExpr is linked you get an HValue of type
588 When you run it you get a list of HValues that should be
589 the same length as the list of names; add them to the ClosureEnv.
591 A naked expression returns a singleton Name [it].
593 What you type The IO [HValue] that hscStmt returns
594 ------------- ------------------------------------
595 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
598 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
601 expr (of IO type) ==> expr >>= \ v -> return [v]
602 [NB: result not printed] bindings: [it]
605 expr (of non-IO type,
606 result showable) ==> let v = expr in print v >> return [v]
609 expr (of non-IO type,
610 result not showable) ==> error
614 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
616 -> String -- The statement
617 -> IO (Maybe (HscEnv, [Name], HValue))
620 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
621 ; case maybe_stmt of {
622 Nothing -> return Nothing ; -- Parse error
623 Just Nothing -> return Nothing ; -- Empty line
624 Just (Just parsed_stmt) -> do { -- The real stuff
626 -- Rename and typecheck it
627 let icontext = hsc_IC hsc_env
628 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
630 ; case maybe_tc_result of {
631 Nothing -> return Nothing ;
632 Just (new_ic, bound_names, tc_expr) -> do {
634 -- Then desugar, code gen, and link it
635 ; hval <- compileExpr hsc_env iNTERACTIVE
636 (ic_rn_gbl_env new_ic)
640 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
643 hscTcExpr -- Typecheck an expression (but don't run it)
645 -> String -- The expression
648 hscTcExpr hsc_env expr
649 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
650 ; let icontext = hsc_IC hsc_env
651 ; case maybe_stmt of {
652 Nothing -> return Nothing ; -- Parse error
653 Just (Just (L _ (ExprStmt expr _ _)))
654 -> tcRnExpr hsc_env icontext expr ;
655 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
659 hscKcType -- Find the kind of a type
661 -> String -- The type
664 hscKcType hsc_env str
665 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
666 ; let icontext = hsc_IC hsc_env
667 ; case maybe_type of {
668 Just ty -> tcRnType hsc_env icontext ty ;
669 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
671 Nothing -> return Nothing } }
677 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
678 hscParseStmt = hscParseThing parseStmt
680 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
681 hscParseType = hscParseThing parseType
684 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
685 hscParseIdentifier = hscParseThing parseIdentifier
687 hscParseThing :: Outputable thing
689 -> DynFlags -> String
691 -- Nothing => Parse error (message already printed)
693 hscParseThing parser dflags str
694 = showPass dflags "Parser" >>
695 {-# SCC "Parser" #-} do
697 buf <- stringToStringBuffer str
699 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
701 case unP parser (mkPState buf loc dflags) of {
703 PFailed span err -> do { printError span err;
708 --ToDo: can't free the string buffer until we've finished this
709 -- compilation sweep and all the identifiers have gone away.
710 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
715 %************************************************************************
717 Desugar, simplify, convert to bytecode, and link an expression
719 %************************************************************************
723 compileExpr :: HscEnv
724 -> Module -> GlobalRdrEnv -> TypeEnv
728 compileExpr hsc_env this_mod rdr_env type_env tc_expr
729 = do { let { dflags = hsc_dflags hsc_env ;
730 lint_on = dopt Opt_DoCoreLinting dflags }
733 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
736 ; flat_expr <- flattenExpr hsc_env ds_expr
739 ; simpl_expr <- simplifyExpr dflags flat_expr
741 -- Tidy it (temporary, until coreSat does cloning)
742 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
744 -- Prepare for codegen
745 ; prepd_expr <- corePrepExpr dflags tidy_expr
748 -- ToDo: improve SrcLoc
750 case lintUnfolding noSrcLoc [] prepd_expr of
751 Just err -> pprPanic "compileExpr" err
757 ; bcos <- coreExprToBCOs dflags prepd_expr
760 ; hval <- linkExpr hsc_env bcos
768 %************************************************************************
770 Statistics on reading interfaces
772 %************************************************************************
775 dumpIfaceStats :: HscEnv -> IO ()
776 dumpIfaceStats hsc_env
777 = do { eps <- readIORef (hsc_EPS hsc_env)
778 ; dumpIfSet (dump_if_trace || dump_rn_stats)
779 "Interface statistics"
782 dflags = hsc_dflags hsc_env
783 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
784 dump_if_trace = dopt Opt_D_dump_if_trace dflags
787 %************************************************************************
789 Progress Messages: Module i of n
791 %************************************************************************
794 showModuleIndex Nothing = ""
795 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
799 padded = replicate (length n_str - length i_str) ' ' ++ i_str