2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 HscResult(..), hscMain, initPersistentCompilerState
11 , hscStmt, hscTcExpr, hscThing,
16 #include "HsVersions.h"
19 import TcHsSyn ( TypecheckedHsExpr )
20 import CodeOutput ( outputForeignStubs )
21 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
22 import Linker ( HValue, linkExpr )
23 import TidyPgm ( tidyCoreExpr )
24 import CorePrep ( corePrepExpr )
25 import Flattening ( flattenExpr )
26 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnThing )
27 import RdrHsSyn ( RdrNameStmt )
29 import PrelNames ( iNTERACTIVE )
30 import StringBuffer ( stringToStringBuffer )
31 import SrcLoc ( noSrcLoc )
33 import CoreLint ( lintUnfolding )
38 import RdrName ( nameRdrName )
39 import StringBuffer ( hGetStringBuffer )
41 import Lexer ( P(..), ParseResult(..), mkPState, showPFailed )
42 import SrcLoc ( mkSrcLoc )
43 import TcRnDriver ( checkOldIface, tcRnModule, tcRnExtCore, tcRnIface )
44 import RnEnv ( extendOrigNameCache )
45 import PrelInfo ( wiredInThingEnv, knownKeyNames )
46 import PrelRules ( builtinRules )
47 import MkIface ( mkIface )
49 import Flattening ( flatten )
51 import TidyPgm ( tidyCorePgm )
52 import CorePrep ( corePrepPgm )
53 import CoreToStg ( coreToStg )
54 import SimplStg ( stg2stg )
55 import CodeGen ( codeGen )
56 import CodeOutput ( codeOutput )
58 import Module ( emptyModuleEnv )
60 import DriverPhases ( isExtCore_file )
61 import ErrUtils ( dumpIfSet_dyn, showPass )
62 import UniqSupply ( mkSplitUniqSupply )
64 import Bag ( consBag, emptyBag )
66 import HscStats ( ppSourceStats )
68 import MkExternalCore ( emitExternalCore )
70 import ParserCoreUtils
71 import FiniteMap ( emptyFM )
72 import Name ( nameModule )
73 import Module ( Module, ModLocation(..), showModMsg )
75 import Maybes ( expectJust )
78 import Maybe ( isJust, fromJust )
83 %************************************************************************
85 \subsection{The main compiler pipeline}
87 %************************************************************************
92 = HscFail PersistentCompilerState -- updated PCS
93 -- concluded that it wasn't necessary
94 | HscNoRecomp PersistentCompilerState -- updated PCS
95 ModDetails -- new details (HomeSymbolTable additions)
96 ModIface -- new iface (if any compilation was done)
98 | HscRecomp PersistentCompilerState -- updated PCS
99 ModDetails -- new details (HomeSymbolTable additions)
100 ModIface -- new iface (if any compilation was done)
101 Bool -- stub_h exists
102 Bool -- stub_c exists
103 (Maybe CompiledByteCode)
105 -- no errors or warnings; the individual passes
106 -- (parse/rename/typecheck) print messages themselves
110 -> PersistentCompilerState -- IN: persistent compiler state
112 -> ModLocation -- location info
113 -> Bool -- True <=> source unchanged
114 -> Bool -- True <=> have an object file (for msgs only)
115 -> Maybe ModIface -- old interface, if available
118 hscMain hsc_env pcs mod location
119 source_unchanged have_object maybe_old_iface
121 (pcs_ch, maybe_chk_result) <- _scc_ "checkOldIface"
122 checkOldIface hsc_env pcs mod
123 (ml_hi_file location)
124 source_unchanged maybe_old_iface;
125 case maybe_chk_result of {
126 Nothing -> return (HscFail pcs_ch) ;
127 Just (recomp_reqd, maybe_checked_iface) -> do {
129 let no_old_iface = not (isJust maybe_checked_iface)
130 what_next | recomp_reqd || no_old_iface = hscRecomp
131 | otherwise = hscNoRecomp
133 ; what_next hsc_env pcs_ch have_object
134 mod location maybe_checked_iface
138 -- hscNoRecomp definitely expects to have the old interface available
139 hscNoRecomp hsc_env pcs_ch have_object
140 mod location (Just old_iface)
141 | hsc_mode hsc_env == OneShot
143 when (verbosity (hsc_dflags hsc_env) > 0) $
144 hPutStrLn stderr "compilation IS NOT required";
145 let { bomb = panic "hscNoRecomp:OneShot" };
146 return (HscNoRecomp pcs_ch bomb bomb)
150 when (verbosity (hsc_dflags hsc_env) >= 1) $
151 hPutStrLn stderr ("Skipping " ++
152 showModMsg have_object mod location);
155 (pcs_tc, maybe_tc_result) <- _scc_ "tcRnIface"
156 tcRnIface hsc_env pcs_ch old_iface ;
158 case maybe_tc_result of {
159 Nothing -> return (HscFail pcs_tc);
162 return (HscNoRecomp pcs_tc new_details old_iface)
165 hscRecomp hsc_env pcs_ch have_object
166 mod location maybe_checked_iface
168 -- what target are we shooting for?
169 ; let one_shot = hsc_mode hsc_env == OneShot
170 ; let dflags = hsc_dflags hsc_env
171 ; let toInterp = dopt_HscLang dflags == HscInterpreted
172 ; let toCore = isJust (ml_hs_file location) &&
173 isExtCore_file (fromJust (ml_hs_file location))
175 ; when (not one_shot && verbosity dflags >= 1) $
176 hPutStrLn stderr ("Compiling " ++
177 showModMsg (not toInterp) mod location);
179 ; front_res <- if toCore then
180 hscCoreFrontEnd hsc_env pcs_ch location
182 hscFrontEnd hsc_env pcs_ch location
185 Left flure -> return flure;
186 Right (pcs_tc, ds_result) -> do {
190 -- ; seqList imported_modules (return ())
195 ; flat_result <- _scc_ "Flattening"
196 flatten hsc_env pcs_tc ds_result
199 ; let -- Rule-base accumulated from imported packages
200 pkg_rule_base = eps_rule_base (pcs_EPS pcs_tc)
202 -- In one-shot mode, ZAP the external package state at
203 -- this point, because we aren't going to need it from
204 -- now on. We keep the name cache, however, because
205 -- tidyCore needs it.
207 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
210 ; pkg_rule_base `seq` pcs_middle `seq` return ()
212 -- alive at this point:
220 ; simpl_result <- _scc_ "Core2Core"
221 core2core hsc_env pkg_rule_base flat_result
226 ; (pcs_simpl, tidy_result)
228 tidyCorePgm dflags pcs_middle simpl_result
230 -- ZAP the persistent compiler state altogether now if we're
231 -- in one-shot mode, to save space.
232 ; pcs_final <- if one_shot then return (error "pcs_final missing")
233 else return pcs_simpl
235 ; emitExternalCore dflags tidy_result
237 -- Alive at this point:
238 -- tidy_result, pcs_final
242 -- BUILD THE NEW ModIface and ModDetails
243 -- and emit external core if necessary
244 -- This has to happen *after* code gen so that the back-end
245 -- info has been set. Not yet clear if it matters waiting
246 -- until after code output
247 ; new_iface <- _scc_ "MkFinalIface"
248 mkIface hsc_env location
249 maybe_checked_iface tidy_result
252 -- Space leak reduction: throw away the new interface if
253 -- we're in one-shot mode; we won't be needing it any
256 if one_shot then return (error "no final iface")
257 else return new_iface
259 -- Build the final ModDetails (except in one-shot mode, where
260 -- we won't need this information after compilation).
262 if one_shot then return (error "no final details")
263 else return $! ModDetails {
264 md_types = mg_types tidy_result,
265 md_insts = mg_insts tidy_result,
266 md_rules = mg_rules tidy_result }
269 -- CONVERT TO STG and COMPLETE CODE GENERATION
270 ; (stub_h_exists, stub_c_exists, maybe_bcos)
271 <- hscBackEnd dflags tidy_result
273 -- and the answer is ...
274 ; return (HscRecomp pcs_final
277 stub_h_exists stub_c_exists
281 hscCoreFrontEnd hsc_env pcs_ch location = do {
285 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
286 ; case parseCore inp 1 of
287 FailP s -> hPutStrLn stderr s >> return (Left (HscFail pcs_ch));
288 OkP rdr_module -> do {
291 -- RENAME and TYPECHECK
293 ; (pcs_tc, maybe_tc_result) <- _scc_ "TypeCheck"
294 tcRnExtCore hsc_env pcs_ch rdr_module
295 ; case maybe_tc_result of {
296 Nothing -> return (Left (HscFail pcs_tc));
297 Just mod_guts -> return (Right (pcs_tc, mod_guts))
298 -- No desugaring to do!
302 hscFrontEnd hsc_env pcs_ch location = do {
306 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
307 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
309 ; case maybe_parsed of {
310 Nothing -> return (Left (HscFail pcs_ch));
311 Just rdr_module -> do {
314 -- RENAME and TYPECHECK
316 ; (pcs_tc, maybe_tc_result) <- _scc_ "Typecheck-Rename"
317 tcRnModule hsc_env pcs_ch rdr_module
318 ; case maybe_tc_result of {
319 Nothing -> return (Left (HscFail pcs_ch));
320 Just tc_result -> do {
325 ; maybe_ds_result <- _scc_ "DeSugar"
326 deSugar hsc_env pcs_tc tc_result
327 ; case maybe_ds_result of
328 Nothing -> return (Left (HscFail pcs_ch));
329 Just ds_result -> return (Right (pcs_tc, ds_result));
334 ModGuts{ -- This is the last use of the ModGuts in a compilation.
335 -- From now on, we just use the bits we need.
336 mg_module = this_mod,
337 mg_binds = core_binds,
339 mg_dir_imps = dir_imps,
340 mg_foreign = foreign_stubs,
341 mg_deps = dependencies } = do {
344 -- PREPARE FOR CODE GENERATION
345 -- Do saturation and convert to A-normal form
346 prepd_binds <- _scc_ "CorePrep"
347 corePrepPgm dflags core_binds type_env;
349 case dopt_HscLang dflags of
350 HscNothing -> return (False, False, Nothing)
354 do ----------------- Generate byte code ------------------
355 comp_bc <- byteCodeGen dflags prepd_binds type_env
357 ------------------ Create f-x-dynamic C-side stuff ---
358 (istub_h_exists, istub_c_exists)
359 <- outputForeignStubs dflags foreign_stubs
361 return ( istub_h_exists, istub_c_exists, Just comp_bc )
363 panic "GHC not compiled with interpreter"
368 ----------------- Convert to STG ------------------
369 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
370 myCoreToStg dflags this_mod prepd_binds
372 ------------------ Code generation ------------------
373 abstractC <- _scc_ "CodeGen"
374 codeGen dflags this_mod type_env foreign_stubs
375 dir_imps cost_centre_info stg_binds
377 ------------------ Code output -----------------------
378 (stub_h_exists, stub_c_exists)
379 <- codeOutput dflags this_mod foreign_stubs
380 dependencies abstractC
382 return (stub_h_exists, stub_c_exists, Nothing)
386 myParseModule dflags src_filename
387 = do -------------------------- Parser ----------------
388 showPass dflags "Parser"
390 buf <- hGetStringBuffer src_filename
392 let loc = mkSrcLoc (mkFastString src_filename) 1 0
394 case unP parseModule (mkPState buf loc dflags) of {
396 PFailed l1 l2 err -> do { hPutStrLn stderr (showPFailed l1 l2 err);
399 POk _ rdr_module -> do {
401 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
403 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
404 (ppSourceStats False rdr_module) ;
406 return (Just rdr_module)
407 -- ToDo: free the string buffer later.
411 myCoreToStg dflags this_mod prepd_binds
413 stg_binds <- _scc_ "Core2Stg"
414 coreToStg dflags prepd_binds
416 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
417 stg2stg dflags this_mod stg_binds
419 return (stg_binds2, cost_centre_info)
423 %************************************************************************
425 \subsection{Compiling a do-statement}
427 %************************************************************************
429 When the UnlinkedBCOExpr is linked you get an HValue of type
431 When you run it you get a list of HValues that should be
432 the same length as the list of names; add them to the ClosureEnv.
434 A naked expression returns a singleton Name [it].
436 What you type The IO [HValue] that hscStmt returns
437 ------------- ------------------------------------
438 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
441 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
444 expr (of IO type) ==> expr >>= \ v -> return [v]
445 [NB: result not printed] bindings: [it]
448 expr (of non-IO type,
449 result showable) ==> let v = expr in print v >> return [v]
452 expr (of non-IO type,
453 result not showable) ==> error
457 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
459 -> PersistentCompilerState -- IN: persistent compiler state
460 -> InteractiveContext -- Context for compiling
461 -> String -- The statement
462 -> IO ( PersistentCompilerState,
463 Maybe (InteractiveContext, [Name], HValue) )
465 hscStmt hsc_env pcs icontext stmt
466 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
467 ; case maybe_stmt of {
468 Nothing -> return (pcs, Nothing) ;
469 Just parsed_stmt -> do {
471 -- Rename and typecheck it
472 (pcs1, maybe_tc_result)
473 <- tcRnStmt hsc_env pcs icontext parsed_stmt
475 ; case maybe_tc_result of {
476 Nothing -> return (pcs1, Nothing) ;
477 Just (new_ic, bound_names, tc_expr) -> do {
479 -- Then desugar, code gen, and link it
480 ; hval <- compileExpr hsc_env pcs1 iNTERACTIVE
481 (ic_rn_gbl_env new_ic)
485 ; return (pcs1, Just (new_ic, bound_names, hval))
488 hscTcExpr -- Typecheck an expression (but don't run it)
490 -> PersistentCompilerState -- IN: persistent compiler state
491 -> InteractiveContext -- Context for compiling
492 -> String -- The expression
493 -> IO (PersistentCompilerState, Maybe Type)
495 hscTcExpr hsc_env pcs icontext expr
496 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
497 ; case maybe_stmt of {
498 Just (ExprStmt expr _ _)
499 -> tcRnExpr hsc_env pcs icontext expr ;
500 Just other -> do { hPutStrLn stderr ("not an expression: `" ++ expr ++ "'") ;
501 return (pcs, Nothing) } ;
502 Nothing -> return (pcs, Nothing) } }
506 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
507 hscParseStmt dflags str
508 = do showPass dflags "Parser"
511 buf <- stringToStringBuffer str
513 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
515 case unP parseStmt (mkPState buf loc dflags) of {
517 PFailed l1 l2 err -> do { hPutStrLn stderr (showPFailed l1 l2 err);
520 -- no stmt: the line consisted of just space or comments
521 POk _ Nothing -> return Nothing;
523 POk _ (Just rdr_stmt) -> do {
525 --ToDo: can't free the string buffer until we've finished this
526 -- compilation sweep and all the identifiers have gone away.
527 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
528 return (Just rdr_stmt)
533 %************************************************************************
535 \subsection{Getting information about an identifer}
537 %************************************************************************
541 hscThing -- like hscStmt, but deals with a single identifier
543 -> PersistentCompilerState -- IN: persistent compiler state
544 -> InteractiveContext -- Context for compiling
545 -> String -- The identifier
546 -> IO ( PersistentCompilerState,
549 hscThing hsc_env pcs0 ic str
550 = do let dflags = hsc_dflags hsc_env
552 maybe_rdr_name <- myParseIdentifier dflags str
553 case maybe_rdr_name of {
554 Nothing -> return (pcs0, []);
557 (pcs1, maybe_tc_result) <-
558 tcRnThing hsc_env pcs0 ic rdr_name
560 case maybe_tc_result of {
561 Nothing -> return (pcs1, []) ;
562 Just things -> return (pcs1, things)
565 myParseIdentifier dflags str
566 = do buf <- stringToStringBuffer str
568 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
569 case unP parseIdentifier (mkPState buf loc dflags) of
571 PFailed l1 l2 err -> do { hPutStrLn stderr (showPFailed l1 l2 err);
574 POk _ rdr_name -> return (Just rdr_name)
578 %************************************************************************
580 Desugar, simplify, convert to bytecode, and link an expression
582 %************************************************************************
586 compileExpr :: HscEnv
587 -> PersistentCompilerState
588 -> Module -> GlobalRdrEnv -> TypeEnv
592 compileExpr hsc_env pcs this_mod rdr_env type_env tc_expr
593 = do { let { dflags = hsc_dflags hsc_env ;
594 lint_on = dopt Opt_DoCoreLinting dflags }
597 ; ds_expr <- deSugarExpr hsc_env pcs this_mod rdr_env type_env tc_expr
600 ; flat_expr <- flattenExpr hsc_env pcs ds_expr
603 ; simpl_expr <- simplifyExpr dflags flat_expr
605 -- Tidy it (temporary, until coreSat does cloning)
606 ; tidy_expr <- tidyCoreExpr simpl_expr
608 -- Prepare for codegen
609 ; prepd_expr <- corePrepExpr dflags tidy_expr
612 -- ToDo: improve SrcLoc
614 case lintUnfolding noSrcLoc [] prepd_expr of
615 Just err -> pprPanic "compileExpr" err
621 ; bcos <- coreExprToBCOs dflags prepd_expr
624 ; hval <- linkExpr hsc_env pcs bcos
632 %************************************************************************
634 \subsection{Initial persistent state}
636 %************************************************************************
639 initPersistentCompilerState :: IO PersistentCompilerState
640 initPersistentCompilerState
641 = do nc <- initNameCache
643 PCS { pcs_EPS = initExternalPackageState,
646 initNameCache :: IO NameCache
647 = do us <- mkSplitUniqSupply 'r'
648 return (NameCache { nsUniqs = us,
649 nsNames = initOrigNames,
652 initExternalPackageState :: ExternalPackageState
653 initExternalPackageState
654 = emptyExternalPackageState {
655 eps_rules = foldr add_rule (emptyBag, 0) builtinRules,
656 eps_PTE = wiredInThingEnv,
659 add_rule (name,rule) (rules, n_slurped)
660 = (gated_decl `consBag` rules, n_slurped)
662 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
663 mod = nameModule name
664 rdr_name = nameRdrName name -- Seems a bit of a hack to go back
666 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
668 initOrigNames :: OrigNameCache
669 initOrigNames = foldl extendOrigNameCache emptyModuleEnv knownKeyNames