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 )
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 (ms_location mod_summary) cg_guts
461 -- And the answer is ...
462 ; dumpIfaceStats hsc_env
464 ; return (HscRecomp final_details
466 stub_h_exists stub_c_exists
472 hscCodeGen dflags location
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 this_mod location 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 location 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 no_loc NoStubs [] [cmm]
540 no_mod = panic "hscCmmFile: no_mod"
541 no_loc = ModLocation{ ml_hs_file = Just filename,
542 ml_hi_file = panic "hscCmmFile: no hi file",
543 ml_obj_file = panic "hscCmmFile: no obj file" }
546 myParseModule dflags src_filename maybe_src_buf
547 = -------------------------- Parser ----------------
548 showPass dflags "Parser" >>
549 {-# SCC "Parser" #-} do
551 -- sometimes we already have the buffer in memory, perhaps
552 -- because we needed to parse the imports out of it, or get the
554 buf <- case maybe_src_buf of
556 Nothing -> hGetStringBuffer src_filename
558 let loc = mkSrcLoc (mkFastString src_filename) 1 0
560 case unP parseModule (mkPState buf loc dflags) of {
562 PFailed span err -> return (Left (mkPlainErrMsg span err));
564 POk _ rdr_module -> do {
566 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
568 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
569 (ppSourceStats False rdr_module) ;
571 return (Right rdr_module)
572 -- ToDo: free the string buffer later.
576 myCoreToStg dflags home_mods this_mod prepd_binds
578 stg_binds <- {-# SCC "Core2Stg" #-}
579 coreToStg home_mods prepd_binds
581 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
582 stg2stg dflags home_mods this_mod stg_binds
584 return (stg_binds2, cost_centre_info)
588 %************************************************************************
590 \subsection{Compiling a do-statement}
592 %************************************************************************
594 When the UnlinkedBCOExpr is linked you get an HValue of type
596 When you run it you get a list of HValues that should be
597 the same length as the list of names; add them to the ClosureEnv.
599 A naked expression returns a singleton Name [it].
601 What you type The IO [HValue] that hscStmt returns
602 ------------- ------------------------------------
603 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
606 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
609 expr (of IO type) ==> expr >>= \ v -> return [v]
610 [NB: result not printed] bindings: [it]
613 expr (of non-IO type,
614 result showable) ==> let v = expr in print v >> return [v]
617 expr (of non-IO type,
618 result not showable) ==> error
622 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
624 -> String -- The statement
625 -> IO (Maybe (HscEnv, [Name], HValue))
628 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
629 ; case maybe_stmt of {
630 Nothing -> return Nothing ; -- Parse error
631 Just Nothing -> return Nothing ; -- Empty line
632 Just (Just parsed_stmt) -> do { -- The real stuff
634 -- Rename and typecheck it
635 let icontext = hsc_IC hsc_env
636 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
638 ; case maybe_tc_result of {
639 Nothing -> return Nothing ;
640 Just (new_ic, bound_names, tc_expr) -> do {
642 -- Then desugar, code gen, and link it
643 ; hval <- compileExpr hsc_env iNTERACTIVE
644 (ic_rn_gbl_env new_ic)
648 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
651 hscTcExpr -- Typecheck an expression (but don't run it)
653 -> String -- The expression
656 hscTcExpr hsc_env expr
657 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
658 ; let icontext = hsc_IC hsc_env
659 ; case maybe_stmt of {
660 Nothing -> return Nothing ; -- Parse error
661 Just (Just (L _ (ExprStmt expr _ _)))
662 -> tcRnExpr hsc_env icontext expr ;
663 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
667 hscKcType -- Find the kind of a type
669 -> String -- The type
672 hscKcType hsc_env str
673 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
674 ; let icontext = hsc_IC hsc_env
675 ; case maybe_type of {
676 Just ty -> tcRnType hsc_env icontext ty ;
677 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
679 Nothing -> return Nothing } }
685 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
686 hscParseStmt = hscParseThing parseStmt
688 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
689 hscParseType = hscParseThing parseType
692 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
693 hscParseIdentifier = hscParseThing parseIdentifier
695 hscParseThing :: Outputable thing
697 -> DynFlags -> String
699 -- Nothing => Parse error (message already printed)
701 hscParseThing parser dflags str
702 = showPass dflags "Parser" >>
703 {-# SCC "Parser" #-} do
705 buf <- stringToStringBuffer str
707 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
709 case unP parser (mkPState buf loc dflags) of {
711 PFailed span err -> do { printError span err;
716 --ToDo: can't free the string buffer until we've finished this
717 -- compilation sweep and all the identifiers have gone away.
718 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
723 %************************************************************************
725 Desugar, simplify, convert to bytecode, and link an expression
727 %************************************************************************
731 compileExpr :: HscEnv
732 -> Module -> GlobalRdrEnv -> TypeEnv
736 compileExpr hsc_env this_mod rdr_env type_env tc_expr
737 = do { let { dflags = hsc_dflags hsc_env ;
738 lint_on = dopt Opt_DoCoreLinting dflags }
741 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
744 ; flat_expr <- flattenExpr hsc_env ds_expr
747 ; simpl_expr <- simplifyExpr dflags flat_expr
749 -- Tidy it (temporary, until coreSat does cloning)
750 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
752 -- Prepare for codegen
753 ; prepd_expr <- corePrepExpr dflags tidy_expr
756 -- ToDo: improve SrcLoc
758 case lintUnfolding noSrcLoc [] prepd_expr of
759 Just err -> pprPanic "compileExpr" err
765 ; bcos <- coreExprToBCOs dflags prepd_expr
768 ; hval <- linkExpr hsc_env bcos
776 %************************************************************************
778 Statistics on reading interfaces
780 %************************************************************************
783 dumpIfaceStats :: HscEnv -> IO ()
784 dumpIfaceStats hsc_env
785 = do { eps <- readIORef (hsc_EPS hsc_env)
786 ; dumpIfSet (dump_if_trace || dump_rn_stats)
787 "Interface statistics"
790 dflags = hsc_dflags hsc_env
791 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
792 dump_if_trace = dopt Opt_D_dump_if_trace dflags
795 %************************************************************************
797 Progress Messages: Module i of n
799 %************************************************************************
802 showModuleIndex Nothing = ""
803 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
807 padded = replicate (length n_str - length i_str) ' ' ++ i_str