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
160 -> MessageAction -- What to do with errors/warnings
162 -> Bool -- True <=> source unchanged
163 -> Bool -- True <=> have an object file (for msgs only)
164 -> Maybe ModIface -- Old interface, if available
165 -> Maybe (Int, Int) -- Just (i,n) <=> module i of n (for msgs)
168 hscMain hsc_env msg_act mod_summary
169 source_unchanged have_object maybe_old_iface
172 (recomp_reqd, maybe_checked_iface) <-
173 {-# SCC "checkOldIface" #-}
174 checkOldIface hsc_env mod_summary
175 source_unchanged maybe_old_iface;
177 let no_old_iface = not (isJust maybe_checked_iface)
178 what_next | recomp_reqd || no_old_iface = hscRecomp
179 | otherwise = hscNoRecomp
181 ; what_next hsc_env msg_act mod_summary have_object
187 ------------------------------
188 hscNoRecomp hsc_env msg_act mod_summary
189 have_object (Just old_iface)
191 | isOneShot (ghcMode (hsc_dflags hsc_env))
193 compilationProgressMsg (hsc_dflags hsc_env) $
194 "compilation IS NOT required";
195 dumpIfaceStats hsc_env ;
197 let { bomb = panic "hscNoRecomp:OneShot" };
198 return (HscNoRecomp bomb bomb)
201 = do { compilationProgressMsg (hsc_dflags hsc_env) $
202 (showModuleIndex mb_mod_index ++
203 "Skipping " ++ showModMsg have_object mod_summary)
205 ; new_details <- {-# SCC "tcRnIface" #-}
206 initIfaceCheck hsc_env $
207 typecheckIface old_iface ;
208 ; dumpIfaceStats hsc_env
210 ; return (HscNoRecomp new_details old_iface)
213 hscNoRecomp hsc_env msg_act mod_summary
216 = panic "hscNoRecomp" -- hscNoRecomp definitely expects to
217 -- have the old interface available
219 ------------------------------
220 hscRecomp hsc_env msg_act mod_summary
221 have_object maybe_old_iface
223 = case ms_hsc_src mod_summary of
225 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index
226 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
229 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index
230 hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
233 front_res <- hscCoreFrontEnd hsc_env msg_act mod_summary
234 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
236 hscCoreFrontEnd hsc_env msg_act mod_summary = do {
240 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
241 ; case parseCore inp 1 of
242 FailP s -> putMsg s{-ToDo: wrong-} >> return Nothing
243 OkP rdr_module -> do {
246 -- RENAME and TYPECHECK
248 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
249 tcRnExtCore hsc_env rdr_module
251 ; case maybe_tc_result of
252 Nothing -> return Nothing
253 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
257 hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index = do {
259 -- DISPLAY PROGRESS MESSAGE
261 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
262 ; let dflags = hsc_dflags hsc_env
263 ; let toInterp = hscTarget dflags == HscInterpreted
264 ; when (not one_shot) $
265 compilationProgressMsg dflags $
266 (showModuleIndex mb_mod_index ++
267 "Compiling " ++ showModMsg (not toInterp) mod_summary)
272 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
273 hspp_buf = ms_hspp_buf mod_summary
275 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
277 ; case maybe_parsed of {
278 Left err -> do { msg_act (unitBag err, emptyBag)
280 Right rdr_module -> do {
283 -- RENAME and TYPECHECK
285 (tc_msgs, maybe_tc_result)
286 <- {-# SCC "Typecheck-Rename" #-}
287 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
290 ; case maybe_tc_result of {
291 Nothing -> return Nothing ;
292 Just tc_result -> do {
297 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
298 deSugar hsc_env tc_result
299 ; msg_act (warns, emptyBag)
300 ; return maybe_ds_result
303 ------------------------------
305 hscFileCheck :: HscEnv -> MessageAction -> ModSummary -> IO HscResult
306 hscFileCheck hsc_env msg_act mod_summary = do {
310 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
311 hspp_buf = ms_hspp_buf mod_summary
313 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
315 ; case maybe_parsed of {
316 Left err -> do { msg_act (unitBag err, emptyBag)
318 Right rdr_module -> do {
321 -- RENAME and TYPECHECK
323 (tc_msgs, maybe_tc_result)
324 <- _scc_ "Typecheck-Rename"
325 tcRnModule hsc_env (ms_hsc_src mod_summary)
326 True{-save renamed syntax-}
330 ; case maybe_tc_result of {
331 Nothing -> return (HscChecked rdr_module Nothing Nothing);
333 let md = ModDetails {
334 md_types = tcg_type_env tc_result,
335 md_exports = tcg_exports tc_result,
336 md_insts = tcg_insts tc_result,
337 md_rules = [panic "no rules"] }
338 -- Rules are CoreRules, not the
339 -- RuleDecls we get out of the typechecker
340 return (HscChecked rdr_module
341 (tcg_rn_decls tc_result)
342 (Just (tcg_binds tc_result,
343 tcg_rdr_env tc_result,
347 ------------------------------
348 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
349 -- For hs-boot files, there's no code generation to do
351 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing
353 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
354 = do { details <- mkBootModDetails hsc_env ds_result
356 ; (new_iface, no_change)
357 <- {-# SCC "MkFinalIface" #-}
358 mkIface hsc_env maybe_old_iface ds_result details
360 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
362 -- And the answer is ...
363 ; dumpIfaceStats hsc_env
365 ; return (HscRecomp details new_iface
369 ------------------------------
370 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
372 hscBackEnd hsc_env mod_summary maybe_old_iface Nothing
375 hscBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
377 -- ; seqList imported_modules (return ())
379 let one_shot = isOneShot (ghcMode dflags)
380 dflags = hsc_dflags hsc_env
385 ; flat_result <- {-# SCC "Flattening" #-}
386 flatten hsc_env ds_result
389 {- TEMP: need to review space-leak fixing here
390 NB: even the code generator can force one of the
391 thunks for constructor arguments, for newtypes in particular
393 ; let -- Rule-base accumulated from imported packages
394 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
396 -- In one-shot mode, ZAP the external package state at
397 -- this point, because we aren't going to need it from
398 -- now on. We keep the name cache, however, because
399 -- tidyCore needs it.
401 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
404 ; pkg_rule_base `seq` pcs_middle `seq` return ()
407 -- alive at this point:
415 ; simpl_result <- {-# SCC "Core2Core" #-}
416 core2core hsc_env flat_result
421 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
422 tidyProgram hsc_env simpl_result
424 -- Alive at this point:
425 -- tidy_result, pcs_final
429 -- BUILD THE NEW ModIface and ModDetails
430 -- and emit external core if necessary
431 -- This has to happen *after* code gen so that the back-end
432 -- info has been set. Not yet clear if it matters waiting
433 -- until after code output
434 ; (new_iface, no_change)
435 <- {-# SCC "MkFinalIface" #-}
436 mkIface hsc_env maybe_old_iface simpl_result details
438 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
440 -- Space leak reduction: throw away the new interface if
441 -- we're in one-shot mode; we won't be needing it any
443 ; final_iface <- if one_shot then return (error "no final iface")
444 else return new_iface
446 -- Build the final ModDetails (except in one-shot mode, where
447 -- we won't need this information after compilation).
448 ; final_details <- if one_shot then return (error "no final details")
449 else return $! details
451 -- Emit external core
452 ; emitExternalCore dflags cg_guts
455 -- CONVERT TO STG and COMPLETE CODE GENERATION
456 ; (stub_h_exists, stub_c_exists, maybe_bcos)
457 <- hscCodeGen dflags cg_guts
459 -- And the answer is ...
460 ; dumpIfaceStats hsc_env
462 ; return (HscRecomp final_details
464 stub_h_exists stub_c_exists
471 CgGuts{ -- This is the last use of the ModGuts in a compilation.
472 -- From now on, we just use the bits we need.
473 cg_module = this_mod,
474 cg_binds = core_binds,
476 cg_dir_imps = dir_imps,
477 cg_foreign = foreign_stubs,
478 cg_home_mods = home_mods,
479 cg_dep_pkgs = dependencies } = do {
481 let { data_tycons = filter isDataTyCon tycons } ;
482 -- cg_tycons includes newtypes, for the benefit of External Core,
483 -- but we don't generate any code for newtypes
486 -- PREPARE FOR CODE GENERATION
487 -- Do saturation and convert to A-normal form
488 prepd_binds <- {-# SCC "CorePrep" #-}
489 corePrepPgm dflags core_binds data_tycons ;
491 case hscTarget dflags of
492 HscNothing -> return (False, False, Nothing)
496 do ----------------- Generate byte code ------------------
497 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
499 ------------------ Create f-x-dynamic C-side stuff ---
500 (istub_h_exists, istub_c_exists)
501 <- outputForeignStubs dflags foreign_stubs
503 return ( istub_h_exists, istub_c_exists, Just comp_bc )
505 panic "GHC not compiled with interpreter"
510 ----------------- Convert to STG ------------------
511 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
512 myCoreToStg dflags home_mods this_mod prepd_binds
514 ------------------ Code generation ------------------
515 abstractC <- {-# SCC "CodeGen" #-}
516 codeGen dflags home_mods this_mod data_tycons
517 foreign_stubs dir_imps cost_centre_info
520 ------------------ Code output -----------------------
521 (stub_h_exists, stub_c_exists)
522 <- codeOutput dflags this_mod foreign_stubs
523 dependencies abstractC
525 return (stub_h_exists, stub_c_exists, Nothing)
529 hscCmmFile :: DynFlags -> FilePath -> IO Bool
530 hscCmmFile dflags filename = do
531 maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
533 Nothing -> return False
535 codeOutput dflags no_mod NoStubs [] [cmm]
538 no_mod = panic "hscCmmFile: no_mod"
541 myParseModule dflags src_filename maybe_src_buf
542 = -------------------------- Parser ----------------
543 showPass dflags "Parser" >>
544 {-# SCC "Parser" #-} do
546 -- sometimes we already have the buffer in memory, perhaps
547 -- because we needed to parse the imports out of it, or get the
549 buf <- case maybe_src_buf of
551 Nothing -> hGetStringBuffer src_filename
553 let loc = mkSrcLoc (mkFastString src_filename) 1 0
555 case unP parseModule (mkPState buf loc dflags) of {
557 PFailed span err -> return (Left (mkPlainErrMsg span err));
559 POk _ rdr_module -> do {
561 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
563 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
564 (ppSourceStats False rdr_module) ;
566 return (Right rdr_module)
567 -- ToDo: free the string buffer later.
571 myCoreToStg dflags home_mods this_mod prepd_binds
573 stg_binds <- {-# SCC "Core2Stg" #-}
574 coreToStg home_mods prepd_binds
576 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
577 stg2stg dflags home_mods this_mod stg_binds
579 return (stg_binds2, cost_centre_info)
583 %************************************************************************
585 \subsection{Compiling a do-statement}
587 %************************************************************************
589 When the UnlinkedBCOExpr is linked you get an HValue of type
591 When you run it you get a list of HValues that should be
592 the same length as the list of names; add them to the ClosureEnv.
594 A naked expression returns a singleton Name [it].
596 What you type The IO [HValue] that hscStmt returns
597 ------------- ------------------------------------
598 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
601 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
604 expr (of IO type) ==> expr >>= \ v -> return [v]
605 [NB: result not printed] bindings: [it]
608 expr (of non-IO type,
609 result showable) ==> let v = expr in print v >> return [v]
612 expr (of non-IO type,
613 result not showable) ==> error
617 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
619 -> String -- The statement
620 -> IO (Maybe (HscEnv, [Name], HValue))
623 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
624 ; case maybe_stmt of {
625 Nothing -> return Nothing ; -- Parse error
626 Just Nothing -> return Nothing ; -- Empty line
627 Just (Just parsed_stmt) -> do { -- The real stuff
629 -- Rename and typecheck it
630 let icontext = hsc_IC hsc_env
631 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
633 ; case maybe_tc_result of {
634 Nothing -> return Nothing ;
635 Just (new_ic, bound_names, tc_expr) -> do {
637 -- Then desugar, code gen, and link it
638 ; hval <- compileExpr hsc_env iNTERACTIVE
639 (ic_rn_gbl_env new_ic)
643 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
646 hscTcExpr -- Typecheck an expression (but don't run it)
648 -> String -- The expression
651 hscTcExpr hsc_env expr
652 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
653 ; let icontext = hsc_IC hsc_env
654 ; case maybe_stmt of {
655 Nothing -> return Nothing ; -- Parse error
656 Just (Just (L _ (ExprStmt expr _ _)))
657 -> tcRnExpr hsc_env icontext expr ;
658 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
662 hscKcType -- Find the kind of a type
664 -> String -- The type
667 hscKcType hsc_env str
668 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
669 ; let icontext = hsc_IC hsc_env
670 ; case maybe_type of {
671 Just ty -> tcRnType hsc_env icontext ty ;
672 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
674 Nothing -> return Nothing } }
680 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
681 hscParseStmt = hscParseThing parseStmt
683 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
684 hscParseType = hscParseThing parseType
687 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
688 hscParseIdentifier = hscParseThing parseIdentifier
690 hscParseThing :: Outputable thing
692 -> DynFlags -> String
694 -- Nothing => Parse error (message already printed)
696 hscParseThing parser dflags str
697 = showPass dflags "Parser" >>
698 {-# SCC "Parser" #-} do
700 buf <- stringToStringBuffer str
702 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
704 case unP parser (mkPState buf loc dflags) of {
706 PFailed span err -> do { printError span err;
711 --ToDo: can't free the string buffer until we've finished this
712 -- compilation sweep and all the identifiers have gone away.
713 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
718 %************************************************************************
720 Desugar, simplify, convert to bytecode, and link an expression
722 %************************************************************************
726 compileExpr :: HscEnv
727 -> Module -> GlobalRdrEnv -> TypeEnv
731 compileExpr hsc_env this_mod rdr_env type_env tc_expr
732 = do { let { dflags = hsc_dflags hsc_env ;
733 lint_on = dopt Opt_DoCoreLinting dflags }
736 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
739 ; flat_expr <- flattenExpr hsc_env ds_expr
742 ; simpl_expr <- simplifyExpr dflags flat_expr
744 -- Tidy it (temporary, until coreSat does cloning)
745 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
747 -- Prepare for codegen
748 ; prepd_expr <- corePrepExpr dflags tidy_expr
751 -- ToDo: improve SrcLoc
753 case lintUnfolding noSrcLoc [] prepd_expr of
754 Just err -> pprPanic "compileExpr" err
760 ; bcos <- coreExprToBCOs dflags prepd_expr
763 ; hval <- linkExpr hsc_env bcos
771 %************************************************************************
773 Statistics on reading interfaces
775 %************************************************************************
778 dumpIfaceStats :: HscEnv -> IO ()
779 dumpIfaceStats hsc_env
780 = do { eps <- readIORef (hsc_EPS hsc_env)
781 ; dumpIfSet (dump_if_trace || dump_rn_stats)
782 "Interface statistics"
785 dflags = hsc_dflags hsc_env
786 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
787 dump_if_trace = dopt Opt_D_dump_if_trace dflags
790 %************************************************************************
792 Progress Messages: Module i of n
794 %************************************************************************
797 showModuleIndex Nothing = ""
798 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
802 padded = replicate (length n_str - length i_str) ' ' ++ i_str