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 Packages ( mkHomeModules )
64 import Name ( Name, NamedThing(..) )
65 import SimplStg ( stg2stg )
66 import CodeGen ( codeGen )
67 import CmmParse ( parseCmmFile )
68 import CodeOutput ( codeOutput )
72 import UniqSupply ( mkSplitUniqSupply )
75 import HscStats ( ppSourceStats )
77 import MkExternalCore ( emitExternalCore )
79 import ParserCoreUtils
81 import Maybes ( expectJust )
82 import Bag ( unitBag, emptyBag )
84 import Maybe ( isJust )
86 import DATA_IOREF ( newIORef, readIORef )
90 %************************************************************************
94 %************************************************************************
97 newHscEnv :: DynFlags -> IO HscEnv
99 = do { eps_var <- newIORef initExternalPackageState
100 ; us <- mkSplitUniqSupply 'r'
101 ; nc_var <- newIORef (initNameCache us knownKeyNames)
102 ; fc_var <- newIORef emptyModuleEnv
103 ; return (HscEnv { hsc_dflags = dflags,
106 hsc_IC = emptyInteractiveContext,
107 hsc_HPT = emptyHomePackageTable,
110 hsc_FC = fc_var } ) }
113 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
114 -- where templateHaskellNames are defined
115 knownKeyNames = map getName wiredInThings
116 ++ basicKnownKeyNames
118 ++ templateHaskellNames
123 %************************************************************************
125 The main compiler pipeline
127 %************************************************************************
131 -- Compilation failed
134 -- In IDE mode: we just do the static/dynamic checks
136 (Located (HsModule RdrName)) -- parsed
137 (Maybe (HsGroup Name)) -- renamed
138 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails)) -- typechecked
140 -- Concluded that it wasn't necessary
141 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
142 ModIface -- new iface (if any compilation was done)
145 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
146 ModIface -- new iface (if any compilation was done)
147 Bool -- stub_h exists
148 Bool -- stub_c exists
149 (Maybe CompiledByteCode)
152 -- What to do when we have compiler error or warning messages
153 type MessageAction = Messages -> IO ()
155 -- no errors or warnings; the individual passes
156 -- (parse/rename/typecheck) print messages themselves
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 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 mod_summary have_object
186 ------------------------------
187 hscNoRecomp hsc_env 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 mod_summary
215 = panic "hscNoRecomp" -- hscNoRecomp definitely expects to
216 -- have the old interface available
218 ------------------------------
219 hscRecomp hsc_env mod_summary
220 have_object maybe_old_iface
222 = case ms_hsc_src mod_summary of
224 front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
225 case ghcMode (hsc_dflags hsc_env) of
226 JustTypecheck -> hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
227 _ -> hscBackEnd hsc_env mod_summary maybe_old_iface front_res
230 front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
231 hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
234 front_res <- hscCoreFrontEnd hsc_env mod_summary
235 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
237 hscCoreFrontEnd hsc_env mod_summary = do {
241 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
242 ; case parseCore inp 1 of
243 FailP s -> errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-}) >> return Nothing
244 OkP rdr_module -> do {
247 -- RENAME and TYPECHECK
249 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
250 tcRnExtCore hsc_env rdr_module
251 ; printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
252 ; case maybe_tc_result of
253 Nothing -> return Nothing
254 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
258 hscFileFrontEnd hsc_env mod_summary mb_mod_index = do {
260 -- DISPLAY PROGRESS MESSAGE
262 ; let dflags = hsc_dflags hsc_env
263 one_shot = isOneShot (ghcMode dflags)
264 toInterp = hscTarget dflags == HscInterpreted
265 ; when (not one_shot) $
266 compilationProgressMsg dflags $
267 (showModuleIndex mb_mod_index ++
268 "Compiling " ++ showModMsg (not toInterp) mod_summary)
273 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
274 hspp_buf = ms_hspp_buf mod_summary
276 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
278 ; case maybe_parsed of {
279 Left err -> do { printBagOfErrors dflags (unitBag err)
281 Right rdr_module -> do {
284 -- RENAME and TYPECHECK
286 (tc_msgs, maybe_tc_result)
287 <- {-# SCC "Typecheck-Rename" #-}
288 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
290 ; printErrorsAndWarnings dflags tc_msgs
291 ; case maybe_tc_result of {
292 Nothing -> return Nothing ;
293 Just tc_result -> do {
298 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
299 deSugar hsc_env tc_result
300 ; printBagOfWarnings dflags warns
301 ; return maybe_ds_result
304 ------------------------------
306 hscFileCheck :: HscEnv -> ModSummary -> IO HscResult
307 hscFileCheck hsc_env mod_summary = do {
311 ; let dflags = hsc_dflags hsc_env
312 hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
313 hspp_buf = ms_hspp_buf mod_summary
315 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
317 ; case maybe_parsed of {
318 Left err -> do { printBagOfErrors dflags (unitBag err)
320 Right rdr_module -> do {
323 -- RENAME and TYPECHECK
325 (tc_msgs, maybe_tc_result)
326 <- _scc_ "Typecheck-Rename"
327 tcRnModule hsc_env (ms_hsc_src mod_summary)
328 True{-save renamed syntax-}
331 ; printErrorsAndWarnings dflags tc_msgs
332 ; case maybe_tc_result of {
333 Nothing -> return (HscChecked rdr_module Nothing Nothing);
335 let md = ModDetails {
336 md_types = tcg_type_env tc_result,
337 md_exports = tcg_exports tc_result,
338 md_insts = tcg_insts tc_result,
339 md_rules = [panic "no rules"] }
340 -- Rules are CoreRules, not the
341 -- RuleDecls we get out of the typechecker
342 return (HscChecked rdr_module
343 (tcg_rn_decls tc_result)
344 (Just (tcg_binds tc_result,
345 tcg_rdr_env tc_result,
349 ------------------------------
350 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
351 -- For hs-boot files, there's no code generation to do
353 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing
355 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
356 = do { details <- mkBootModDetails hsc_env ds_result
358 ; (new_iface, no_change)
359 <- {-# SCC "MkFinalIface" #-}
360 mkIface hsc_env maybe_old_iface ds_result details
362 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
364 -- And the answer is ...
365 ; dumpIfaceStats hsc_env
367 ; return (HscRecomp details new_iface
371 ------------------------------
372 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
374 hscBackEnd hsc_env mod_summary maybe_old_iface Nothing
377 hscBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
379 -- ; seqList imported_modules (return ())
381 let one_shot = isOneShot (ghcMode dflags)
382 dflags = hsc_dflags hsc_env
387 ; flat_result <- {-# SCC "Flattening" #-}
388 flatten hsc_env ds_result
391 {- TEMP: need to review space-leak fixing here
392 NB: even the code generator can force one of the
393 thunks for constructor arguments, for newtypes in particular
395 ; let -- Rule-base accumulated from imported packages
396 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
398 -- In one-shot mode, ZAP the external package state at
399 -- this point, because we aren't going to need it from
400 -- now on. We keep the name cache, however, because
401 -- tidyCore needs it.
403 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
406 ; pkg_rule_base `seq` pcs_middle `seq` return ()
409 -- alive at this point:
417 ; simpl_result <- {-# SCC "Core2Core" #-}
418 core2core hsc_env flat_result
423 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
424 tidyProgram hsc_env simpl_result
426 -- Alive at this point:
427 -- tidy_result, pcs_final
431 -- BUILD THE NEW ModIface and ModDetails
432 -- and emit external core if necessary
433 -- This has to happen *after* code gen so that the back-end
434 -- info has been set. Not yet clear if it matters waiting
435 -- until after code output
436 ; (new_iface, no_change)
437 <- {-# SCC "MkFinalIface" #-}
438 mkIface hsc_env maybe_old_iface simpl_result details
440 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
442 -- Space leak reduction: throw away the new interface if
443 -- we're in one-shot mode; we won't be needing it any
445 ; final_iface <- if one_shot then return (error "no final iface")
446 else return new_iface
448 -- Build the final ModDetails (except in one-shot mode, where
449 -- we won't need this information after compilation).
450 ; final_details <- if one_shot then return (error "no final details")
451 else return $! details
453 -- Emit external core
454 ; emitExternalCore dflags cg_guts
457 -- CONVERT TO STG and COMPLETE CODE GENERATION
458 ; (stub_h_exists, stub_c_exists, maybe_bcos)
459 <- hscCodeGen dflags cg_guts
461 -- And the answer is ...
462 ; dumpIfaceStats hsc_env
464 ; return (HscRecomp final_details
466 stub_h_exists stub_c_exists
473 CgGuts{ -- This is the last use of the ModGuts in a compilation.
474 -- From now on, we just use the bits we need.
475 cg_module = this_mod,
476 cg_binds = core_binds,
478 cg_dir_imps = dir_imps,
479 cg_foreign = foreign_stubs,
480 cg_home_mods = home_mods,
481 cg_dep_pkgs = dependencies } = do {
483 let { data_tycons = filter isDataTyCon tycons } ;
484 -- cg_tycons includes newtypes, for the benefit of External Core,
485 -- but we don't generate any code for newtypes
488 -- PREPARE FOR CODE GENERATION
489 -- Do saturation and convert to A-normal form
490 prepd_binds <- {-# SCC "CorePrep" #-}
491 corePrepPgm dflags core_binds data_tycons ;
493 case hscTarget dflags of
494 HscNothing -> return (False, False, Nothing)
498 do ----------------- Generate byte code ------------------
499 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
501 ------------------ Create f-x-dynamic C-side stuff ---
502 (istub_h_exists, istub_c_exists)
503 <- outputForeignStubs dflags foreign_stubs
505 return ( istub_h_exists, istub_c_exists, Just comp_bc )
507 panic "GHC not compiled with interpreter"
512 ----------------- Convert to STG ------------------
513 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
514 myCoreToStg dflags home_mods this_mod prepd_binds
516 ------------------ Code generation ------------------
517 abstractC <- {-# SCC "CodeGen" #-}
518 codeGen dflags home_mods this_mod data_tycons
519 foreign_stubs dir_imps cost_centre_info
522 ------------------ Code output -----------------------
523 (stub_h_exists, stub_c_exists)
524 <- codeOutput dflags this_mod foreign_stubs
525 dependencies abstractC
527 return (stub_h_exists, stub_c_exists, Nothing)
531 hscCmmFile :: DynFlags -> FilePath -> IO Bool
532 hscCmmFile dflags filename = do
533 maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
535 Nothing -> return False
537 codeOutput dflags no_mod NoStubs [] [cmm]
540 no_mod = panic "hscCmmFile: no_mod"
543 myParseModule dflags src_filename maybe_src_buf
544 = -------------------------- Parser ----------------
545 showPass dflags "Parser" >>
546 {-# SCC "Parser" #-} do
548 -- sometimes we already have the buffer in memory, perhaps
549 -- because we needed to parse the imports out of it, or get the
551 buf <- case maybe_src_buf of
553 Nothing -> hGetStringBuffer src_filename
555 let loc = mkSrcLoc (mkFastString src_filename) 1 0
557 case unP parseModule (mkPState buf loc dflags) of {
559 PFailed span err -> return (Left (mkPlainErrMsg span err));
561 POk _ rdr_module -> do {
563 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
565 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
566 (ppSourceStats False rdr_module) ;
568 return (Right rdr_module)
569 -- ToDo: free the string buffer later.
573 myCoreToStg dflags home_mods this_mod prepd_binds
575 stg_binds <- {-# SCC "Core2Stg" #-}
576 coreToStg home_mods prepd_binds
578 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
579 stg2stg dflags home_mods this_mod stg_binds
581 return (stg_binds2, cost_centre_info)
585 %************************************************************************
587 \subsection{Compiling a do-statement}
589 %************************************************************************
591 When the UnlinkedBCOExpr is linked you get an HValue of type
593 When you run it you get a list of HValues that should be
594 the same length as the list of names; add them to the ClosureEnv.
596 A naked expression returns a singleton Name [it].
598 What you type The IO [HValue] that hscStmt returns
599 ------------- ------------------------------------
600 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
603 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
606 expr (of IO type) ==> expr >>= \ v -> return [v]
607 [NB: result not printed] bindings: [it]
610 expr (of non-IO type,
611 result showable) ==> let v = expr in print v >> return [v]
614 expr (of non-IO type,
615 result not showable) ==> error
619 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
621 -> String -- The statement
622 -> IO (Maybe (HscEnv, [Name], HValue))
625 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
626 ; case maybe_stmt of {
627 Nothing -> return Nothing ; -- Parse error
628 Just Nothing -> return Nothing ; -- Empty line
629 Just (Just parsed_stmt) -> do { -- The real stuff
631 -- Rename and typecheck it
632 let icontext = hsc_IC hsc_env
633 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
635 ; case maybe_tc_result of {
636 Nothing -> return Nothing ;
637 Just (new_ic, bound_names, tc_expr) -> do {
639 -- Then desugar, code gen, and link it
640 ; hval <- compileExpr hsc_env iNTERACTIVE
641 (ic_rn_gbl_env new_ic)
645 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
648 hscTcExpr -- Typecheck an expression (but don't run it)
650 -> String -- The expression
653 hscTcExpr hsc_env expr
654 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
655 ; let icontext = hsc_IC hsc_env
656 ; case maybe_stmt of {
657 Nothing -> return Nothing ; -- Parse error
658 Just (Just (L _ (ExprStmt expr _ _)))
659 -> tcRnExpr hsc_env icontext expr ;
660 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
664 hscKcType -- Find the kind of a type
666 -> String -- The type
669 hscKcType hsc_env str
670 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
671 ; let icontext = hsc_IC hsc_env
672 ; case maybe_type of {
673 Just ty -> tcRnType hsc_env icontext ty ;
674 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
676 Nothing -> return Nothing } }
682 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
683 hscParseStmt = hscParseThing parseStmt
685 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
686 hscParseType = hscParseThing parseType
689 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
690 hscParseIdentifier = hscParseThing parseIdentifier
692 hscParseThing :: Outputable thing
694 -> DynFlags -> String
696 -- Nothing => Parse error (message already printed)
698 hscParseThing parser dflags str
699 = showPass dflags "Parser" >>
700 {-# SCC "Parser" #-} do
702 buf <- stringToStringBuffer str
704 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
706 case unP parser (mkPState buf loc dflags) of {
708 PFailed span err -> do { printError span err;
713 --ToDo: can't free the string buffer until we've finished this
714 -- compilation sweep and all the identifiers have gone away.
715 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
720 %************************************************************************
722 Desugar, simplify, convert to bytecode, and link an expression
724 %************************************************************************
728 compileExpr :: HscEnv
729 -> Module -> GlobalRdrEnv -> TypeEnv
733 compileExpr hsc_env this_mod rdr_env type_env tc_expr
734 = do { let { dflags = hsc_dflags hsc_env ;
735 lint_on = dopt Opt_DoCoreLinting dflags }
738 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
741 ; flat_expr <- flattenExpr hsc_env ds_expr
744 ; simpl_expr <- simplifyExpr dflags flat_expr
746 -- Tidy it (temporary, until coreSat does cloning)
747 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
749 -- Prepare for codegen
750 ; prepd_expr <- corePrepExpr dflags tidy_expr
753 -- ToDo: improve SrcLoc
755 case lintUnfolding noSrcLoc [] prepd_expr of
756 Just err -> pprPanic "compileExpr" err
762 ; bcos <- coreExprToBCOs dflags prepd_expr
765 ; hval <- linkExpr hsc_env bcos
773 %************************************************************************
775 Statistics on reading interfaces
777 %************************************************************************
780 dumpIfaceStats :: HscEnv -> IO ()
781 dumpIfaceStats hsc_env
782 = do { eps <- readIORef (hsc_EPS hsc_env)
783 ; dumpIfSet (dump_if_trace || dump_rn_stats)
784 "Interface statistics"
787 dflags = hsc_dflags hsc_env
788 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
789 dump_if_trace = dopt Opt_D_dump_if_trace dflags
792 %************************************************************************
794 Progress Messages: Module i of n
796 %************************************************************************
799 showModuleIndex Nothing = ""
800 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
804 padded = replicate (length n_str - length i_str) ' ' ++ i_str