2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 HscResult(..), hscMain, newHscEnv
11 , hscStmt, hscTcExpr, hscThing,
16 #include "HsVersions.h"
19 import HsSyn ( Stmt(..) )
20 import TcHsSyn ( TypecheckedHsExpr )
21 import IfaceSyn ( IfaceDecl )
22 import CodeOutput ( outputForeignStubs )
23 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
24 import Linker ( HValue, linkExpr )
25 import TidyPgm ( tidyCoreExpr )
26 import CorePrep ( corePrepExpr )
27 import Flattening ( flattenExpr )
28 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnThing )
29 import RdrHsSyn ( RdrNameStmt )
30 import RdrName ( GlobalRdrEnv )
32 import PrelNames ( iNTERACTIVE )
33 import StringBuffer ( stringToStringBuffer )
34 import SrcLoc ( noSrcLoc )
36 import CoreLint ( lintUnfolding )
37 import DsMeta ( templateHaskellNames )
38 import BasicTypes ( Fixity )
41 import StringBuffer ( hGetStringBuffer )
43 import Lexer ( P(..), ParseResult(..), mkPState, showPFailed )
44 import SrcLoc ( mkSrcLoc )
45 import TcRnDriver ( tcRnModule, tcRnExtCore )
46 import TcIface ( typecheckIface )
47 import IfaceEnv ( initNameCache )
48 import LoadIface ( ifaceStats, initExternalPackageState )
49 import PrelInfo ( wiredInThings, basicKnownKeyNames )
50 import RdrName ( GlobalRdrEnv )
51 import MkIface ( checkOldIface, mkIface )
53 import Flattening ( flatten )
55 import TidyPgm ( tidyCorePgm )
56 import CorePrep ( corePrepPgm )
57 import CoreToStg ( coreToStg )
58 import Name ( Name, NamedThing(..) )
59 import SimplStg ( stg2stg )
60 import CodeGen ( codeGen )
61 import CodeOutput ( codeOutput )
64 import DriverPhases ( isExtCoreFilename )
65 import ErrUtils ( dumpIfSet, dumpIfSet_dyn, showPass )
66 import UniqSupply ( mkSplitUniqSupply )
69 import HscStats ( ppSourceStats )
71 import MkExternalCore ( emitExternalCore )
73 import ParserCoreUtils
74 import Module ( Module, ModLocation(..), showModMsg )
76 import Maybes ( expectJust )
79 import Maybe ( isJust, fromJust )
81 import DATA_IOREF ( newIORef, readIORef )
85 %************************************************************************
89 %************************************************************************
92 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
93 newHscEnv ghci_mode dflags
94 = do { eps_var <- newIORef initExternalPackageState
95 ; us <- mkSplitUniqSupply 'r'
96 ; nc_var <- newIORef (initNameCache us knownKeyNames)
97 ; return (HscEnv { hsc_mode = ghci_mode,
99 hsc_HPT = emptyHomePackageTable,
101 hsc_NC = nc_var } ) }
104 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
105 -- where templateHaskellNames are defined
106 knownKeyNames = map getName wiredInThings
107 ++ basicKnownKeyNames
109 ++ templateHaskellNames
114 %************************************************************************
116 The main compiler pipeline
118 %************************************************************************
122 -- Compilation failed
125 -- Concluded that it wasn't necessary
126 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
127 ModIface -- new iface (if any compilation was done)
130 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
132 ModIface -- new iface (if any compilation was done)
133 Bool -- stub_h exists
134 Bool -- stub_c exists
135 (Maybe CompiledByteCode)
137 -- no errors or warnings; the individual passes
138 -- (parse/rename/typecheck) print messages themselves
143 -> ModLocation -- location info
144 -> Bool -- True <=> source unchanged
145 -> Bool -- True <=> have an object file (for msgs only)
146 -> Maybe ModIface -- old interface, if available
149 hscMain hsc_env mod location
150 source_unchanged have_object maybe_old_iface
152 (recomp_reqd, maybe_checked_iface) <-
153 _scc_ "checkOldIface"
154 checkOldIface hsc_env mod
155 (ml_hi_file location)
156 source_unchanged maybe_old_iface;
158 let no_old_iface = not (isJust maybe_checked_iface)
159 what_next | recomp_reqd || no_old_iface = hscRecomp
160 | otherwise = hscNoRecomp
162 ; what_next hsc_env have_object
163 mod location maybe_checked_iface
167 -- hscNoRecomp definitely expects to have the old interface available
168 hscNoRecomp hsc_env have_object
169 mod location (Just old_iface)
170 | hsc_mode hsc_env == OneShot
172 when (verbosity (hsc_dflags hsc_env) > 0) $
173 hPutStrLn stderr "compilation IS NOT required";
174 dumpIfaceStats hsc_env ;
176 let { bomb = panic "hscNoRecomp:OneShot" };
177 return (HscNoRecomp bomb bomb)
181 when (verbosity (hsc_dflags hsc_env) >= 1) $
182 hPutStrLn stderr ("Skipping " ++
183 showModMsg have_object mod location);
185 new_details <- _scc_ "tcRnIface"
186 typecheckIface hsc_env old_iface ;
187 dumpIfaceStats hsc_env ;
189 return (HscNoRecomp new_details old_iface)
192 hscRecomp hsc_env have_object
193 mod location maybe_checked_iface
195 -- what target are we shooting for?
196 ; let one_shot = hsc_mode hsc_env == OneShot
197 ; let dflags = hsc_dflags hsc_env
198 ; let toInterp = dopt_HscLang dflags == HscInterpreted
199 ; let toCore = isJust (ml_hs_file location) &&
200 isExtCoreFilename (fromJust (ml_hs_file location))
202 ; when (not one_shot && verbosity dflags >= 1) $
203 hPutStrLn stderr ("Compiling " ++
204 showModMsg (not toInterp) mod location);
206 ; front_res <- if toCore then
207 hscCoreFrontEnd hsc_env location
209 hscFrontEnd hsc_env location
212 Left flure -> return flure;
213 Right ds_result -> do {
217 -- ; seqList imported_modules (return ())
222 ; flat_result <- _scc_ "Flattening"
223 flatten hsc_env ds_result
226 {- TEMP: need to review space-leak fixing here
227 NB: even the code generator can force one of the
228 thunks for constructor arguments, for newtypes in particular
230 ; let -- Rule-base accumulated from imported packages
231 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
233 -- In one-shot mode, ZAP the external package state at
234 -- this point, because we aren't going to need it from
235 -- now on. We keep the name cache, however, because
236 -- tidyCore needs it.
238 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
241 ; pkg_rule_base `seq` pcs_middle `seq` return ()
244 -- alive at this point:
252 ; simpl_result <- _scc_ "Core2Core"
253 core2core hsc_env flat_result
258 ; tidy_result <- _scc_ "CoreTidy"
259 tidyCorePgm hsc_env simpl_result
261 -- Emit external core
262 ; emitExternalCore dflags tidy_result
264 -- Alive at this point:
265 -- tidy_result, pcs_final
269 -- BUILD THE NEW ModIface and ModDetails
270 -- and emit external core if necessary
271 -- This has to happen *after* code gen so that the back-end
272 -- info has been set. Not yet clear if it matters waiting
273 -- until after code output
274 ; new_iface <- _scc_ "MkFinalIface"
275 mkIface hsc_env location
276 maybe_checked_iface tidy_result
279 -- Space leak reduction: throw away the new interface if
280 -- we're in one-shot mode; we won't be needing it any
283 if one_shot then return (error "no final iface")
284 else return new_iface
285 ; let { final_globals | one_shot = Nothing
286 | otherwise = Just $! (mg_rdr_env tidy_result) }
287 ; final_globals `seq` return ()
289 -- Build the final ModDetails (except in one-shot mode, where
290 -- we won't need this information after compilation).
292 if one_shot then return (error "no final details")
293 else return $! ModDetails {
294 md_types = mg_types tidy_result,
295 md_insts = mg_insts tidy_result,
296 md_rules = mg_rules tidy_result }
299 -- CONVERT TO STG and COMPLETE CODE GENERATION
300 ; (stub_h_exists, stub_c_exists, maybe_bcos)
301 <- hscBackEnd dflags tidy_result
303 -- And the answer is ...
304 ; dumpIfaceStats hsc_env
306 ; return (HscRecomp final_details
309 stub_h_exists stub_c_exists
313 hscCoreFrontEnd hsc_env location = do {
317 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
318 ; case parseCore inp 1 of
319 FailP s -> hPutStrLn stderr s >> return (Left HscFail);
320 OkP rdr_module -> do {
323 -- RENAME and TYPECHECK
325 ; maybe_tc_result <- _scc_ "TypeCheck"
326 tcRnExtCore hsc_env rdr_module
327 ; case maybe_tc_result of {
328 Nothing -> return (Left HscFail);
329 Just mod_guts -> return (Right mod_guts)
330 -- No desugaring to do!
334 hscFrontEnd hsc_env location = do {
338 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
339 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
341 ; case maybe_parsed of {
342 Nothing -> return (Left HscFail);
343 Just rdr_module -> do {
346 -- RENAME and TYPECHECK
348 ; maybe_tc_result <- _scc_ "Typecheck-Rename"
349 tcRnModule hsc_env rdr_module
350 ; case maybe_tc_result of {
351 Nothing -> return (Left HscFail);
352 Just tc_result -> do {
357 ; maybe_ds_result <- _scc_ "DeSugar"
358 deSugar hsc_env tc_result
359 ; case maybe_ds_result of
360 Nothing -> return (Left HscFail);
361 Just ds_result -> return (Right ds_result);
366 ModGuts{ -- This is the last use of the ModGuts in a compilation.
367 -- From now on, we just use the bits we need.
368 mg_module = this_mod,
369 mg_binds = core_binds,
371 mg_dir_imps = dir_imps,
372 mg_foreign = foreign_stubs,
373 mg_deps = dependencies } = do {
376 -- PREPARE FOR CODE GENERATION
377 -- Do saturation and convert to A-normal form
378 prepd_binds <- _scc_ "CorePrep"
379 corePrepPgm dflags core_binds type_env;
381 case dopt_HscLang dflags of
382 HscNothing -> return (False, False, Nothing)
386 do ----------------- Generate byte code ------------------
387 comp_bc <- byteCodeGen dflags prepd_binds type_env
389 ------------------ Create f-x-dynamic C-side stuff ---
390 (istub_h_exists, istub_c_exists)
391 <- outputForeignStubs dflags foreign_stubs
393 return ( istub_h_exists, istub_c_exists, Just comp_bc )
395 panic "GHC not compiled with interpreter"
400 ----------------- Convert to STG ------------------
401 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
402 myCoreToStg dflags this_mod prepd_binds
404 ------------------ Code generation ------------------
405 abstractC <- _scc_ "CodeGen"
406 codeGen dflags this_mod type_env foreign_stubs
407 dir_imps cost_centre_info stg_binds
409 ------------------ Code output -----------------------
410 (stub_h_exists, stub_c_exists)
411 <- codeOutput dflags this_mod foreign_stubs
412 dependencies abstractC
414 return (stub_h_exists, stub_c_exists, Nothing)
418 myParseModule dflags src_filename
419 = do -------------------------- Parser ----------------
420 showPass dflags "Parser"
422 buf <- hGetStringBuffer src_filename
424 let loc = mkSrcLoc (mkFastString src_filename) 1 0
426 case unP parseModule (mkPState buf loc dflags) of {
428 PFailed l1 l2 err -> do { hPutStrLn stderr (showSDoc (showPFailed l1 l2 err));
431 POk _ rdr_module -> do {
433 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
435 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
436 (ppSourceStats False rdr_module) ;
438 return (Just rdr_module)
439 -- ToDo: free the string buffer later.
443 myCoreToStg dflags this_mod prepd_binds
445 stg_binds <- _scc_ "Core2Stg"
446 coreToStg dflags prepd_binds
448 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
449 stg2stg dflags this_mod stg_binds
451 return (stg_binds2, cost_centre_info)
455 %************************************************************************
457 \subsection{Compiling a do-statement}
459 %************************************************************************
461 When the UnlinkedBCOExpr is linked you get an HValue of type
463 When you run it you get a list of HValues that should be
464 the same length as the list of names; add them to the ClosureEnv.
466 A naked expression returns a singleton Name [it].
468 What you type The IO [HValue] that hscStmt returns
469 ------------- ------------------------------------
470 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
473 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
476 expr (of IO type) ==> expr >>= \ v -> return [v]
477 [NB: result not printed] bindings: [it]
480 expr (of non-IO type,
481 result showable) ==> let v = expr in print v >> return [v]
484 expr (of non-IO type,
485 result not showable) ==> error
489 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
491 -> InteractiveContext -- Context for compiling
492 -> String -- The statement
493 -> IO (Maybe (InteractiveContext, [Name], HValue))
495 hscStmt hsc_env icontext stmt
496 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
497 ; case maybe_stmt of {
498 Nothing -> return Nothing ;
499 Just parsed_stmt -> do {
501 -- Rename and typecheck it
503 <- tcRnStmt hsc_env icontext parsed_stmt
505 ; case maybe_tc_result of {
506 Nothing -> return Nothing ;
507 Just (new_ic, bound_names, tc_expr) -> do {
509 -- Then desugar, code gen, and link it
510 ; hval <- compileExpr hsc_env iNTERACTIVE
511 (ic_rn_gbl_env new_ic)
515 ; return (Just (new_ic, bound_names, hval))
518 hscTcExpr -- Typecheck an expression (but don't run it)
520 -> InteractiveContext -- Context for compiling
521 -> String -- The expression
524 hscTcExpr hsc_env icontext expr
525 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
526 ; case maybe_stmt of {
527 Just (ExprStmt expr _ _)
528 -> tcRnExpr hsc_env icontext expr ;
529 Just other -> do { hPutStrLn stderr ("not an expression: `" ++ expr ++ "'") ;
531 Nothing -> return Nothing } }
535 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
536 hscParseStmt dflags str
537 = do showPass dflags "Parser"
540 buf <- stringToStringBuffer str
542 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
544 case unP parseStmt (mkPState buf loc dflags) of {
546 PFailed l1 l2 err -> do { hPutStrLn stderr (showSDoc (showPFailed l1 l2 err));
549 -- no stmt: the line consisted of just space or comments
550 POk _ Nothing -> return Nothing;
552 POk _ (Just rdr_stmt) -> do {
554 --ToDo: can't free the string buffer until we've finished this
555 -- compilation sweep and all the identifiers have gone away.
556 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
557 return (Just rdr_stmt)
562 %************************************************************************
564 \subsection{Getting information about an identifer}
566 %************************************************************************
570 hscThing -- like hscStmt, but deals with a single identifier
572 -> InteractiveContext -- Context for compiling
573 -> String -- The identifier
574 -> IO [(IfaceDecl, Fixity)]
576 hscThing hsc_env ic str
577 = do maybe_rdr_name <- myParseIdentifier (hsc_dflags hsc_env) str
578 case maybe_rdr_name of {
579 Nothing -> return [];
582 maybe_tc_result <- tcRnThing hsc_env ic rdr_name
584 case maybe_tc_result of {
585 Nothing -> return [] ;
586 Just things -> return things
589 myParseIdentifier dflags str
590 = do buf <- stringToStringBuffer str
592 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
593 case unP parseIdentifier (mkPState buf loc dflags) of
595 PFailed l1 l2 err -> do { hPutStrLn stderr (showSDoc (showPFailed l1 l2 err));
598 POk _ rdr_name -> return (Just rdr_name)
602 %************************************************************************
604 Desugar, simplify, convert to bytecode, and link an expression
606 %************************************************************************
610 compileExpr :: HscEnv
611 -> Module -> GlobalRdrEnv -> TypeEnv
615 compileExpr hsc_env this_mod rdr_env type_env tc_expr
616 = do { let { dflags = hsc_dflags hsc_env ;
617 lint_on = dopt Opt_DoCoreLinting dflags }
620 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
623 ; flat_expr <- flattenExpr hsc_env ds_expr
626 ; simpl_expr <- simplifyExpr dflags flat_expr
628 -- Tidy it (temporary, until coreSat does cloning)
629 ; tidy_expr <- tidyCoreExpr simpl_expr
631 -- Prepare for codegen
632 ; prepd_expr <- corePrepExpr dflags tidy_expr
635 -- ToDo: improve SrcLoc
637 case lintUnfolding noSrcLoc [] prepd_expr of
638 Just err -> pprPanic "compileExpr" err
644 ; bcos <- coreExprToBCOs dflags prepd_expr
647 ; hval <- linkExpr hsc_env bcos
655 %************************************************************************
657 Statistics on reading interfaces
659 %************************************************************************
662 dumpIfaceStats :: HscEnv -> IO ()
663 dumpIfaceStats hsc_env
664 = do { eps <- readIORef (hsc_EPS hsc_env)
665 ; dumpIfSet (dump_if_trace || dump_rn_stats)
666 "Interface statistics"
669 dflags = hsc_dflags hsc_env
670 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
671 dump_if_trace = dopt Opt_D_dump_if_trace dflags