2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
10 hscMain, newHscEnv, hscCmmFile,
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, GetInfoResult, 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 Module ( emptyModuleEnv )
46 import RdrName ( RdrName )
47 import HsSyn ( HsModule, LHsBinds )
48 import SrcLoc ( Located(..) )
49 import StringBuffer ( hGetStringBuffer )
51 import Lexer ( P(..), ParseResult(..), mkPState )
52 import SrcLoc ( mkSrcLoc )
53 import TcRnDriver ( tcRnModule, tcRnExtCore )
54 import TcRnTypes ( TcGblEnv(..) )
55 import TcIface ( typecheckIface )
56 import IfaceEnv ( initNameCache )
57 import LoadIface ( ifaceStats, initExternalPackageState )
58 import PrelInfo ( wiredInThings, basicKnownKeyNames )
59 import RdrName ( GlobalRdrEnv )
60 import MkIface ( checkOldIface, mkIface )
62 import Flattening ( flatten )
64 import TidyPgm ( tidyCorePgm )
65 import CorePrep ( corePrepPgm )
66 import CoreToStg ( coreToStg )
67 import Name ( Name, NamedThing(..) )
68 import SimplStg ( stg2stg )
69 import CodeGen ( codeGen )
70 import CmmParse ( parseCmmFile )
71 import CodeOutput ( codeOutput )
74 import DriverPhases ( HscSource(..) )
76 import UniqSupply ( mkSplitUniqSupply )
79 import HscStats ( ppSourceStats )
81 import MkExternalCore ( emitExternalCore )
83 import ParserCoreUtils
85 import Maybes ( expectJust )
86 import StringBuffer ( StringBuffer )
87 import Bag ( unitBag, emptyBag )
90 import Maybe ( isJust )
92 import DATA_IOREF ( newIORef, readIORef )
96 %************************************************************************
100 %************************************************************************
103 newHscEnv :: DynFlags -> IO HscEnv
105 = do { eps_var <- newIORef initExternalPackageState
106 ; us <- mkSplitUniqSupply 'r'
107 ; nc_var <- newIORef (initNameCache us knownKeyNames)
108 ; fc_var <- newIORef emptyModuleEnv
109 ; return (HscEnv { hsc_dflags = dflags,
112 hsc_IC = emptyInteractiveContext,
113 hsc_HPT = emptyHomePackageTable,
116 hsc_FC = fc_var } ) }
119 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
120 -- where templateHaskellNames are defined
121 knownKeyNames = map getName wiredInThings
122 ++ basicKnownKeyNames
124 ++ templateHaskellNames
129 %************************************************************************
131 The main compiler pipeline
133 %************************************************************************
137 -- Compilation failed
140 -- In IDE mode: we just do the static/dynamic checks
141 | HscChecked (Located (HsModule RdrName)) (Maybe (LHsBinds Id, GlobalRdrEnv))
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
163 -> MessageAction -- What to do with errors/warnings
165 -> Bool -- True <=> source unchanged
166 -> Bool -- True <=> have an object file (for msgs only)
167 -> Maybe ModIface -- Old interface, if available
170 hscMain hsc_env msg_act mod_summary
171 source_unchanged have_object maybe_old_iface
173 (recomp_reqd, maybe_checked_iface) <-
174 {-# SCC "checkOldIface" #-}
175 checkOldIface hsc_env mod_summary
176 source_unchanged maybe_old_iface;
178 let no_old_iface = not (isJust maybe_checked_iface)
179 what_next | recomp_reqd || no_old_iface = hscRecomp
180 | otherwise = hscNoRecomp
182 ; what_next hsc_env msg_act mod_summary have_object
187 ------------------------------
188 -- hscNoRecomp definitely expects to have the old interface available
189 hscNoRecomp hsc_env msg_act mod_summary
190 have_object (Just old_iface)
191 | isOneShot (ghcMode (hsc_dflags hsc_env))
193 compilationProgressMsg (hsc_dflags hsc_env) $
194 "compilation IS NOT required";
195 dumpIfaceStats hsc_env ;
197 let { bomb = panic "hscNoRecomp:OneShot" };
198 return (HscNoRecomp bomb bomb)
201 = do { compilationProgressMsg (hsc_dflags hsc_env) $
202 ("Skipping " ++ showModMsg have_object mod_summary)
204 ; new_details <- {-# SCC "tcRnIface" #-}
205 typecheckIface hsc_env old_iface ;
206 ; dumpIfaceStats hsc_env
208 ; return (HscNoRecomp new_details old_iface)
211 ------------------------------
212 hscRecomp hsc_env msg_act mod_summary
213 have_object maybe_checked_iface
214 = case ms_hsc_src mod_summary of
216 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
217 hscBackEnd hsc_env mod_summary maybe_checked_iface front_res
220 front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
221 hscBootBackEnd hsc_env mod_summary maybe_checked_iface front_res
224 front_res <- hscCoreFrontEnd hsc_env msg_act mod_summary
225 hscBackEnd hsc_env mod_summary maybe_checked_iface front_res
227 hscCoreFrontEnd hsc_env msg_act mod_summary = do {
231 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
232 ; case parseCore inp 1 of
233 FailP s -> putMsg s{-ToDo: wrong-} >> return Nothing
234 OkP rdr_module -> do {
237 -- RENAME and TYPECHECK
239 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
240 tcRnExtCore hsc_env rdr_module
242 ; case maybe_tc_result of
243 Nothing -> return Nothing
244 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
248 hscFileFrontEnd hsc_env msg_act mod_summary = do {
250 -- DISPLAY PROGRESS MESSAGE
252 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
253 ; let dflags = hsc_dflags hsc_env
254 ; let toInterp = hscTarget dflags == HscInterpreted
255 ; when (not one_shot) $
256 compilationProgressMsg dflags $
257 ("Compiling " ++ showModMsg (not toInterp) mod_summary)
262 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
263 hspp_buf = ms_hspp_buf mod_summary
265 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
267 ; case maybe_parsed of {
268 Left err -> do { msg_act (unitBag err, emptyBag)
270 Right rdr_module -> do {
273 -- RENAME and TYPECHECK
275 (tc_msgs, maybe_tc_result)
276 <- {-# SCC "Typecheck-Rename" #-}
277 tcRnModule hsc_env (ms_hsc_src mod_summary) rdr_module
280 ; case maybe_tc_result of {
281 Nothing -> return Nothing ;
282 Just tc_result -> do {
287 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
288 deSugar hsc_env tc_result
289 ; msg_act (warns, emptyBag)
290 ; case maybe_ds_result of
291 Nothing -> return Nothing
292 Just ds_result -> return (Just ds_result)
295 ------------------------------
297 hscFileCheck :: HscEnv -> MessageAction -> ModSummary -> IO HscResult
298 hscFileCheck hsc_env msg_act mod_summary = do {
302 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
303 hspp_buf = ms_hspp_buf mod_summary
305 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
307 ; case maybe_parsed of {
308 Left err -> do { msg_act (unitBag err, emptyBag)
310 Right rdr_module -> do {
313 -- RENAME and TYPECHECK
315 (tc_msgs, maybe_tc_result)
316 <- _scc_ "Typecheck-Rename"
317 tcRnModule hsc_env (ms_hsc_src mod_summary) rdr_module
320 ; case maybe_tc_result of {
321 Nothing -> return (HscChecked rdr_module Nothing);
322 Just tc_result -> return (HscChecked rdr_module
323 (Just (tcg_binds tc_result,
324 tcg_rdr_env tc_result)))
327 ------------------------------
328 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
329 -- For hs-boot files, there's no code generation to do
331 hscBootBackEnd hsc_env mod_summary maybe_checked_iface Nothing
333 hscBootBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
334 = do { final_iface <- {-# SCC "MkFinalIface" #-}
335 mkIface hsc_env (ms_location mod_summary)
336 maybe_checked_iface ds_result
338 ; let { final_details = ModDetails { md_types = mg_types ds_result,
339 md_insts = mg_insts ds_result,
340 md_rules = mg_rules ds_result } }
341 -- And the answer is ...
342 ; dumpIfaceStats hsc_env
344 ; return (HscRecomp final_details
349 ------------------------------
350 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
352 hscBackEnd hsc_env mod_summary maybe_checked_iface Nothing
355 hscBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
357 -- ; seqList imported_modules (return ())
359 let one_shot = isOneShot (ghcMode dflags)
360 dflags = hsc_dflags hsc_env
365 ; flat_result <- {-# SCC "Flattening" #-}
366 flatten hsc_env ds_result
369 {- TEMP: need to review space-leak fixing here
370 NB: even the code generator can force one of the
371 thunks for constructor arguments, for newtypes in particular
373 ; let -- Rule-base accumulated from imported packages
374 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
376 -- In one-shot mode, ZAP the external package state at
377 -- this point, because we aren't going to need it from
378 -- now on. We keep the name cache, however, because
379 -- tidyCore needs it.
381 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
384 ; pkg_rule_base `seq` pcs_middle `seq` return ()
387 -- alive at this point:
395 ; simpl_result <- {-# SCC "Core2Core" #-}
396 core2core hsc_env flat_result
401 ; tidy_result <- {-# SCC "CoreTidy" #-}
402 tidyCorePgm hsc_env simpl_result
404 -- Emit external core
405 ; emitExternalCore dflags tidy_result
407 -- Alive at this point:
408 -- tidy_result, pcs_final
412 -- BUILD THE NEW ModIface and ModDetails
413 -- and emit external core if necessary
414 -- This has to happen *after* code gen so that the back-end
415 -- info has been set. Not yet clear if it matters waiting
416 -- until after code output
417 ; new_iface <- {-# SCC "MkFinalIface" #-}
418 mkIface hsc_env (ms_location mod_summary)
419 maybe_checked_iface tidy_result
421 -- Space leak reduction: throw away the new interface if
422 -- we're in one-shot mode; we won't be needing it any
425 if one_shot then return (error "no final iface")
426 else return new_iface
428 -- Build the final ModDetails (except in one-shot mode, where
429 -- we won't need this information after compilation).
431 if one_shot then return (error "no final details")
432 else return $! ModDetails {
433 md_types = mg_types tidy_result,
434 md_insts = mg_insts tidy_result,
435 md_rules = mg_rules tidy_result }
438 -- CONVERT TO STG and COMPLETE CODE GENERATION
439 ; (stub_h_exists, stub_c_exists, maybe_bcos)
440 <- hscCodeGen dflags tidy_result
442 -- And the answer is ...
443 ; dumpIfaceStats hsc_env
445 ; return (HscRecomp final_details
447 stub_h_exists stub_c_exists
454 ModGuts{ -- This is the last use of the ModGuts in a compilation.
455 -- From now on, we just use the bits we need.
456 mg_module = this_mod,
457 mg_binds = core_binds,
459 mg_dir_imps = dir_imps,
460 mg_foreign = foreign_stubs,
461 mg_deps = dependencies } = do {
464 -- PREPARE FOR CODE GENERATION
465 -- Do saturation and convert to A-normal form
466 prepd_binds <- {-# SCC "CorePrep" #-}
467 corePrepPgm dflags core_binds type_env;
469 case hscTarget dflags of
470 HscNothing -> return (False, False, Nothing)
474 do ----------------- Generate byte code ------------------
475 comp_bc <- byteCodeGen dflags prepd_binds type_env
477 ------------------ Create f-x-dynamic C-side stuff ---
478 (istub_h_exists, istub_c_exists)
479 <- outputForeignStubs dflags foreign_stubs
481 return ( istub_h_exists, istub_c_exists, Just comp_bc )
483 panic "GHC not compiled with interpreter"
488 ----------------- Convert to STG ------------------
489 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
490 myCoreToStg dflags this_mod prepd_binds
492 ------------------ Code generation ------------------
493 abstractC <- {-# SCC "CodeGen" #-}
494 codeGen dflags this_mod type_env foreign_stubs
495 dir_imps cost_centre_info stg_binds
497 ------------------ Code output -----------------------
498 (stub_h_exists, stub_c_exists)
499 <- codeOutput dflags this_mod foreign_stubs
500 dependencies abstractC
502 return (stub_h_exists, stub_c_exists, Nothing)
506 hscCmmFile :: DynFlags -> FilePath -> IO Bool
507 hscCmmFile dflags filename = do
508 maybe_cmm <- parseCmmFile dflags filename
510 Nothing -> return False
512 codeOutput dflags no_mod NoStubs noDependencies [cmm]
515 no_mod = panic "hscCmmFile: no_mod"
518 myParseModule dflags src_filename maybe_src_buf
519 = -------------------------- Parser ----------------
520 showPass dflags "Parser" >>
521 {-# SCC "Parser" #-} do
523 -- sometimes we already have the buffer in memory, perhaps
524 -- because we needed to parse the imports out of it, or get the
526 buf <- case maybe_src_buf of
528 Nothing -> hGetStringBuffer src_filename
530 let loc = mkSrcLoc (mkFastString src_filename) 1 0
532 case unP parseModule (mkPState buf loc dflags) of {
534 PFailed span err -> return (Left (mkPlainErrMsg span err));
536 POk _ rdr_module -> do {
538 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
540 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
541 (ppSourceStats False rdr_module) ;
543 return (Right rdr_module)
544 -- ToDo: free the string buffer later.
548 myCoreToStg dflags this_mod prepd_binds
550 stg_binds <- {-# SCC "Core2Stg" #-}
551 coreToStg dflags prepd_binds
553 (stg_binds2, cost_centre_info) <- {-# SCC "Core2Stg" #-}
554 stg2stg dflags this_mod stg_binds
556 return (stg_binds2, cost_centre_info)
560 %************************************************************************
562 \subsection{Compiling a do-statement}
564 %************************************************************************
566 When the UnlinkedBCOExpr is linked you get an HValue of type
568 When you run it you get a list of HValues that should be
569 the same length as the list of names; add them to the ClosureEnv.
571 A naked expression returns a singleton Name [it].
573 What you type The IO [HValue] that hscStmt returns
574 ------------- ------------------------------------
575 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
578 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
581 expr (of IO type) ==> expr >>= \ v -> return [v]
582 [NB: result not printed] bindings: [it]
585 expr (of non-IO type,
586 result showable) ==> let v = expr in print v >> return [v]
589 expr (of non-IO type,
590 result not showable) ==> error
594 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
596 -> String -- The statement
597 -> IO (Maybe (HscEnv, [Name], HValue))
600 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
601 ; case maybe_stmt of {
602 Nothing -> return Nothing ; -- Parse error
603 Just Nothing -> return Nothing ; -- Empty line
604 Just (Just parsed_stmt) -> do { -- The real stuff
606 -- Rename and typecheck it
607 let icontext = hsc_IC hsc_env
608 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
610 ; case maybe_tc_result of {
611 Nothing -> return Nothing ;
612 Just (new_ic, bound_names, tc_expr) -> do {
614 -- Then desugar, code gen, and link it
615 ; hval <- compileExpr hsc_env iNTERACTIVE
616 (ic_rn_gbl_env new_ic)
620 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
623 hscTcExpr -- Typecheck an expression (but don't run it)
625 -> String -- The expression
628 hscTcExpr hsc_env expr
629 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
630 ; let icontext = hsc_IC hsc_env
631 ; case maybe_stmt of {
632 Nothing -> return Nothing ; -- Parse error
633 Just (Just (L _ (ExprStmt expr _)))
634 -> tcRnExpr hsc_env icontext expr ;
635 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
639 hscKcType -- Find the kind of a type
641 -> String -- The type
644 hscKcType hsc_env str
645 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
646 ; let icontext = hsc_IC hsc_env
647 ; case maybe_type of {
648 Just ty -> tcRnType hsc_env icontext ty ;
649 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
651 Nothing -> return Nothing } }
655 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
656 hscParseStmt = hscParseThing parseStmt
658 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
659 hscParseType = hscParseThing parseType
661 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
662 hscParseIdentifier = hscParseThing parseIdentifier
664 hscParseThing :: Outputable thing
666 -> DynFlags -> String
668 -- Nothing => Parse error (message already printed)
670 hscParseThing parser dflags str
671 = showPass dflags "Parser" >>
672 {-# SCC "Parser" #-} do
674 buf <- stringToStringBuffer str
676 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
678 case unP parser (mkPState buf loc dflags) of {
680 PFailed span err -> do { printError span err;
685 --ToDo: can't free the string buffer until we've finished this
686 -- compilation sweep and all the identifiers have gone away.
687 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
693 %************************************************************************
695 \subsection{Getting information about an identifer}
697 %************************************************************************
701 hscGetInfo -- like hscStmt, but deals with a single identifier
703 -> String -- The identifier
704 -> IO [GetInfoResult]
706 hscGetInfo hsc_env str
707 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
708 case maybe_rdr_name of {
709 Nothing -> return [];
710 Just (L _ rdr_name) -> do
712 maybe_tc_result <- tcRnGetInfo hsc_env (hsc_IC hsc_env) rdr_name
714 case maybe_tc_result of
716 Just things -> return things
721 %************************************************************************
723 Desugar, simplify, convert to bytecode, and link an expression
725 %************************************************************************
729 compileExpr :: HscEnv
730 -> Module -> GlobalRdrEnv -> TypeEnv
734 compileExpr hsc_env this_mod rdr_env type_env tc_expr
735 = do { let { dflags = hsc_dflags hsc_env ;
736 lint_on = dopt Opt_DoCoreLinting dflags }
739 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
742 ; flat_expr <- flattenExpr hsc_env ds_expr
745 ; simpl_expr <- simplifyExpr dflags flat_expr
747 -- Tidy it (temporary, until coreSat does cloning)
748 ; tidy_expr <- tidyCoreExpr simpl_expr
750 -- Prepare for codegen
751 ; prepd_expr <- corePrepExpr dflags tidy_expr
754 -- ToDo: improve SrcLoc
756 case lintUnfolding noSrcLoc [] prepd_expr of
757 Just err -> pprPanic "compileExpr" err
763 ; bcos <- coreExprToBCOs dflags prepd_expr
766 ; hval <- linkExpr hsc_env bcos
774 %************************************************************************
776 Statistics on reading interfaces
778 %************************************************************************
781 dumpIfaceStats :: HscEnv -> IO ()
782 dumpIfaceStats hsc_env
783 = do { eps <- readIORef (hsc_EPS hsc_env)
784 ; dumpIfSet (dump_if_trace || dump_rn_stats)
785 "Interface statistics"
788 dflags = hsc_dflags hsc_env
789 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
790 dump_if_trace = dopt Opt_D_dump_if_trace dflags