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,
15 hscGetInfo, GetInfoResult,
20 #include "HsVersions.h"
23 import HsSyn ( Stmt(..), LHsExpr, LStmt, LHsType )
24 import Module ( Module )
25 import CodeOutput ( outputForeignStubs )
26 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
27 import Linker ( HValue, linkExpr )
28 import CoreTidy ( tidyExpr )
29 import CorePrep ( corePrepExpr )
30 import Flattening ( flattenExpr )
31 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnGetInfo, GetInfoResult, tcRnType )
33 import PrelNames ( iNTERACTIVE )
35 import CoreLint ( lintUnfolding )
36 import DsMeta ( templateHaskellNames )
37 import SrcLoc ( noSrcLoc )
38 import VarEnv ( emptyTidyEnv )
42 import Module ( emptyModuleEnv )
43 import RdrName ( GlobalRdrEnv, RdrName )
44 import HsSyn ( HsModule, LHsBinds, HsGroup )
45 import SrcLoc ( Located(..) )
46 import StringBuffer ( hGetStringBuffer, stringToStringBuffer )
48 import Lexer ( P(..), ParseResult(..), mkPState )
49 import SrcLoc ( mkSrcLoc )
50 import TcRnDriver ( tcRnModule, tcRnExtCore )
51 import TcIface ( typecheckIface )
52 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
53 import IfaceEnv ( initNameCache )
54 import LoadIface ( ifaceStats, initExternalPackageState )
55 import PrelInfo ( wiredInThings, basicKnownKeyNames )
56 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
58 import Flattening ( flatten )
60 import TidyPgm ( tidyProgram, mkBootModDetails )
61 import CorePrep ( corePrepPgm )
62 import CoreToStg ( coreToStg )
63 import TyCon ( isDataTyCon )
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_dep_pkgs = dependencies } = do {
480 let { data_tycons = filter isDataTyCon tycons } ;
481 -- cg_tycons includes newtypes, for the benefit of External Core,
482 -- but we don't generate any code for newtypes
485 -- PREPARE FOR CODE GENERATION
486 -- Do saturation and convert to A-normal form
487 prepd_binds <- {-# SCC "CorePrep" #-}
488 corePrepPgm dflags core_binds data_tycons ;
490 case hscTarget dflags of
491 HscNothing -> return (False, False, Nothing)
495 do ----------------- Generate byte code ------------------
496 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
498 ------------------ Create f-x-dynamic C-side stuff ---
499 (istub_h_exists, istub_c_exists)
500 <- outputForeignStubs dflags foreign_stubs
502 return ( istub_h_exists, istub_c_exists, Just comp_bc )
504 panic "GHC not compiled with interpreter"
509 ----------------- Convert to STG ------------------
510 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
511 myCoreToStg dflags this_mod prepd_binds
513 ------------------ Code generation ------------------
514 abstractC <- {-# SCC "CodeGen" #-}
515 codeGen dflags this_mod data_tycons foreign_stubs
516 dir_imps cost_centre_info stg_binds
518 ------------------ Code output -----------------------
519 (stub_h_exists, stub_c_exists)
520 <- codeOutput dflags this_mod foreign_stubs
521 dependencies abstractC
523 return (stub_h_exists, stub_c_exists, Nothing)
527 hscCmmFile :: DynFlags -> FilePath -> IO Bool
528 hscCmmFile dflags filename = do
529 maybe_cmm <- parseCmmFile dflags filename
531 Nothing -> return False
533 codeOutput dflags no_mod NoStubs [] [cmm]
536 no_mod = panic "hscCmmFile: no_mod"
539 myParseModule dflags src_filename maybe_src_buf
540 = -------------------------- Parser ----------------
541 showPass dflags "Parser" >>
542 {-# SCC "Parser" #-} do
544 -- sometimes we already have the buffer in memory, perhaps
545 -- because we needed to parse the imports out of it, or get the
547 buf <- case maybe_src_buf of
549 Nothing -> hGetStringBuffer src_filename
551 let loc = mkSrcLoc (mkFastString src_filename) 1 0
553 case unP parseModule (mkPState buf loc dflags) of {
555 PFailed span err -> return (Left (mkPlainErrMsg span err));
557 POk _ rdr_module -> do {
559 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
561 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
562 (ppSourceStats False rdr_module) ;
564 return (Right rdr_module)
565 -- ToDo: free the string buffer later.
569 myCoreToStg dflags this_mod prepd_binds
571 stg_binds <- {-# SCC "Core2Stg" #-}
572 coreToStg dflags prepd_binds
574 (stg_binds2, cost_centre_info) <- {-# SCC "Core2Stg" #-}
575 stg2stg dflags this_mod stg_binds
577 return (stg_binds2, cost_centre_info)
581 %************************************************************************
583 \subsection{Compiling a do-statement}
585 %************************************************************************
587 When the UnlinkedBCOExpr is linked you get an HValue of type
589 When you run it you get a list of HValues that should be
590 the same length as the list of names; add them to the ClosureEnv.
592 A naked expression returns a singleton Name [it].
594 What you type The IO [HValue] that hscStmt returns
595 ------------- ------------------------------------
596 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
599 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
602 expr (of IO type) ==> expr >>= \ v -> return [v]
603 [NB: result not printed] bindings: [it]
606 expr (of non-IO type,
607 result showable) ==> let v = expr in print v >> return [v]
610 expr (of non-IO type,
611 result not showable) ==> error
615 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
617 -> String -- The statement
618 -> IO (Maybe (HscEnv, [Name], HValue))
621 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
622 ; case maybe_stmt of {
623 Nothing -> return Nothing ; -- Parse error
624 Just Nothing -> return Nothing ; -- Empty line
625 Just (Just parsed_stmt) -> do { -- The real stuff
627 -- Rename and typecheck it
628 let icontext = hsc_IC hsc_env
629 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
631 ; case maybe_tc_result of {
632 Nothing -> return Nothing ;
633 Just (new_ic, bound_names, tc_expr) -> do {
635 -- Then desugar, code gen, and link it
636 ; hval <- compileExpr hsc_env iNTERACTIVE
637 (ic_rn_gbl_env new_ic)
641 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
644 hscTcExpr -- Typecheck an expression (but don't run it)
646 -> String -- The expression
649 hscTcExpr hsc_env expr
650 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
651 ; let icontext = hsc_IC hsc_env
652 ; case maybe_stmt of {
653 Nothing -> return Nothing ; -- Parse error
654 Just (Just (L _ (ExprStmt expr _ _)))
655 -> tcRnExpr hsc_env icontext expr ;
656 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
660 hscKcType -- Find the kind of a type
662 -> String -- The type
665 hscKcType hsc_env str
666 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
667 ; let icontext = hsc_IC hsc_env
668 ; case maybe_type of {
669 Just ty -> tcRnType hsc_env icontext ty ;
670 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
672 Nothing -> return Nothing } }
678 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
679 hscParseStmt = hscParseThing parseStmt
681 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
682 hscParseType = hscParseThing parseType
685 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
686 hscParseIdentifier = hscParseThing parseIdentifier
688 hscParseThing :: Outputable thing
690 -> DynFlags -> String
692 -- Nothing => Parse error (message already printed)
694 hscParseThing parser dflags str
695 = showPass dflags "Parser" >>
696 {-# SCC "Parser" #-} do
698 buf <- stringToStringBuffer str
700 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
702 case unP parser (mkPState buf loc dflags) of {
704 PFailed span err -> do { printError span err;
709 --ToDo: can't free the string buffer until we've finished this
710 -- compilation sweep and all the identifiers have gone away.
711 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
716 %************************************************************************
718 \subsection{Getting information about an identifer}
720 %************************************************************************
724 hscGetInfo -- like hscStmt, but deals with a single identifier
726 -> String -- The identifier
727 -> IO [GetInfoResult]
729 hscGetInfo hsc_env str
730 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
731 case maybe_rdr_name of {
732 Nothing -> return [];
733 Just (L _ rdr_name) -> do
735 maybe_tc_result <- tcRnGetInfo hsc_env (hsc_IC hsc_env) rdr_name
737 case maybe_tc_result of
739 Just things -> return things
744 %************************************************************************
746 Desugar, simplify, convert to bytecode, and link an expression
748 %************************************************************************
752 compileExpr :: HscEnv
753 -> Module -> GlobalRdrEnv -> TypeEnv
757 compileExpr hsc_env this_mod rdr_env type_env tc_expr
758 = do { let { dflags = hsc_dflags hsc_env ;
759 lint_on = dopt Opt_DoCoreLinting dflags }
762 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
765 ; flat_expr <- flattenExpr hsc_env ds_expr
768 ; simpl_expr <- simplifyExpr dflags flat_expr
770 -- Tidy it (temporary, until coreSat does cloning)
771 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
773 -- Prepare for codegen
774 ; prepd_expr <- corePrepExpr dflags tidy_expr
777 -- ToDo: improve SrcLoc
779 case lintUnfolding noSrcLoc [] prepd_expr of
780 Just err -> pprPanic "compileExpr" err
786 ; bcos <- coreExprToBCOs dflags prepd_expr
789 ; hval <- linkExpr hsc_env bcos
797 %************************************************************************
799 Statistics on reading interfaces
801 %************************************************************************
804 dumpIfaceStats :: HscEnv -> IO ()
805 dumpIfaceStats hsc_env
806 = do { eps <- readIORef (hsc_EPS hsc_env)
807 ; dumpIfSet (dump_if_trace || dump_rn_stats)
808 "Interface statistics"
811 dflags = hsc_dflags hsc_env
812 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
813 dump_if_trace = dopt Opt_D_dump_if_trace dflags
816 %************************************************************************
818 Progress Messages: Module i of n
820 %************************************************************************
823 showModuleIndex Nothing = ""
824 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
828 padded = replicate (length n_str - length i_str) ' ' ++ i_str