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, LIE, LImportDecl )
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 )
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
137 (Located (HsModule RdrName))
139 (Maybe (HsGroup Name,[LImportDecl Name],Maybe [LIE Name]))
141 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
143 -- Concluded that it wasn't necessary
144 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
145 ModIface -- new iface (if any compilation was done)
148 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
149 ModIface -- new iface (if any compilation was done)
150 Bool -- stub_h exists
151 Bool -- stub_c exists
152 (Maybe CompiledByteCode)
155 -- What to do when we have compiler error or warning messages
156 type MessageAction = Messages -> IO ()
158 -- no errors or warnings; the individual passes
159 -- (parse/rename/typecheck) print messages themselves
164 -> Bool -- True <=> source unchanged
165 -> Bool -- True <=> have an object file (for msgs only)
166 -> Maybe ModIface -- Old interface, if available
167 -> Maybe (Int, Int) -- Just (i,n) <=> module i of n (for msgs)
170 hscMain hsc_env mod_summary
171 source_unchanged have_object maybe_old_iface
174 (recomp_reqd, maybe_checked_iface) <-
175 {-# SCC "checkOldIface" #-}
176 checkOldIface hsc_env mod_summary
177 source_unchanged maybe_old_iface;
179 let no_old_iface = not (isJust maybe_checked_iface)
180 what_next | recomp_reqd || no_old_iface = hscRecomp
181 | otherwise = hscNoRecomp
183 ; what_next hsc_env mod_summary have_object
189 ------------------------------
190 hscNoRecomp hsc_env mod_summary
191 have_object (Just old_iface)
193 | isOneShot (ghcMode (hsc_dflags hsc_env))
195 compilationProgressMsg (hsc_dflags hsc_env) $
196 "compilation IS NOT required";
197 dumpIfaceStats hsc_env ;
199 let { bomb = panic "hscNoRecomp:OneShot" };
200 return (HscNoRecomp bomb bomb)
203 = do { compilationProgressMsg (hsc_dflags hsc_env) $
204 (showModuleIndex mb_mod_index ++
205 "Skipping " ++ showModMsg have_object mod_summary)
207 ; new_details <- {-# SCC "tcRnIface" #-}
208 initIfaceCheck hsc_env $
209 typecheckIface old_iface ;
210 ; dumpIfaceStats hsc_env
212 ; return (HscNoRecomp new_details old_iface)
215 hscNoRecomp hsc_env mod_summary
218 = panic "hscNoRecomp" -- hscNoRecomp definitely expects to
219 -- have the old interface available
221 ------------------------------
222 hscRecomp hsc_env mod_summary
223 have_object maybe_old_iface
225 = case ms_hsc_src mod_summary of
227 front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
228 case ghcMode (hsc_dflags hsc_env) of
229 JustTypecheck -> hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
230 _ -> hscBackEnd hsc_env mod_summary maybe_old_iface front_res
233 front_res <- hscFileFrontEnd hsc_env mod_summary mb_mod_index
234 hscBootBackEnd hsc_env mod_summary maybe_old_iface front_res
237 front_res <- hscCoreFrontEnd hsc_env mod_summary
238 hscBackEnd hsc_env mod_summary maybe_old_iface front_res
240 hscCoreFrontEnd hsc_env mod_summary = do {
244 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
245 ; case parseCore inp 1 of
246 FailP s -> errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-}) >> return Nothing
247 OkP rdr_module -> do {
250 -- RENAME and TYPECHECK
252 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
253 tcRnExtCore hsc_env rdr_module
254 ; printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
255 ; case maybe_tc_result of
256 Nothing -> return Nothing
257 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
261 hscFileFrontEnd hsc_env mod_summary mb_mod_index = do {
263 -- DISPLAY PROGRESS MESSAGE
265 ; let dflags = hsc_dflags hsc_env
266 one_shot = isOneShot (ghcMode dflags)
267 toInterp = hscTarget dflags == HscInterpreted
268 ; when (not one_shot) $
269 compilationProgressMsg dflags $
270 (showModuleIndex mb_mod_index ++
271 "Compiling " ++ showModMsg (not toInterp) mod_summary)
276 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
277 hspp_buf = ms_hspp_buf mod_summary
279 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
281 ; case maybe_parsed of {
282 Left err -> do { printBagOfErrors dflags (unitBag err)
284 Right rdr_module -> do {
287 -- RENAME and TYPECHECK
289 (tc_msgs, maybe_tc_result)
290 <- {-# SCC "Typecheck-Rename" #-}
291 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
293 ; printErrorsAndWarnings dflags tc_msgs
294 ; case maybe_tc_result of {
295 Nothing -> return Nothing ;
296 Just tc_result -> do {
301 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
302 deSugar hsc_env tc_result
303 ; printBagOfWarnings dflags warns
304 ; return maybe_ds_result
307 ------------------------------
309 hscFileCheck :: HscEnv -> ModSummary -> IO HscResult
310 hscFileCheck hsc_env mod_summary = do {
314 ; let dflags = hsc_dflags hsc_env
315 hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
316 hspp_buf = ms_hspp_buf mod_summary
318 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
320 ; case maybe_parsed of {
321 Left err -> do { printBagOfErrors dflags (unitBag err)
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-}
334 ; printErrorsAndWarnings dflags tc_msgs
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 rnInfo = do decl <- tcg_rn_decls tc_result
346 imports <- tcg_rn_imports tc_result
347 let exports = tcg_rn_exports tc_result
348 return (decl,imports,exports)
349 return (HscChecked rdr_module
351 (Just (tcg_binds tc_result,
352 tcg_rdr_env tc_result,
356 ------------------------------
357 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
358 -- For hs-boot files, there's no code generation to do
360 hscBootBackEnd hsc_env mod_summary maybe_old_iface Nothing
362 hscBootBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
363 = do { details <- mkBootModDetails hsc_env ds_result
365 ; (new_iface, no_change)
366 <- {-# SCC "MkFinalIface" #-}
367 mkIface hsc_env maybe_old_iface ds_result details
369 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
371 -- And the answer is ...
372 ; dumpIfaceStats hsc_env
374 ; return (HscRecomp details new_iface
378 ------------------------------
379 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
381 hscBackEnd hsc_env mod_summary maybe_old_iface Nothing
384 hscBackEnd hsc_env mod_summary maybe_old_iface (Just ds_result)
386 -- ; seqList imported_modules (return ())
388 let one_shot = isOneShot (ghcMode dflags)
389 dflags = hsc_dflags hsc_env
394 ; flat_result <- {-# SCC "Flattening" #-}
395 flatten hsc_env ds_result
398 {- TEMP: need to review space-leak fixing here
399 NB: even the code generator can force one of the
400 thunks for constructor arguments, for newtypes in particular
402 ; let -- Rule-base accumulated from imported packages
403 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
405 -- In one-shot mode, ZAP the external package state at
406 -- this point, because we aren't going to need it from
407 -- now on. We keep the name cache, however, because
408 -- tidyCore needs it.
410 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
413 ; pkg_rule_base `seq` pcs_middle `seq` return ()
416 -- alive at this point:
424 ; simpl_result <- {-# SCC "Core2Core" #-}
425 core2core hsc_env flat_result
430 ; (cg_guts, details) <- {-# SCC "CoreTidy" #-}
431 tidyProgram hsc_env simpl_result
433 -- Alive at this point:
434 -- tidy_result, pcs_final
438 -- BUILD THE NEW ModIface and ModDetails
439 -- and emit external core if necessary
440 -- This has to happen *after* code gen so that the back-end
441 -- info has been set. Not yet clear if it matters waiting
442 -- until after code output
443 ; (new_iface, no_change)
444 <- {-# SCC "MkFinalIface" #-}
445 mkIface hsc_env maybe_old_iface simpl_result details
447 ; writeIfaceFile hsc_env (ms_location mod_summary) new_iface no_change
449 -- Space leak reduction: throw away the new interface if
450 -- we're in one-shot mode; we won't be needing it any
452 ; final_iface <- if one_shot then return (error "no final iface")
453 else return new_iface
455 -- Build the final ModDetails (except in one-shot mode, where
456 -- we won't need this information after compilation).
457 ; final_details <- if one_shot then return (error "no final details")
458 else return $! details
460 -- Emit external core
461 ; emitExternalCore dflags cg_guts
464 -- CONVERT TO STG and COMPLETE CODE GENERATION
465 ; (stub_h_exists, stub_c_exists, maybe_bcos)
466 <- hscCodeGen dflags (ms_location mod_summary) cg_guts
468 -- And the answer is ...
469 ; dumpIfaceStats hsc_env
471 ; return (HscRecomp final_details
473 stub_h_exists stub_c_exists
479 hscCodeGen dflags location
480 CgGuts{ -- This is the last use of the ModGuts in a compilation.
481 -- From now on, we just use the bits we need.
482 cg_module = this_mod,
483 cg_binds = core_binds,
485 cg_dir_imps = dir_imps,
486 cg_foreign = foreign_stubs,
487 cg_home_mods = home_mods,
488 cg_dep_pkgs = dependencies } = do {
490 let { data_tycons = filter isDataTyCon tycons } ;
491 -- cg_tycons includes newtypes, for the benefit of External Core,
492 -- but we don't generate any code for newtypes
495 -- PREPARE FOR CODE GENERATION
496 -- Do saturation and convert to A-normal form
497 prepd_binds <- {-# SCC "CorePrep" #-}
498 corePrepPgm dflags core_binds data_tycons ;
500 case hscTarget dflags of
501 HscNothing -> return (False, False, Nothing)
505 do ----------------- Generate byte code ------------------
506 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
508 ------------------ Create f-x-dynamic C-side stuff ---
509 (istub_h_exists, istub_c_exists)
510 <- outputForeignStubs dflags this_mod location foreign_stubs
512 return ( istub_h_exists, istub_c_exists, Just comp_bc )
514 panic "GHC not compiled with interpreter"
519 ----------------- Convert to STG ------------------
520 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
521 myCoreToStg dflags home_mods this_mod prepd_binds
523 ------------------ Code generation ------------------
524 abstractC <- {-# SCC "CodeGen" #-}
525 codeGen dflags home_mods this_mod data_tycons
526 foreign_stubs dir_imps cost_centre_info
529 ------------------ Code output -----------------------
530 (stub_h_exists, stub_c_exists)
531 <- codeOutput dflags this_mod location foreign_stubs
532 dependencies abstractC
534 return (stub_h_exists, stub_c_exists, Nothing)
538 hscCmmFile :: DynFlags -> FilePath -> IO Bool
539 hscCmmFile dflags filename = do
540 maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
542 Nothing -> return False
544 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
547 no_mod = panic "hscCmmFile: no_mod"
548 no_loc = ModLocation{ ml_hs_file = Just filename,
549 ml_hi_file = panic "hscCmmFile: no hi file",
550 ml_obj_file = panic "hscCmmFile: no obj file" }
553 myParseModule dflags src_filename maybe_src_buf
554 = -------------------------- Parser ----------------
555 showPass dflags "Parser" >>
556 {-# SCC "Parser" #-} do
558 -- sometimes we already have the buffer in memory, perhaps
559 -- because we needed to parse the imports out of it, or get the
561 buf <- case maybe_src_buf of
563 Nothing -> hGetStringBuffer src_filename
565 let loc = mkSrcLoc (mkFastString src_filename) 1 0
567 case unP parseModule (mkPState buf loc dflags) of {
569 PFailed span err -> return (Left (mkPlainErrMsg span err));
571 POk _ rdr_module -> do {
573 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
575 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
576 (ppSourceStats False rdr_module) ;
578 return (Right rdr_module)
579 -- ToDo: free the string buffer later.
583 myCoreToStg dflags home_mods this_mod prepd_binds
585 stg_binds <- {-# SCC "Core2Stg" #-}
586 coreToStg home_mods prepd_binds
588 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
589 stg2stg dflags home_mods this_mod stg_binds
591 return (stg_binds2, cost_centre_info)
595 %************************************************************************
597 \subsection{Compiling a do-statement}
599 %************************************************************************
601 When the UnlinkedBCOExpr is linked you get an HValue of type
603 When you run it you get a list of HValues that should be
604 the same length as the list of names; add them to the ClosureEnv.
606 A naked expression returns a singleton Name [it].
608 What you type The IO [HValue] that hscStmt returns
609 ------------- ------------------------------------
610 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
613 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
616 expr (of IO type) ==> expr >>= \ v -> return [v]
617 [NB: result not printed] bindings: [it]
620 expr (of non-IO type,
621 result showable) ==> let v = expr in print v >> return [v]
624 expr (of non-IO type,
625 result not showable) ==> error
629 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
631 -> String -- The statement
632 -> IO (Maybe (HscEnv, [Name], HValue))
635 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
636 ; case maybe_stmt of {
637 Nothing -> return Nothing ; -- Parse error
638 Just Nothing -> return Nothing ; -- Empty line
639 Just (Just parsed_stmt) -> do { -- The real stuff
641 -- Rename and typecheck it
642 let icontext = hsc_IC hsc_env
643 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
645 ; case maybe_tc_result of {
646 Nothing -> return Nothing ;
647 Just (new_ic, bound_names, tc_expr) -> do {
649 -- Then desugar, code gen, and link it
650 ; hval <- compileExpr hsc_env iNTERACTIVE
651 (ic_rn_gbl_env new_ic)
655 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
658 hscTcExpr -- Typecheck an expression (but don't run it)
660 -> String -- The expression
663 hscTcExpr hsc_env expr
664 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
665 ; let icontext = hsc_IC hsc_env
666 ; case maybe_stmt of {
667 Nothing -> return Nothing ; -- Parse error
668 Just (Just (L _ (ExprStmt expr _ _)))
669 -> tcRnExpr hsc_env icontext expr ;
670 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
674 hscKcType -- Find the kind of a type
676 -> String -- The type
679 hscKcType hsc_env str
680 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
681 ; let icontext = hsc_IC hsc_env
682 ; case maybe_type of {
683 Just ty -> tcRnType hsc_env icontext ty ;
684 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
686 Nothing -> return Nothing } }
692 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
693 hscParseStmt = hscParseThing parseStmt
695 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
696 hscParseType = hscParseThing parseType
699 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
700 hscParseIdentifier = hscParseThing parseIdentifier
702 hscParseThing :: Outputable thing
704 -> DynFlags -> String
706 -- Nothing => Parse error (message already printed)
708 hscParseThing parser dflags str
709 = showPass dflags "Parser" >>
710 {-# SCC "Parser" #-} do
712 buf <- stringToStringBuffer str
714 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
716 case unP parser (mkPState buf loc dflags) of {
718 PFailed span err -> do { printError span err;
723 --ToDo: can't free the string buffer until we've finished this
724 -- compilation sweep and all the identifiers have gone away.
725 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
730 %************************************************************************
732 Desugar, simplify, convert to bytecode, and link an expression
734 %************************************************************************
738 compileExpr :: HscEnv
739 -> Module -> GlobalRdrEnv -> TypeEnv
743 compileExpr hsc_env this_mod rdr_env type_env tc_expr
744 = do { let { dflags = hsc_dflags hsc_env ;
745 lint_on = dopt Opt_DoCoreLinting dflags }
748 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
751 ; flat_expr <- flattenExpr hsc_env ds_expr
754 ; simpl_expr <- simplifyExpr dflags flat_expr
756 -- Tidy it (temporary, until coreSat does cloning)
757 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
759 -- Prepare for codegen
760 ; prepd_expr <- corePrepExpr dflags tidy_expr
763 -- ToDo: improve SrcLoc
765 case lintUnfolding noSrcLoc [] prepd_expr of
766 Just err -> pprPanic "compileExpr" err
772 ; bcos <- coreExprToBCOs dflags prepd_expr
775 ; hval <- linkExpr hsc_env bcos
783 %************************************************************************
785 Statistics on reading interfaces
787 %************************************************************************
790 dumpIfaceStats :: HscEnv -> IO ()
791 dumpIfaceStats hsc_env
792 = do { eps <- readIORef (hsc_EPS hsc_env)
793 ; dumpIfSet (dump_if_trace || dump_rn_stats)
794 "Interface statistics"
797 dflags = hsc_dflags hsc_env
798 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
799 dump_if_trace = dopt Opt_D_dump_if_trace dflags
802 %************************************************************************
804 Progress Messages: Module i of n
806 %************************************************************************
809 showModuleIndex Nothing = ""
810 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
814 padded = replicate (length n_str - length i_str) ' ' ++ i_str