2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 HscResult(..), hscMain, newHscEnv, hscBufferFrontEnd
11 , hscStmt, hscTcExpr, hscThing,
16 #include "HsVersions.h"
19 import HsSyn ( Stmt(..), LStmt, LHsExpr )
20 import IfaceSyn ( IfaceDecl )
21 import CodeOutput ( outputForeignStubs )
22 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
23 import Linker ( HValue, linkExpr )
24 import TidyPgm ( tidyCoreExpr )
25 import CorePrep ( corePrepExpr )
26 import Flattening ( flattenExpr )
27 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnThing )
28 import RdrName ( RdrName, GlobalRdrEnv )
30 import PrelNames ( iNTERACTIVE )
31 import StringBuffer ( stringToStringBuffer )
32 import SrcLoc ( noSrcLoc, Located(..) )
35 import CoreLint ( lintUnfolding )
36 import DsMeta ( templateHaskellNames )
37 import BasicTypes ( Fixity )
40 import StringBuffer ( hGetStringBuffer )
42 import Lexer ( P(..), ParseResult(..), mkPState )
43 import SrcLoc ( mkSrcLoc )
44 import TcRnDriver ( tcRnModule, tcRnExtCore )
45 import TcIface ( typecheckIface )
46 import IfaceEnv ( initNameCache )
47 import LoadIface ( ifaceStats, initExternalPackageState )
48 import PrelInfo ( wiredInThings, basicKnownKeyNames )
49 import RdrName ( GlobalRdrEnv )
50 import MkIface ( checkOldIface, mkIface )
52 import Flattening ( flatten )
54 import TidyPgm ( tidyCorePgm )
55 import CorePrep ( corePrepPgm )
56 import CoreToStg ( coreToStg )
57 import Name ( Name, NamedThing(..) )
58 import SimplStg ( stg2stg )
59 import CodeGen ( codeGen )
60 import CodeOutput ( codeOutput )
63 import DriverPhases ( isExtCoreFilename )
65 import UniqSupply ( mkSplitUniqSupply )
68 import HscStats ( ppSourceStats )
70 import MkExternalCore ( emitExternalCore )
72 import ParserCoreUtils
73 import Module ( Module, ModLocation(..), showModMsg )
75 import Maybes ( expectJust )
76 import StringBuffer ( StringBuffer )
77 import Bag ( unitBag, emptyBag )
80 import Maybe ( isJust, fromJust )
82 import DATA_IOREF ( newIORef, readIORef )
86 %************************************************************************
90 %************************************************************************
93 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
94 newHscEnv ghci_mode dflags
95 = do { eps_var <- newIORef initExternalPackageState
96 ; us <- mkSplitUniqSupply 'r'
97 ; nc_var <- newIORef (initNameCache us knownKeyNames)
98 ; return (HscEnv { hsc_mode = ghci_mode,
100 hsc_HPT = emptyHomePackageTable,
102 hsc_NC = nc_var } ) }
105 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
106 -- where templateHaskellNames are defined
107 knownKeyNames = map getName wiredInThings
108 ++ basicKnownKeyNames
110 ++ templateHaskellNames
115 %************************************************************************
117 The main compiler pipeline
119 %************************************************************************
123 -- Compilation failed
126 -- In IDE mode: we just do the static/dynamic checks
129 -- Concluded that it wasn't necessary
130 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
131 ModIface -- new iface (if any compilation was done)
134 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
136 ModIface -- new iface (if any compilation was done)
137 Bool -- stub_h exists
138 Bool -- stub_c exists
139 (Maybe CompiledByteCode)
142 -- What to do when we have compiler error or warning messages
143 type MessageAction = Messages -> IO ()
145 -- no errors or warnings; the individual passes
146 -- (parse/rename/typecheck) print messages themselves
150 -> MessageAction -- what to do with errors/warnings
152 -> ModLocation -- location info
153 -> Bool -- True <=> source unchanged
154 -> Bool -- True <=> have an object file (for msgs only)
155 -> Maybe ModIface -- old interface, if available
158 hscMain hsc_env msg_act mod location
159 source_unchanged have_object maybe_old_iface
161 (recomp_reqd, maybe_checked_iface) <-
162 _scc_ "checkOldIface"
163 checkOldIface hsc_env mod
164 (ml_hi_file location)
165 source_unchanged maybe_old_iface;
167 let no_old_iface = not (isJust maybe_checked_iface)
168 what_next | recomp_reqd || no_old_iface = hscRecomp
169 | otherwise = hscNoRecomp
171 ; what_next hsc_env msg_act have_object
172 mod location maybe_checked_iface
176 -- hscNoRecomp definitely expects to have the old interface available
177 hscNoRecomp hsc_env msg_act have_object
178 mod location (Just old_iface)
179 | hsc_mode hsc_env == OneShot
181 when (verbosity (hsc_dflags hsc_env) > 0) $
182 hPutStrLn stderr "compilation IS NOT required";
183 dumpIfaceStats hsc_env ;
185 let { bomb = panic "hscNoRecomp:OneShot" };
186 return (HscNoRecomp bomb bomb)
190 when (verbosity (hsc_dflags hsc_env) >= 1) $
191 hPutStrLn stderr ("Skipping " ++
192 showModMsg have_object mod location);
194 new_details <- _scc_ "tcRnIface"
195 typecheckIface hsc_env old_iface ;
196 dumpIfaceStats hsc_env ;
198 return (HscNoRecomp new_details old_iface)
201 hscRecomp hsc_env msg_act have_object
202 mod location maybe_checked_iface
204 -- what target are we shooting for?
205 ; let one_shot = hsc_mode hsc_env == OneShot
206 ; let dflags = hsc_dflags hsc_env
207 ; let toInterp = dopt_HscLang dflags == HscInterpreted
208 ; let toCore = isJust (ml_hs_file location) &&
209 isExtCoreFilename (fromJust (ml_hs_file location))
211 ; when (not one_shot && verbosity dflags >= 1) $
212 hPutStrLn stderr ("Compiling " ++
213 showModMsg (not toInterp) mod location);
215 ; front_res <- if toCore then
216 hscCoreFrontEnd hsc_env msg_act location
218 hscFileFrontEnd hsc_env msg_act location
221 Left flure -> return flure;
222 Right ds_result -> do {
226 -- ; seqList imported_modules (return ())
231 ; flat_result <- _scc_ "Flattening"
232 flatten hsc_env ds_result
235 {- TEMP: need to review space-leak fixing here
236 NB: even the code generator can force one of the
237 thunks for constructor arguments, for newtypes in particular
239 ; let -- Rule-base accumulated from imported packages
240 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
242 -- In one-shot mode, ZAP the external package state at
243 -- this point, because we aren't going to need it from
244 -- now on. We keep the name cache, however, because
245 -- tidyCore needs it.
247 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
250 ; pkg_rule_base `seq` pcs_middle `seq` return ()
253 -- alive at this point:
261 ; simpl_result <- _scc_ "Core2Core"
262 core2core hsc_env flat_result
267 ; tidy_result <- _scc_ "CoreTidy"
268 tidyCorePgm hsc_env simpl_result
270 -- Emit external core
271 ; emitExternalCore dflags tidy_result
273 -- Alive at this point:
274 -- tidy_result, pcs_final
278 -- BUILD THE NEW ModIface and ModDetails
279 -- and emit external core if necessary
280 -- This has to happen *after* code gen so that the back-end
281 -- info has been set. Not yet clear if it matters waiting
282 -- until after code output
283 ; new_iface <- _scc_ "MkFinalIface"
284 mkIface hsc_env location
285 maybe_checked_iface tidy_result
288 -- Space leak reduction: throw away the new interface if
289 -- we're in one-shot mode; we won't be needing it any
292 if one_shot then return (error "no final iface")
293 else return new_iface
294 ; let { final_globals | one_shot = Nothing
295 | otherwise = Just $! (mg_rdr_env tidy_result) }
296 ; final_globals `seq` return ()
298 -- Build the final ModDetails (except in one-shot mode, where
299 -- we won't need this information after compilation).
301 if one_shot then return (error "no final details")
302 else return $! ModDetails {
303 md_types = mg_types tidy_result,
304 md_insts = mg_insts tidy_result,
305 md_rules = mg_rules tidy_result }
308 -- CONVERT TO STG and COMPLETE CODE GENERATION
309 ; (stub_h_exists, stub_c_exists, maybe_bcos)
310 <- hscBackEnd dflags tidy_result
312 -- And the answer is ...
313 ; dumpIfaceStats hsc_env
315 ; return (HscRecomp final_details
318 stub_h_exists stub_c_exists
322 hscCoreFrontEnd hsc_env msg_act location = do {
326 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
327 ; case parseCore inp 1 of
328 FailP s -> hPutStrLn stderr s >> return (Left HscFail)
329 OkP rdr_module -> do {
332 -- RENAME and TYPECHECK
334 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
335 tcRnExtCore hsc_env rdr_module
337 ; case maybe_tc_result of {
338 Nothing -> return (Left HscFail);
339 Just mod_guts -> return (Right mod_guts)
340 -- No desugaring to do!
344 hscFileFrontEnd hsc_env msg_act location = do {
348 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
349 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
351 ; case maybe_parsed of {
352 Left err -> do { msg_act (unitBag err, emptyBag) ;
353 ; return (Left HscFail) ;
355 Right rdr_module -> hscFrontEnd hsc_env msg_act rdr_module
358 -- Perform static/dynamic checks on the source code in a StringBuffer
359 -- This is a temporary solution: it'll read in interface files lazilly, whereas
360 -- we probably want to use the compilation manager to load in all the modules
362 hscBufferFrontEnd :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
363 hscBufferFrontEnd hsc_env buffer msg_act = do
364 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
365 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
366 PFailed span err -> do
367 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
369 POk _ rdr_module -> do
370 r <- hscFrontEnd hsc_env msg_act rdr_module
373 Right _ -> return HscChecked
377 hscFrontEnd hsc_env msg_act rdr_module = do {
379 -- RENAME and TYPECHECK
381 ; (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
382 tcRnModule hsc_env rdr_module
384 ; case maybe_tc_result of {
385 Nothing -> return (Left HscFail);
386 Just tc_result -> do {
391 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
392 deSugar hsc_env tc_result
393 ; msg_act (warns, emptyBag)
394 ; case maybe_ds_result of
395 Nothing -> return (Left HscFail);
396 Just ds_result -> return (Right ds_result);
400 ModGuts{ -- This is the last use of the ModGuts in a compilation.
401 -- From now on, we just use the bits we need.
402 mg_module = this_mod,
403 mg_binds = core_binds,
405 mg_dir_imps = dir_imps,
406 mg_foreign = foreign_stubs,
407 mg_deps = dependencies } = do {
410 -- PREPARE FOR CODE GENERATION
411 -- Do saturation and convert to A-normal form
412 prepd_binds <- _scc_ "CorePrep"
413 corePrepPgm dflags core_binds type_env;
415 case dopt_HscLang dflags of
416 HscNothing -> return (False, False, Nothing)
420 do ----------------- Generate byte code ------------------
421 comp_bc <- byteCodeGen dflags prepd_binds type_env
423 ------------------ Create f-x-dynamic C-side stuff ---
424 (istub_h_exists, istub_c_exists)
425 <- outputForeignStubs dflags foreign_stubs
427 return ( istub_h_exists, istub_c_exists, Just comp_bc )
429 panic "GHC not compiled with interpreter"
434 ----------------- Convert to STG ------------------
435 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
436 myCoreToStg dflags this_mod prepd_binds
438 ------------------ Code generation ------------------
439 abstractC <- _scc_ "CodeGen"
440 codeGen dflags this_mod type_env foreign_stubs
441 dir_imps cost_centre_info stg_binds
443 ------------------ Code output -----------------------
444 (stub_h_exists, stub_c_exists)
445 <- codeOutput dflags this_mod foreign_stubs
446 dependencies abstractC
448 return (stub_h_exists, stub_c_exists, Nothing)
452 myParseModule dflags src_filename
453 = do -------------------------- Parser ----------------
454 showPass dflags "Parser"
456 buf <- hGetStringBuffer src_filename
458 let loc = mkSrcLoc (mkFastString src_filename) 1 0
460 case unP parseModule (mkPState buf loc dflags) of {
462 PFailed span err -> return (Left (mkPlainErrMsg span err));
464 POk _ rdr_module -> do {
466 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
468 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
469 (ppSourceStats False rdr_module) ;
471 return (Right rdr_module)
472 -- ToDo: free the string buffer later.
476 myCoreToStg dflags this_mod prepd_binds
478 stg_binds <- _scc_ "Core2Stg"
479 coreToStg dflags prepd_binds
481 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
482 stg2stg dflags this_mod stg_binds
484 return (stg_binds2, cost_centre_info)
488 %************************************************************************
490 \subsection{Compiling a do-statement}
492 %************************************************************************
494 When the UnlinkedBCOExpr is linked you get an HValue of type
496 When you run it you get a list of HValues that should be
497 the same length as the list of names; add them to the ClosureEnv.
499 A naked expression returns a singleton Name [it].
501 What you type The IO [HValue] that hscStmt returns
502 ------------- ------------------------------------
503 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
506 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
509 expr (of IO type) ==> expr >>= \ v -> return [v]
510 [NB: result not printed] bindings: [it]
513 expr (of non-IO type,
514 result showable) ==> let v = expr in print v >> return [v]
517 expr (of non-IO type,
518 result not showable) ==> error
522 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
524 -> InteractiveContext -- Context for compiling
525 -> String -- The statement
526 -> IO (Maybe (InteractiveContext, [Name], HValue))
528 hscStmt hsc_env icontext stmt
529 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
530 ; case maybe_stmt of {
531 Nothing -> return Nothing ;
532 Just parsed_stmt -> do {
534 -- Rename and typecheck it
536 <- tcRnStmt hsc_env icontext parsed_stmt
538 ; case maybe_tc_result of {
539 Nothing -> return Nothing ;
540 Just (new_ic, bound_names, tc_expr) -> do {
542 -- Then desugar, code gen, and link it
543 ; hval <- compileExpr hsc_env iNTERACTIVE
544 (ic_rn_gbl_env new_ic)
548 ; return (Just (new_ic, bound_names, hval))
551 hscTcExpr -- Typecheck an expression (but don't run it)
553 -> InteractiveContext -- Context for compiling
554 -> String -- The expression
557 hscTcExpr hsc_env icontext expr
558 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
559 ; case maybe_stmt of {
560 Just (L _ (ExprStmt expr _))
561 -> tcRnExpr hsc_env icontext expr ;
562 Just other -> do { hPutStrLn stderr ("not an expression: `" ++ expr ++ "'") ;
564 Nothing -> return Nothing } }
568 hscParseStmt :: DynFlags -> String -> IO (Maybe (LStmt RdrName))
569 hscParseStmt dflags str
570 = do showPass dflags "Parser"
573 buf <- stringToStringBuffer str
575 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
577 case unP parseStmt (mkPState buf loc dflags) of {
579 PFailed span err -> do { printError span err;
582 -- no stmt: the line consisted of just space or comments
583 POk _ Nothing -> return Nothing;
585 POk _ (Just rdr_stmt) -> do {
587 --ToDo: can't free the string buffer until we've finished this
588 -- compilation sweep and all the identifiers have gone away.
589 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
590 return (Just rdr_stmt)
595 %************************************************************************
597 \subsection{Getting information about an identifer}
599 %************************************************************************
603 hscThing -- like hscStmt, but deals with a single identifier
605 -> InteractiveContext -- Context for compiling
606 -> String -- The identifier
607 -> IO [(IfaceDecl, Fixity)]
609 hscThing hsc_env ic str
610 = do maybe_rdr_name <- myParseIdentifier (hsc_dflags hsc_env) str
611 case maybe_rdr_name of {
612 Nothing -> return [];
613 Just (L _ rdr_name) -> do
615 maybe_tc_result <- tcRnThing hsc_env ic rdr_name
617 case maybe_tc_result of {
618 Nothing -> return [] ;
619 Just things -> return things
622 myParseIdentifier dflags str
623 = do buf <- stringToStringBuffer str
625 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
626 case unP parseIdentifier (mkPState buf loc dflags) of
628 PFailed span err -> do { printError span err;
631 POk _ rdr_name -> return (Just rdr_name)
635 %************************************************************************
637 Desugar, simplify, convert to bytecode, and link an expression
639 %************************************************************************
643 compileExpr :: HscEnv
644 -> Module -> GlobalRdrEnv -> TypeEnv
648 compileExpr hsc_env this_mod rdr_env type_env tc_expr
649 = do { let { dflags = hsc_dflags hsc_env ;
650 lint_on = dopt Opt_DoCoreLinting dflags }
653 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
656 ; flat_expr <- flattenExpr hsc_env ds_expr
659 ; simpl_expr <- simplifyExpr dflags flat_expr
661 -- Tidy it (temporary, until coreSat does cloning)
662 ; tidy_expr <- tidyCoreExpr simpl_expr
664 -- Prepare for codegen
665 ; prepd_expr <- corePrepExpr dflags tidy_expr
668 -- ToDo: improve SrcLoc
670 case lintUnfolding noSrcLoc [] prepd_expr of
671 Just err -> pprPanic "compileExpr" err
677 ; bcos <- coreExprToBCOs dflags prepd_expr
680 ; hval <- linkExpr hsc_env bcos
688 %************************************************************************
690 Statistics on reading interfaces
692 %************************************************************************
695 dumpIfaceStats :: HscEnv -> IO ()
696 dumpIfaceStats hsc_env
697 = do { eps <- readIORef (hsc_EPS hsc_env)
698 ; dumpIfSet (dump_if_trace || dump_rn_stats)
699 "Interface statistics"
702 dflags = hsc_dflags hsc_env
703 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
704 dump_if_trace = dopt Opt_D_dump_if_trace dflags