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 IfaceSyn ( IfaceDecl, IfaceInst )
25 import Module ( Module )
26 import CodeOutput ( outputForeignStubs )
27 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
28 import Linker ( HValue, linkExpr )
29 import CoreTidy ( tidyExpr )
30 import CorePrep ( corePrepExpr )
31 import Flattening ( flattenExpr )
32 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnGetInfo, GetInfoResult, tcRnType )
33 import RdrName ( rdrNameOcc )
34 import OccName ( occNameUserString )
36 import PrelNames ( iNTERACTIVE )
38 import CoreLint ( lintUnfolding )
39 import DsMeta ( templateHaskellNames )
40 import BasicTypes ( Fixity )
41 import SrcLoc ( SrcLoc, noSrcLoc )
42 import VarEnv ( emptyTidyEnv )
46 import Module ( emptyModuleEnv )
47 import RdrName ( GlobalRdrEnv, RdrName )
48 import HsSyn ( HsModule, LHsBinds, HsGroup )
49 import SrcLoc ( Located(..) )
50 import StringBuffer ( hGetStringBuffer, stringToStringBuffer )
52 import Lexer ( P(..), ParseResult(..), mkPState )
53 import SrcLoc ( mkSrcLoc )
54 import TcRnDriver ( tcRnModule, tcRnExtCore )
55 import TcIface ( typecheckIface )
56 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
57 import IfaceEnv ( initNameCache )
58 import LoadIface ( ifaceStats, initExternalPackageState )
59 import PrelInfo ( wiredInThings, basicKnownKeyNames )
60 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
62 import Flattening ( flatten )
64 import TidyPgm ( tidyProgram, mkBootModDetails )
65 import CorePrep ( corePrepPgm )
66 import CoreToStg ( coreToStg )
67 import TyCon ( isDataTyCon )
68 import Name ( Name, NamedThing(..) )
69 import SimplStg ( stg2stg )
70 import CodeGen ( codeGen )
71 import CmmParse ( parseCmmFile )
72 import CodeOutput ( codeOutput )
75 import DriverPhases ( HscSource(..) )
77 import UniqSupply ( mkSplitUniqSupply )
80 import HscStats ( ppSourceStats )
82 import MkExternalCore ( emitExternalCore )
84 import ParserCoreUtils
86 import Maybes ( expectJust )
87 import Bag ( unitBag, emptyBag )
89 import Maybe ( isJust )
91 import DATA_IOREF ( newIORef, readIORef )
95 %************************************************************************
99 %************************************************************************
102 newHscEnv :: DynFlags -> IO HscEnv
104 = do { eps_var <- newIORef initExternalPackageState
105 ; us <- mkSplitUniqSupply 'r'
106 ; nc_var <- newIORef (initNameCache us knownKeyNames)
107 ; fc_var <- newIORef emptyModuleEnv
108 ; return (HscEnv { hsc_dflags = dflags,
111 hsc_IC = emptyInteractiveContext,
112 hsc_HPT = emptyHomePackageTable,
115 hsc_FC = fc_var } ) }
118 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
119 -- where templateHaskellNames are defined
120 knownKeyNames = map getName wiredInThings
121 ++ basicKnownKeyNames
123 ++ templateHaskellNames
128 %************************************************************************
130 The main compiler pipeline
132 %************************************************************************
136 -- Compilation failed
139 -- In IDE mode: we just do the static/dynamic checks
141 (Located (HsModule RdrName)) -- parsed
142 (Maybe (HsGroup Name)) -- renamed
143 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails)) -- typechecked
145 -- Concluded that it wasn't necessary
146 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
147 ModIface -- new iface (if any compilation was done)
150 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
151 ModIface -- new iface (if any compilation was done)
152 Bool -- stub_h exists
153 Bool -- stub_c exists
154 (Maybe CompiledByteCode)
157 -- What to do when we have compiler error or warning messages
158 type MessageAction = Messages -> IO ()
160 -- no errors or warnings; the individual passes
161 -- (parse/rename/typecheck) print messages themselves
165 -> MessageAction -- What to do with errors/warnings
167 -> Bool -- True <=> source unchanged
168 -> Bool -- True <=> have an object file (for msgs only)
169 -> Maybe ModIface -- Old interface, if available
170 -> Maybe (Int, Int) -- Just (i,n) <=> module i of n (for msgs)
173 hscMain hsc_env msg_act mod_summary
174 source_unchanged have_object maybe_old_iface
177 (recomp_reqd, maybe_checked_iface) <-
178 {-# SCC "checkOldIface" #-}
179 checkOldIface hsc_env mod_summary
180 source_unchanged maybe_old_iface;
182 let no_old_iface = not (isJust maybe_checked_iface)
183 what_next | recomp_reqd || no_old_iface = hscRecomp
184 | otherwise = hscNoRecomp
186 ; what_next hsc_env msg_act mod_summary have_object
192 ------------------------------
193 hscNoRecomp hsc_env msg_act mod_summary
194 have_object (Just old_iface)
196 | isOneShot (ghcMode (hsc_dflags hsc_env))
198 compilationProgressMsg (hsc_dflags hsc_env) $
199 "compilation IS NOT required";
200 dumpIfaceStats hsc_env ;
202 let { bomb = panic "hscNoRecomp:OneShot" };
203 return (HscNoRecomp bomb bomb)
206 = do { compilationProgressMsg (hsc_dflags hsc_env) $
207 (showModuleIndex mb_mod_index ++
208 "Skipping " ++ showModMsg have_object mod_summary)
210 ; new_details <- {-# SCC "tcRnIface" #-}
211 initIfaceCheck hsc_env $
212 typecheckIface old_iface ;
213 ; dumpIfaceStats hsc_env
215 ; return (HscNoRecomp new_details old_iface)
218 hscNoRecomp hsc_env msg_act mod_summary
221 = panic "hscNoRecomp" -- hscNoRecomp definitely expects to
222 -- have the old interface available
224 ------------------------------
225 hscRecomp hsc_env msg_act mod_summary
226 have_object maybe_old_iface
228 = case ms_hsc_src mod_summary of
230 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index
231 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
234 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index
235 hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
238 front_res <- hscCoreFrontEnd hsc_env msg_act mod_summary
239 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
241 hscCoreFrontEnd hsc_env msg_act mod_summary = do {
245 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
246 ; case parseCore inp 1 of
247 FailP s -> putMsg s{-ToDo: wrong-} >> return Nothing
248 OkP rdr_module -> do {
251 -- RENAME and TYPECHECK
253 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
254 tcRnExtCore hsc_env rdr_module
256 ; case maybe_tc_result of
257 Nothing -> return Nothing
258 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
262 hscFileFrontEnd hsc_env msg_act mod_summary mb_mod_index = do {
264 -- DISPLAY PROGRESS MESSAGE
266 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
267 ; let dflags = hsc_dflags hsc_env
268 ; let toInterp = hscTarget dflags == HscInterpreted
269 ; when (not one_shot) $
270 compilationProgressMsg dflags $
271 (showModuleIndex mb_mod_index ++
272 "Compiling " ++ showModMsg (not toInterp) mod_summary)
277 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
278 hspp_buf = ms_hspp_buf mod_summary
280 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
282 ; case maybe_parsed of {
283 Left err -> do { msg_act (unitBag err, emptyBag)
285 Right rdr_module -> do {
288 -- RENAME and TYPECHECK
290 (tc_msgs, maybe_tc_result)
291 <- {-# SCC "Typecheck-Rename" #-}
292 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
295 ; case maybe_tc_result of {
296 Nothing -> return Nothing ;
297 Just tc_result -> do {
302 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
303 deSugar hsc_env tc_result
304 ; msg_act (warns, emptyBag)
305 ; return maybe_ds_result
308 ------------------------------
310 hscFileCheck :: HscEnv -> MessageAction -> ModSummary -> IO HscResult
311 hscFileCheck hsc_env msg_act mod_summary = do {
315 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
316 hspp_buf = ms_hspp_buf mod_summary
318 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
320 ; case maybe_parsed of {
321 Left err -> do { msg_act (unitBag err, emptyBag)
323 Right rdr_module -> do {
326 -- RENAME and TYPECHECK
328 (tc_msgs, maybe_tc_result)
329 <- _scc_ "Typecheck-Rename"
330 tcRnModule hsc_env (ms_hsc_src mod_summary)
331 True{-save renamed syntax-}
335 ; case maybe_tc_result of {
336 Nothing -> return (HscChecked rdr_module Nothing Nothing);
338 let md = ModDetails {
339 md_types = tcg_type_env tc_result,
340 md_exports = tcg_exports tc_result,
341 md_insts = tcg_insts tc_result,
342 md_rules = [panic "no rules"] }
343 -- Rules are CoreRules, not the
344 -- RuleDecls we get out of the typechecker
345 return (HscChecked rdr_module
346 (tcg_rn_decls tc_result)
347 (Just (tcg_binds tc_result,
348 tcg_rdr_env tc_result,
352 ------------------------------
353 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
354 -- For hs-boot files, there's no code generation to do
356 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing
358 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
359 = do { details <- mkBootModDetails hsc_env ds_result
361 ; (new_iface, no_change)
362 <- {-# SCC "MkFinalIface" #-}
363 mkIface hsc_env maybe_old_iface ds_result details
365 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
367 -- And the answer is ...
368 ; dumpIfaceStats hsc_env
370 ; return (HscRecomp details new_iface
374 ------------------------------
375 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
377 hscBackEnd hsc_env mod_summary maybe_old_iface Nothing
380 hscBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
382 -- ; seqList imported_modules (return ())
384 let one_shot = isOneShot (ghcMode dflags)
385 dflags = hsc_dflags hsc_env
390 ; flat_result <- {-# SCC "Flattening" #-}
391 flatten hsc_env ds_result
394 {- TEMP: need to review space-leak fixing here
395 NB: even the code generator can force one of the
396 thunks for constructor arguments, for newtypes in particular
398 ; let -- Rule-base accumulated from imported packages
399 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
401 -- In one-shot mode, ZAP the external package state at
402 -- this point, because we aren't going to need it from
403 -- now on. We keep the name cache, however, because
404 -- tidyCore needs it.
406 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
409 ; pkg_rule_base `seq` pcs_middle `seq` return ()
412 -- alive at this point:
420 ; simpl_result <- {-# SCC "Core2Core" #-}
421 core2core hsc_env flat_result
426 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
427 tidyProgram hsc_env simpl_result
429 -- Alive at this point:
430 -- tidy_result, pcs_final
434 -- BUILD THE NEW ModIface and ModDetails
435 -- and emit external core if necessary
436 -- This has to happen *after* code gen so that the back-end
437 -- info has been set. Not yet clear if it matters waiting
438 -- until after code output
439 ; (new_iface, no_change)
440 <- {-# SCC "MkFinalIface" #-}
441 mkIface hsc_env maybe_old_iface simpl_result details
443 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
445 -- Space leak reduction: throw away the new interface if
446 -- we're in one-shot mode; we won't be needing it any
448 ; final_iface <- if one_shot then return (error "no final iface")
449 else return new_iface
451 -- Build the final ModDetails (except in one-shot mode, where
452 -- we won't need this information after compilation).
453 ; final_details <- if one_shot then return (error "no final details")
454 else return $! details
456 -- Emit external core
457 ; emitExternalCore dflags cg_guts
460 -- CONVERT TO STG and COMPLETE CODE GENERATION
461 ; (stub_h_exists, stub_c_exists, maybe_bcos)
462 <- hscCodeGen dflags cg_guts
464 -- And the answer is ...
465 ; dumpIfaceStats hsc_env
467 ; return (HscRecomp final_details
469 stub_h_exists stub_c_exists
476 CgGuts{ -- This is the last use of the ModGuts in a compilation.
477 -- From now on, we just use the bits we need.
478 cg_module = this_mod,
479 cg_binds = core_binds,
481 cg_dir_imps = dir_imps,
482 cg_foreign = foreign_stubs,
483 cg_dep_pkgs = dependencies } = do {
485 let { data_tycons = filter isDataTyCon tycons } ;
486 -- cg_tycons includes newtypes, for the benefit of External Core,
487 -- but we don't generate any code for newtypes
490 -- PREPARE FOR CODE GENERATION
491 -- Do saturation and convert to A-normal form
492 prepd_binds <- {-# SCC "CorePrep" #-}
493 corePrepPgm dflags core_binds data_tycons ;
495 case hscTarget dflags of
496 HscNothing -> return (False, False, Nothing)
500 do ----------------- Generate byte code ------------------
501 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
503 ------------------ Create f-x-dynamic C-side stuff ---
504 (istub_h_exists, istub_c_exists)
505 <- outputForeignStubs dflags foreign_stubs
507 return ( istub_h_exists, istub_c_exists, Just comp_bc )
509 panic "GHC not compiled with interpreter"
514 ----------------- Convert to STG ------------------
515 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
516 myCoreToStg dflags this_mod prepd_binds
518 ------------------ Code generation ------------------
519 abstractC <- {-# SCC "CodeGen" #-}
520 codeGen dflags this_mod data_tycons foreign_stubs
521 dir_imps cost_centre_info stg_binds
523 ------------------ Code output -----------------------
524 (stub_h_exists, stub_c_exists)
525 <- codeOutput dflags this_mod foreign_stubs
526 dependencies abstractC
528 return (stub_h_exists, stub_c_exists, Nothing)
532 hscCmmFile :: DynFlags -> FilePath -> IO Bool
533 hscCmmFile dflags filename = do
534 maybe_cmm <- parseCmmFile dflags filename
536 Nothing -> return False
538 codeOutput dflags no_mod NoStubs [] [cmm]
541 no_mod = panic "hscCmmFile: no_mod"
544 myParseModule dflags src_filename maybe_src_buf
545 = -------------------------- Parser ----------------
546 showPass dflags "Parser" >>
547 {-# SCC "Parser" #-} do
549 -- sometimes we already have the buffer in memory, perhaps
550 -- because we needed to parse the imports out of it, or get the
552 buf <- case maybe_src_buf of
554 Nothing -> hGetStringBuffer src_filename
556 let loc = mkSrcLoc (mkFastString src_filename) 1 0
558 case unP parseModule (mkPState buf loc dflags) of {
560 PFailed span err -> return (Left (mkPlainErrMsg span err));
562 POk _ rdr_module -> do {
564 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
566 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
567 (ppSourceStats False rdr_module) ;
569 return (Right rdr_module)
570 -- ToDo: free the string buffer later.
574 myCoreToStg dflags this_mod prepd_binds
576 stg_binds <- {-# SCC "Core2Stg" #-}
577 coreToStg dflags prepd_binds
579 (stg_binds2, cost_centre_info) <- {-# SCC "Core2Stg" #-}
580 stg2stg dflags this_mod stg_binds
582 return (stg_binds2, cost_centre_info)
586 %************************************************************************
588 \subsection{Compiling a do-statement}
590 %************************************************************************
592 When the UnlinkedBCOExpr is linked you get an HValue of type
594 When you run it you get a list of HValues that should be
595 the same length as the list of names; add them to the ClosureEnv.
597 A naked expression returns a singleton Name [it].
599 What you type The IO [HValue] that hscStmt returns
600 ------------- ------------------------------------
601 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
604 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
607 expr (of IO type) ==> expr >>= \ v -> return [v]
608 [NB: result not printed] bindings: [it]
611 expr (of non-IO type,
612 result showable) ==> let v = expr in print v >> return [v]
615 expr (of non-IO type,
616 result not showable) ==> error
620 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
622 -> String -- The statement
623 -> IO (Maybe (HscEnv, [Name], HValue))
626 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
627 ; case maybe_stmt of {
628 Nothing -> return Nothing ; -- Parse error
629 Just Nothing -> return Nothing ; -- Empty line
630 Just (Just parsed_stmt) -> do { -- The real stuff
632 -- Rename and typecheck it
633 let icontext = hsc_IC hsc_env
634 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
636 ; case maybe_tc_result of {
637 Nothing -> return Nothing ;
638 Just (new_ic, bound_names, tc_expr) -> do {
640 -- Then desugar, code gen, and link it
641 ; hval <- compileExpr hsc_env iNTERACTIVE
642 (ic_rn_gbl_env new_ic)
646 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
649 hscTcExpr -- Typecheck an expression (but don't run it)
651 -> String -- The expression
654 hscTcExpr hsc_env expr
655 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
656 ; let icontext = hsc_IC hsc_env
657 ; case maybe_stmt of {
658 Nothing -> return Nothing ; -- Parse error
659 Just (Just (L _ (ExprStmt expr _ _)))
660 -> tcRnExpr hsc_env icontext expr ;
661 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
665 hscKcType -- Find the kind of a type
667 -> String -- The type
670 hscKcType hsc_env str
671 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
672 ; let icontext = hsc_IC hsc_env
673 ; case maybe_type of {
674 Just ty -> tcRnType hsc_env icontext ty ;
675 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
677 Nothing -> return Nothing } }
683 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
684 hscParseStmt = hscParseThing parseStmt
686 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
687 hscParseType = hscParseThing parseType
690 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
691 hscParseIdentifier = hscParseThing parseIdentifier
693 hscParseThing :: Outputable thing
695 -> DynFlags -> String
697 -- Nothing => Parse error (message already printed)
699 hscParseThing parser dflags str
700 = showPass dflags "Parser" >>
701 {-# SCC "Parser" #-} do
703 buf <- stringToStringBuffer str
705 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
707 case unP parser (mkPState buf loc dflags) of {
709 PFailed span err -> do { printError span err;
714 --ToDo: can't free the string buffer until we've finished this
715 -- compilation sweep and all the identifiers have gone away.
716 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
721 %************************************************************************
723 \subsection{Getting information about an identifer}
725 %************************************************************************
729 hscGetInfo -- like hscStmt, but deals with a single identifier
731 -> String -- The identifier
732 -> IO [GetInfoResult]
734 hscGetInfo hsc_env str
735 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
736 case maybe_rdr_name of {
737 Nothing -> return [];
738 Just (L _ rdr_name) -> do
740 maybe_tc_result <- tcRnGetInfo hsc_env (hsc_IC hsc_env) rdr_name
742 case maybe_tc_result of
744 Just things -> return things
749 %************************************************************************
751 Desugar, simplify, convert to bytecode, and link an expression
753 %************************************************************************
757 compileExpr :: HscEnv
758 -> Module -> GlobalRdrEnv -> TypeEnv
762 compileExpr hsc_env this_mod rdr_env type_env tc_expr
763 = do { let { dflags = hsc_dflags hsc_env ;
764 lint_on = dopt Opt_DoCoreLinting dflags }
767 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
770 ; flat_expr <- flattenExpr hsc_env ds_expr
773 ; simpl_expr <- simplifyExpr dflags flat_expr
775 -- Tidy it (temporary, until coreSat does cloning)
776 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
778 -- Prepare for codegen
779 ; prepd_expr <- corePrepExpr dflags tidy_expr
782 -- ToDo: improve SrcLoc
784 case lintUnfolding noSrcLoc [] prepd_expr of
785 Just err -> pprPanic "compileExpr" err
791 ; bcos <- coreExprToBCOs dflags prepd_expr
794 ; hval <- linkExpr hsc_env bcos
802 %************************************************************************
804 Statistics on reading interfaces
806 %************************************************************************
809 dumpIfaceStats :: HscEnv -> IO ()
810 dumpIfaceStats hsc_env
811 = do { eps <- readIORef (hsc_EPS hsc_env)
812 ; dumpIfSet (dump_if_trace || dump_rn_stats)
813 "Interface statistics"
816 dflags = hsc_dflags hsc_env
817 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
818 dump_if_trace = dopt Opt_D_dump_if_trace dflags
821 %************************************************************************
823 Progress Messages: Module i of n
825 %************************************************************************
828 showModuleIndex Nothing = ""
829 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
833 padded = replicate (length n_str - length i_str) ' ' ++ i_str