2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
10 hscMain, newHscEnv, hscCmmFile,
11 hscBufferCheck, hscFileCheck,
13 , hscStmt, hscTcExpr, hscKcType
14 , hscGetInfo, GetInfoResult
19 #include "HsVersions.h"
22 import HsSyn ( Stmt(..), LStmt, LHsExpr, LHsType )
23 import IfaceSyn ( IfaceDecl, IfaceInst )
24 import Module ( Module )
25 import CodeOutput ( outputForeignStubs )
26 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
27 import Linker ( HValue, linkExpr )
28 import TidyPgm ( tidyCoreExpr )
29 import CorePrep ( corePrepExpr )
30 import Flattening ( flattenExpr )
31 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnGetInfo, tcRnType )
32 import RdrName ( rdrNameOcc )
33 import OccName ( occNameUserString )
35 import PrelNames ( iNTERACTIVE )
36 import StringBuffer ( stringToStringBuffer )
39 import CoreLint ( lintUnfolding )
40 import DsMeta ( templateHaskellNames )
41 import BasicTypes ( Fixity )
42 import SrcLoc ( SrcLoc, noSrcLoc )
45 import RdrName ( RdrName )
46 import HsSyn ( HsModule )
47 import SrcLoc ( Located(..) )
48 import StringBuffer ( hGetStringBuffer )
50 import Lexer ( P(..), ParseResult(..), mkPState )
51 import SrcLoc ( mkSrcLoc )
52 import TcRnDriver ( tcRnModule, tcRnExtCore )
53 import TcRnTypes ( TcGblEnv )
54 import TcIface ( typecheckIface )
55 import IfaceEnv ( initNameCache )
56 import LoadIface ( ifaceStats, initExternalPackageState )
57 import PrelInfo ( wiredInThings, basicKnownKeyNames )
58 import RdrName ( GlobalRdrEnv )
59 import MkIface ( checkOldIface, mkIface )
61 import Flattening ( flatten )
63 import TidyPgm ( tidyCorePgm )
64 import CorePrep ( corePrepPgm )
65 import CoreToStg ( coreToStg )
66 import Name ( Name, NamedThing(..) )
67 import SimplStg ( stg2stg )
68 import CodeGen ( codeGen )
69 import CmmParse ( parseCmmFile )
70 import CodeOutput ( codeOutput )
73 import DriverPhases ( HscSource(..) )
75 import UniqSupply ( mkSplitUniqSupply )
78 import HscStats ( ppSourceStats )
80 import MkExternalCore ( emitExternalCore )
82 import ParserCoreUtils
84 import Maybes ( expectJust )
85 import StringBuffer ( StringBuffer )
86 import Bag ( unitBag, emptyBag )
89 import Maybe ( isJust )
91 import DATA_IOREF ( newIORef, readIORef )
95 %************************************************************************
99 %************************************************************************
102 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
103 newHscEnv ghci_mode dflags
104 = do { eps_var <- newIORef initExternalPackageState
105 ; us <- mkSplitUniqSupply 'r'
106 ; nc_var <- newIORef (initNameCache us knownKeyNames)
107 ; return (HscEnv { hsc_mode = ghci_mode,
109 hsc_HPT = emptyHomePackageTable,
111 hsc_NC = nc_var } ) }
114 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
115 -- where templateHaskellNames are defined
116 knownKeyNames = map getName wiredInThings
117 ++ basicKnownKeyNames
119 ++ templateHaskellNames
124 %************************************************************************
126 The main compiler pipeline
128 %************************************************************************
132 -- Compilation failed
135 -- In IDE mode: we just do the static/dynamic checks
136 | HscChecked (Located (HsModule RdrName)) (Maybe TcGblEnv)
138 -- Concluded that it wasn't necessary
139 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
140 ModIface -- new iface (if any compilation was done)
143 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
145 ModIface -- new iface (if any compilation was done)
146 Bool -- stub_h exists
147 Bool -- stub_c exists
148 (Maybe CompiledByteCode)
151 -- What to do when we have compiler error or warning messages
152 type MessageAction = Messages -> IO ()
154 -- no errors or warnings; the individual passes
155 -- (parse/rename/typecheck) print messages themselves
159 -> MessageAction -- What to do with errors/warnings
161 -> Bool -- True <=> source unchanged
162 -> Bool -- True <=> have an object file (for msgs only)
163 -> Maybe ModIface -- Old interface, if available
166 hscMain hsc_env msg_act mod_summary
167 source_unchanged have_object maybe_old_iface
169 (recomp_reqd, maybe_checked_iface) <-
170 _scc_ "checkOldIface"
171 checkOldIface hsc_env mod_summary
172 source_unchanged maybe_old_iface;
174 let no_old_iface = not (isJust maybe_checked_iface)
175 what_next | recomp_reqd || no_old_iface = hscRecomp
176 | otherwise = hscNoRecomp
178 ; what_next hsc_env msg_act mod_summary have_object
183 ------------------------------
184 -- hscNoRecomp definitely expects to have the old interface available
185 hscNoRecomp hsc_env msg_act mod_summary
186 have_object (Just old_iface)
187 | isOneShot (hsc_mode hsc_env)
189 compilationProgressMsg (hsc_dflags hsc_env) $
190 "compilation IS NOT required";
191 dumpIfaceStats hsc_env ;
193 let { bomb = panic "hscNoRecomp:OneShot" };
194 return (HscNoRecomp bomb bomb)
197 = do { compilationProgressMsg (hsc_dflags hsc_env) $
198 ("Skipping " ++ showModMsg have_object mod_summary)
200 ; new_details <- _scc_ "tcRnIface"
201 typecheckIface hsc_env old_iface ;
202 ; dumpIfaceStats hsc_env
204 ; return (HscNoRecomp new_details old_iface)
207 ------------------------------
208 hscRecomp hsc_env msg_act mod_summary
209 have_object maybe_checked_iface
210 = case ms_hsc_src mod_summary of
211 HsSrcFile -> do { front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
212 ; hscBackEnd hsc_env mod_summary maybe_checked_iface front_res }
214 HsBootFile -> do { front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
215 ; hscBootBackEnd hsc_env mod_summary maybe_checked_iface front_res }
217 ExtCoreFile -> do { front_res <- hscCoreFrontEnd hsc_env msg_act mod_summary
218 ; hscBackEnd hsc_env mod_summary maybe_checked_iface front_res }
220 hscCoreFrontEnd hsc_env msg_act mod_summary = do {
224 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
225 ; case parseCore inp 1 of
226 FailP s -> putMsg s{-ToDo: wrong-} >> return Nothing
227 OkP rdr_module -> do {
230 -- RENAME and TYPECHECK
232 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
233 tcRnExtCore hsc_env rdr_module
235 ; case maybe_tc_result of
236 Nothing -> return Nothing
237 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
241 hscFileFrontEnd hsc_env msg_act mod_summary = do {
243 -- DISPLAY PROGRESS MESSAGE
245 let one_shot = isOneShot (hsc_mode hsc_env)
246 ; let dflags = hsc_dflags hsc_env
247 ; let toInterp = dopt_HscTarget dflags == HscInterpreted
248 ; when (not one_shot) $
249 compilationProgressMsg dflags $
250 ("Compiling " ++ showModMsg (not toInterp) mod_summary)
255 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
256 hspp_buf = ms_hspp_buf mod_summary
258 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
260 ; case maybe_parsed of {
261 Left err -> do { msg_act (unitBag err, emptyBag)
263 Right rdr_module -> do {
266 -- RENAME and TYPECHECK
268 (tc_msgs, maybe_tc_result)
269 <- _scc_ "Typecheck-Rename"
270 tcRnModule hsc_env (ms_hsc_src mod_summary) rdr_module
273 ; case maybe_tc_result of {
274 Nothing -> return Nothing ;
275 Just tc_result -> do {
280 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
281 deSugar hsc_env tc_result
282 ; msg_act (warns, emptyBag)
283 ; case maybe_ds_result of
284 Nothing -> return Nothing
285 Just ds_result -> return (Just ds_result)
288 ------------------------------
289 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
290 -- For hs-boot files, there's no code generation to do
292 hscBootBackEnd hsc_env mod_summary maybe_checked_iface Nothing
294 hscBootBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
295 = do { final_iface <- _scc_ "MkFinalIface"
296 mkIface hsc_env (ms_location mod_summary)
297 maybe_checked_iface ds_result
299 ; let { final_globals = Just $! (mg_rdr_env ds_result)
300 ; final_details = ModDetails { md_types = mg_types ds_result,
301 md_insts = mg_insts ds_result,
302 md_rules = mg_rules ds_result } }
303 -- And the answer is ...
304 ; dumpIfaceStats hsc_env
306 ; return (HscRecomp final_details
312 ------------------------------
313 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
315 hscBackEnd hsc_env mod_summary maybe_checked_iface Nothing
318 hscBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
320 -- ; seqList imported_modules (return ())
322 let one_shot = isOneShot (hsc_mode hsc_env)
323 dflags = hsc_dflags hsc_env
328 ; flat_result <- _scc_ "Flattening"
329 flatten hsc_env ds_result
332 {- TEMP: need to review space-leak fixing here
333 NB: even the code generator can force one of the
334 thunks for constructor arguments, for newtypes in particular
336 ; let -- Rule-base accumulated from imported packages
337 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
339 -- In one-shot mode, ZAP the external package state at
340 -- this point, because we aren't going to need it from
341 -- now on. We keep the name cache, however, because
342 -- tidyCore needs it.
344 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
347 ; pkg_rule_base `seq` pcs_middle `seq` return ()
350 -- alive at this point:
358 ; simpl_result <- _scc_ "Core2Core"
359 core2core hsc_env flat_result
364 ; tidy_result <- _scc_ "CoreTidy"
365 tidyCorePgm hsc_env simpl_result
367 -- Emit external core
368 ; emitExternalCore dflags tidy_result
370 -- Alive at this point:
371 -- tidy_result, pcs_final
375 -- BUILD THE NEW ModIface and ModDetails
376 -- and emit external core if necessary
377 -- This has to happen *after* code gen so that the back-end
378 -- info has been set. Not yet clear if it matters waiting
379 -- until after code output
380 ; new_iface <- _scc_ "MkFinalIface"
381 mkIface hsc_env (ms_location mod_summary)
382 maybe_checked_iface tidy_result
384 -- Space leak reduction: throw away the new interface if
385 -- we're in one-shot mode; we won't be needing it any
388 if one_shot then return (error "no final iface")
389 else return new_iface
390 ; let { final_globals | one_shot = Nothing
391 | otherwise = Just $! (mg_rdr_env tidy_result) }
392 ; final_globals `seq` return ()
394 -- Build the final ModDetails (except in one-shot mode, where
395 -- we won't need this information after compilation).
397 if one_shot then return (error "no final details")
398 else return $! ModDetails {
399 md_types = mg_types tidy_result,
400 md_insts = mg_insts tidy_result,
401 md_rules = mg_rules tidy_result }
404 -- CONVERT TO STG and COMPLETE CODE GENERATION
405 ; (stub_h_exists, stub_c_exists, maybe_bcos)
406 <- hscCodeGen dflags tidy_result
408 -- And the answer is ...
409 ; dumpIfaceStats hsc_env
411 ; return (HscRecomp final_details
414 stub_h_exists stub_c_exists
419 hscFileCheck hsc_env msg_act hspp_file = do {
423 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file Nothing
425 ; case maybe_parsed of {
426 Left err -> do { msg_act (unitBag err, emptyBag) ;
429 Right rdr_module -> hscBufferTypecheck hsc_env rdr_module msg_act
433 -- Perform static/dynamic checks on the source code in a StringBuffer
434 -- This is a temporary solution: it'll read in interface files lazily, whereas
435 -- we probably want to use the compilation manager to load in all the modules
437 hscBufferCheck :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
438 hscBufferCheck hsc_env buffer msg_act = do
439 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
440 showPass (hsc_dflags hsc_env) "Parser"
441 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
442 PFailed span err -> do
443 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
445 POk _ rdr_module -> do
446 hscBufferTypecheck hsc_env rdr_module msg_act
448 hscBufferTypecheck hsc_env rdr_module msg_act = do
449 (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
450 tcRnModule hsc_env HsSrcFile rdr_module
452 case maybe_tc_result of
453 Nothing -> return (HscChecked rdr_module Nothing)
454 -- space leak on rdr_module!
455 Just r -> return (HscChecked rdr_module (Just r))
459 ModGuts{ -- This is the last use of the ModGuts in a compilation.
460 -- From now on, we just use the bits we need.
461 mg_module = this_mod,
462 mg_binds = core_binds,
464 mg_dir_imps = dir_imps,
465 mg_foreign = foreign_stubs,
466 mg_deps = dependencies } = do {
469 -- PREPARE FOR CODE GENERATION
470 -- Do saturation and convert to A-normal form
471 prepd_binds <- _scc_ "CorePrep"
472 corePrepPgm dflags core_binds type_env;
474 case dopt_HscTarget dflags of
475 HscNothing -> return (False, False, Nothing)
479 do ----------------- Generate byte code ------------------
480 comp_bc <- byteCodeGen dflags prepd_binds type_env
482 ------------------ Create f-x-dynamic C-side stuff ---
483 (istub_h_exists, istub_c_exists)
484 <- outputForeignStubs dflags foreign_stubs
486 return ( istub_h_exists, istub_c_exists, Just comp_bc )
488 panic "GHC not compiled with interpreter"
493 ----------------- Convert to STG ------------------
494 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
495 myCoreToStg dflags this_mod prepd_binds
497 ------------------ Code generation ------------------
498 abstractC <- _scc_ "CodeGen"
499 codeGen dflags this_mod type_env foreign_stubs
500 dir_imps cost_centre_info stg_binds
502 ------------------ Code output -----------------------
503 (stub_h_exists, stub_c_exists)
504 <- codeOutput dflags this_mod foreign_stubs
505 dependencies abstractC
507 return (stub_h_exists, stub_c_exists, Nothing)
511 hscCmmFile :: DynFlags -> FilePath -> IO Bool
512 hscCmmFile dflags filename = do
513 maybe_cmm <- parseCmmFile dflags filename
515 Nothing -> return False
517 codeOutput dflags no_mod NoStubs noDependencies [cmm]
520 no_mod = panic "hscCmmFile: no_mod"
523 myParseModule dflags src_filename maybe_src_buf
524 = do -------------------------- Parser ----------------
525 showPass dflags "Parser"
528 -- sometimes we already have the buffer in memory, perhaps
529 -- because we needed to parse the imports out of it, or get the
531 buf <- case maybe_src_buf of
533 Nothing -> hGetStringBuffer src_filename
535 let loc = mkSrcLoc (mkFastString src_filename) 1 0
537 case unP parseModule (mkPState buf loc dflags) of {
539 PFailed span err -> return (Left (mkPlainErrMsg span err));
541 POk _ rdr_module -> do {
543 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
545 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
546 (ppSourceStats False rdr_module) ;
548 return (Right rdr_module)
549 -- ToDo: free the string buffer later.
553 myCoreToStg dflags this_mod prepd_binds
555 stg_binds <- _scc_ "Core2Stg"
556 coreToStg dflags prepd_binds
558 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
559 stg2stg dflags this_mod stg_binds
561 return (stg_binds2, cost_centre_info)
565 %************************************************************************
567 \subsection{Compiling a do-statement}
569 %************************************************************************
571 When the UnlinkedBCOExpr is linked you get an HValue of type
573 When you run it you get a list of HValues that should be
574 the same length as the list of names; add them to the ClosureEnv.
576 A naked expression returns a singleton Name [it].
578 What you type The IO [HValue] that hscStmt returns
579 ------------- ------------------------------------
580 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
583 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
586 expr (of IO type) ==> expr >>= \ v -> return [v]
587 [NB: result not printed] bindings: [it]
590 expr (of non-IO type,
591 result showable) ==> let v = expr in print v >> return [v]
594 expr (of non-IO type,
595 result not showable) ==> error
599 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
601 -> InteractiveContext -- Context for compiling
602 -> String -- The statement
603 -> IO (Maybe (InteractiveContext, [Name], HValue))
605 hscStmt hsc_env icontext stmt
606 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
607 ; case maybe_stmt of {
608 Nothing -> return Nothing ; -- Parse error
609 Just Nothing -> return Nothing ; -- Empty line
610 Just (Just parsed_stmt) -> do { -- The real stuff
612 -- Rename and typecheck it
614 <- tcRnStmt hsc_env icontext parsed_stmt
616 ; case maybe_tc_result of {
617 Nothing -> return Nothing ;
618 Just (new_ic, bound_names, tc_expr) -> do {
620 -- Then desugar, code gen, and link it
621 ; hval <- compileExpr hsc_env iNTERACTIVE
622 (ic_rn_gbl_env new_ic)
626 ; return (Just (new_ic, bound_names, hval))
629 hscTcExpr -- Typecheck an expression (but don't run it)
631 -> InteractiveContext -- Context for compiling
632 -> String -- The expression
635 hscTcExpr hsc_env icontext expr
636 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
637 ; case maybe_stmt of {
638 Nothing -> return Nothing ; -- Parse error
639 Just (Just (L _ (ExprStmt expr _)))
640 -> tcRnExpr hsc_env icontext expr ;
641 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
645 hscKcType -- Find the kind of a type
647 -> InteractiveContext -- Context for compiling
648 -> String -- The type
651 hscKcType hsc_env icontext str
652 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
653 ; case maybe_type of {
654 Just ty -> tcRnType hsc_env icontext ty ;
655 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
657 Nothing -> return Nothing } }
661 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
662 hscParseStmt = hscParseThing parseStmt
664 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
665 hscParseType = hscParseThing parseType
667 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
668 hscParseIdentifier = hscParseThing parseIdentifier
670 hscParseThing :: Outputable thing
672 -> DynFlags -> String
674 -- Nothing => Parse error (message already printed)
676 hscParseThing parser dflags str
677 = do showPass dflags "Parser"
680 buf <- stringToStringBuffer str
682 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
684 case unP parser (mkPState buf loc dflags) of {
686 PFailed span err -> do { printError span err;
691 --ToDo: can't free the string buffer until we've finished this
692 -- compilation sweep and all the identifiers have gone away.
693 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
699 %************************************************************************
701 \subsection{Getting information about an identifer}
703 %************************************************************************
707 type GetInfoResult = (String, (IfaceDecl, Fixity, SrcLoc, [(IfaceInst,SrcLoc)]))
709 hscGetInfo -- like hscStmt, but deals with a single identifier
711 -> InteractiveContext -- Context for compiling
712 -> String -- The identifier
713 -> IO [GetInfoResult]
715 hscGetInfo hsc_env ic str
716 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
717 case maybe_rdr_name of {
718 Nothing -> return [];
719 Just (L _ rdr_name) -> do
721 maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
723 let -- str' is the the naked occurrence name
724 -- after stripping off qualification and parens (+)
725 str' = occNameUserString (rdrNameOcc rdr_name)
727 case maybe_tc_result of {
728 Nothing -> return [] ;
729 Just things -> return [(str', t) | t <- things]
734 %************************************************************************
736 Desugar, simplify, convert to bytecode, and link an expression
738 %************************************************************************
742 compileExpr :: HscEnv
743 -> Module -> GlobalRdrEnv -> TypeEnv
747 compileExpr hsc_env this_mod rdr_env type_env tc_expr
748 = do { let { dflags = hsc_dflags hsc_env ;
749 lint_on = dopt Opt_DoCoreLinting dflags }
752 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
755 ; flat_expr <- flattenExpr hsc_env ds_expr
758 ; simpl_expr <- simplifyExpr dflags flat_expr
760 -- Tidy it (temporary, until coreSat does cloning)
761 ; tidy_expr <- tidyCoreExpr simpl_expr
763 -- Prepare for codegen
764 ; prepd_expr <- corePrepExpr dflags tidy_expr
767 -- ToDo: improve SrcLoc
769 case lintUnfolding noSrcLoc [] prepd_expr of
770 Just err -> pprPanic "compileExpr" err
776 ; bcos <- coreExprToBCOs dflags prepd_expr
779 ; hval <- linkExpr hsc_env bcos
787 %************************************************************************
789 Statistics on reading interfaces
791 %************************************************************************
794 dumpIfaceStats :: HscEnv -> IO ()
795 dumpIfaceStats hsc_env
796 = do { eps <- readIORef (hsc_EPS hsc_env)
797 ; dumpIfSet (dump_if_trace || dump_rn_stats)
798 "Interface statistics"
801 dflags = hsc_dflags hsc_env
802 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
803 dump_if_trace = dopt Opt_D_dump_if_trace dflags