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, 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 )
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 TcGblEnv)
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
215 HsSrcFile -> do { front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
216 ; hscBackEnd hsc_env mod_summary maybe_checked_iface front_res }
218 HsBootFile -> do { front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
219 ; hscBootBackEnd hsc_env mod_summary maybe_checked_iface front_res }
221 ExtCoreFile -> do { front_res <- hscCoreFrontEnd hsc_env msg_act mod_summary
222 ; hscBackEnd hsc_env mod_summary maybe_checked_iface front_res }
224 hscCoreFrontEnd hsc_env msg_act mod_summary = do {
228 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
229 ; case parseCore inp 1 of
230 FailP s -> putMsg s{-ToDo: wrong-} >> return Nothing
231 OkP rdr_module -> do {
234 -- RENAME and TYPECHECK
236 ; (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
237 tcRnExtCore hsc_env rdr_module
239 ; case maybe_tc_result of
240 Nothing -> return Nothing
241 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
245 hscFileFrontEnd hsc_env msg_act mod_summary = do {
247 -- DISPLAY PROGRESS MESSAGE
249 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
250 ; let dflags = hsc_dflags hsc_env
251 ; let toInterp = hscTarget dflags == HscInterpreted
252 ; when (not one_shot) $
253 compilationProgressMsg dflags $
254 ("Compiling " ++ showModMsg (not toInterp) mod_summary)
259 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
260 hspp_buf = ms_hspp_buf mod_summary
262 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
264 ; case maybe_parsed of {
265 Left err -> do { msg_act (unitBag err, emptyBag)
267 Right rdr_module -> do {
270 -- RENAME and TYPECHECK
272 (tc_msgs, maybe_tc_result)
273 <- {-# SCC "Typecheck-Rename" #-}
274 tcRnModule hsc_env (ms_hsc_src mod_summary) rdr_module
277 ; case maybe_tc_result of {
278 Nothing -> return Nothing ;
279 Just tc_result -> do {
284 ; (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
285 deSugar hsc_env tc_result
286 ; msg_act (warns, emptyBag)
287 ; case maybe_ds_result of
288 Nothing -> return Nothing
289 Just ds_result -> return (Just ds_result)
292 ------------------------------
293 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
294 -- For hs-boot files, there's no code generation to do
296 hscBootBackEnd hsc_env mod_summary maybe_checked_iface Nothing
298 hscBootBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
299 = do { final_iface <- {-# SCC "MkFinalIface" #-}
300 mkIface hsc_env (ms_location mod_summary)
301 maybe_checked_iface ds_result
303 ; let { final_details = ModDetails { md_types = mg_types ds_result,
304 md_insts = mg_insts ds_result,
305 md_rules = mg_rules ds_result } }
306 -- And the answer is ...
307 ; dumpIfaceStats hsc_env
309 ; return (HscRecomp final_details
314 ------------------------------
315 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
317 hscBackEnd hsc_env mod_summary maybe_checked_iface Nothing
320 hscBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
322 -- ; seqList imported_modules (return ())
324 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
325 dflags = hsc_dflags hsc_env
330 ; flat_result <- {-# SCC "Flattening" #-}
331 flatten hsc_env ds_result
334 {- TEMP: need to review space-leak fixing here
335 NB: even the code generator can force one of the
336 thunks for constructor arguments, for newtypes in particular
338 ; let -- Rule-base accumulated from imported packages
339 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
341 -- In one-shot mode, ZAP the external package state at
342 -- this point, because we aren't going to need it from
343 -- now on. We keep the name cache, however, because
344 -- tidyCore needs it.
346 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
349 ; pkg_rule_base `seq` pcs_middle `seq` return ()
352 -- alive at this point:
360 ; simpl_result <- {-# SCC "Core2Core" #-}
361 core2core hsc_env flat_result
366 ; tidy_result <- {-# SCC "CoreTidy" #-}
367 tidyCorePgm hsc_env simpl_result
369 -- Emit external core
370 ; emitExternalCore dflags tidy_result
372 -- Alive at this point:
373 -- tidy_result, pcs_final
377 -- BUILD THE NEW ModIface and ModDetails
378 -- and emit external core if necessary
379 -- This has to happen *after* code gen so that the back-end
380 -- info has been set. Not yet clear if it matters waiting
381 -- until after code output
382 ; new_iface <- {-# SCC "MkFinalIface" #-}
383 mkIface hsc_env (ms_location mod_summary)
384 maybe_checked_iface tidy_result
386 -- Space leak reduction: throw away the new interface if
387 -- we're in one-shot mode; we won't be needing it any
390 if one_shot then return (error "no final iface")
391 else return new_iface
393 -- Build the final ModDetails (except in one-shot mode, where
394 -- we won't need this information after compilation).
396 if one_shot then return (error "no final details")
397 else return $! ModDetails {
398 md_types = mg_types tidy_result,
399 md_insts = mg_insts tidy_result,
400 md_rules = mg_rules tidy_result }
403 -- CONVERT TO STG and COMPLETE CODE GENERATION
404 ; (stub_h_exists, stub_c_exists, maybe_bcos)
405 <- hscCodeGen dflags tidy_result
407 -- And the answer is ...
408 ; dumpIfaceStats hsc_env
410 ; return (HscRecomp final_details
412 stub_h_exists stub_c_exists
417 hscFileCheck hsc_env msg_act hspp_file = do {
421 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file Nothing
423 ; case maybe_parsed of {
424 Left err -> do { msg_act (unitBag err, emptyBag) ;
427 Right rdr_module -> hscBufferTypecheck hsc_env rdr_module msg_act
431 -- Perform static/dynamic checks on the source code in a StringBuffer
432 -- This is a temporary solution: it'll read in interface files lazily, whereas
433 -- we probably want to use the compilation manager to load in all the modules
435 hscBufferCheck :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
436 hscBufferCheck hsc_env buffer msg_act = do
437 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
438 showPass (hsc_dflags hsc_env) "Parser"
439 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
440 PFailed span err -> do
441 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
443 POk _ rdr_module -> do
444 hscBufferTypecheck hsc_env rdr_module msg_act
446 hscBufferTypecheck hsc_env rdr_module msg_act = do
447 (tc_msgs, maybe_tc_result) <- {-# SCC "Typecheck-Rename" #-}
448 tcRnModule hsc_env HsSrcFile rdr_module
450 case maybe_tc_result of
451 Nothing -> return (HscChecked rdr_module Nothing)
452 -- space leak on rdr_module!
453 Just r -> return (HscChecked rdr_module (Just r))
457 ModGuts{ -- This is the last use of the ModGuts in a compilation.
458 -- From now on, we just use the bits we need.
459 mg_module = this_mod,
460 mg_binds = core_binds,
462 mg_dir_imps = dir_imps,
463 mg_foreign = foreign_stubs,
464 mg_deps = dependencies } = do {
467 -- PREPARE FOR CODE GENERATION
468 -- Do saturation and convert to A-normal form
469 prepd_binds <- {-# SCC "CorePrep" #-}
470 corePrepPgm dflags core_binds type_env;
472 case hscTarget dflags of
473 HscNothing -> return (False, False, Nothing)
477 do ----------------- Generate byte code ------------------
478 comp_bc <- byteCodeGen dflags prepd_binds type_env
480 ------------------ Create f-x-dynamic C-side stuff ---
481 (istub_h_exists, istub_c_exists)
482 <- outputForeignStubs dflags foreign_stubs
484 return ( istub_h_exists, istub_c_exists, Just comp_bc )
486 panic "GHC not compiled with interpreter"
491 ----------------- Convert to STG ------------------
492 (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-}
493 myCoreToStg dflags this_mod prepd_binds
495 ------------------ Code generation ------------------
496 abstractC <- {-# SCC "CodeGen" #-}
497 codeGen dflags this_mod type_env foreign_stubs
498 dir_imps cost_centre_info stg_binds
500 ------------------ Code output -----------------------
501 (stub_h_exists, stub_c_exists)
502 <- codeOutput dflags this_mod foreign_stubs
503 dependencies abstractC
505 return (stub_h_exists, stub_c_exists, Nothing)
509 hscCmmFile :: DynFlags -> FilePath -> IO Bool
510 hscCmmFile dflags filename = do
511 maybe_cmm <- parseCmmFile dflags filename
513 Nothing -> return False
515 codeOutput dflags no_mod NoStubs noDependencies [cmm]
518 no_mod = panic "hscCmmFile: no_mod"
521 myParseModule dflags src_filename maybe_src_buf
522 = -------------------------- Parser ----------------
523 showPass dflags "Parser" >>
524 {-# SCC "Parser" #-} do
526 -- sometimes we already have the buffer in memory, perhaps
527 -- because we needed to parse the imports out of it, or get the
529 buf <- case maybe_src_buf of
531 Nothing -> hGetStringBuffer src_filename
533 let loc = mkSrcLoc (mkFastString src_filename) 1 0
535 case unP parseModule (mkPState buf loc dflags) of {
537 PFailed span err -> return (Left (mkPlainErrMsg span err));
539 POk _ rdr_module -> do {
541 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
543 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
544 (ppSourceStats False rdr_module) ;
546 return (Right rdr_module)
547 -- ToDo: free the string buffer later.
551 myCoreToStg dflags this_mod prepd_binds
553 stg_binds <- {-# SCC "Core2Stg" #-}
554 coreToStg dflags prepd_binds
556 (stg_binds2, cost_centre_info) <- {-# SCC "Core2Stg" #-}
557 stg2stg dflags this_mod stg_binds
559 return (stg_binds2, cost_centre_info)
563 %************************************************************************
565 \subsection{Compiling a do-statement}
567 %************************************************************************
569 When the UnlinkedBCOExpr is linked you get an HValue of type
571 When you run it you get a list of HValues that should be
572 the same length as the list of names; add them to the ClosureEnv.
574 A naked expression returns a singleton Name [it].
576 What you type The IO [HValue] that hscStmt returns
577 ------------- ------------------------------------
578 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
581 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
584 expr (of IO type) ==> expr >>= \ v -> return [v]
585 [NB: result not printed] bindings: [it]
588 expr (of non-IO type,
589 result showable) ==> let v = expr in print v >> return [v]
592 expr (of non-IO type,
593 result not showable) ==> error
597 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
599 -> String -- The statement
600 -> IO (Maybe (HscEnv, [Name], HValue))
603 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
604 ; case maybe_stmt of {
605 Nothing -> return Nothing ; -- Parse error
606 Just Nothing -> return Nothing ; -- Empty line
607 Just (Just parsed_stmt) -> do { -- The real stuff
609 -- Rename and typecheck it
610 let icontext = hsc_IC hsc_env
611 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
613 ; case maybe_tc_result of {
614 Nothing -> return Nothing ;
615 Just (new_ic, bound_names, tc_expr) -> do {
617 -- Then desugar, code gen, and link it
618 ; hval <- compileExpr hsc_env iNTERACTIVE
619 (ic_rn_gbl_env new_ic)
623 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
626 hscTcExpr -- Typecheck an expression (but don't run it)
628 -> String -- The expression
631 hscTcExpr hsc_env expr
632 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
633 ; let icontext = hsc_IC hsc_env
634 ; case maybe_stmt of {
635 Nothing -> return Nothing ; -- Parse error
636 Just (Just (L _ (ExprStmt expr _)))
637 -> tcRnExpr hsc_env icontext expr ;
638 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
642 hscKcType -- Find the kind of a type
644 -> String -- The type
647 hscKcType hsc_env str
648 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
649 ; let icontext = hsc_IC hsc_env
650 ; case maybe_type of {
651 Just ty -> tcRnType hsc_env icontext ty ;
652 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
654 Nothing -> return Nothing } }
658 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
659 hscParseStmt = hscParseThing parseStmt
661 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
662 hscParseType = hscParseThing parseType
664 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
665 hscParseIdentifier = hscParseThing parseIdentifier
667 hscParseThing :: Outputable thing
669 -> DynFlags -> String
671 -- Nothing => Parse error (message already printed)
673 hscParseThing parser dflags str
674 = showPass dflags "Parser" >>
675 {-# SCC "Parser" #-} do
677 buf <- stringToStringBuffer str
679 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
681 case unP parser (mkPState buf loc dflags) of {
683 PFailed span err -> do { printError span err;
688 --ToDo: can't free the string buffer until we've finished this
689 -- compilation sweep and all the identifiers have gone away.
690 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
696 %************************************************************************
698 \subsection{Getting information about an identifer}
700 %************************************************************************
704 hscGetInfo -- like hscStmt, but deals with a single identifier
706 -> String -- The identifier
707 -> IO [GetInfoResult]
709 hscGetInfo hsc_env str
710 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
711 case maybe_rdr_name of {
712 Nothing -> return [];
713 Just (L _ rdr_name) -> do
715 maybe_tc_result <- tcRnGetInfo hsc_env (hsc_IC hsc_env) rdr_name
717 case maybe_tc_result of
719 Just things -> return things
724 %************************************************************************
726 Desugar, simplify, convert to bytecode, and link an expression
728 %************************************************************************
732 compileExpr :: HscEnv
733 -> Module -> GlobalRdrEnv -> TypeEnv
737 compileExpr hsc_env this_mod rdr_env type_env tc_expr
738 = do { let { dflags = hsc_dflags hsc_env ;
739 lint_on = dopt Opt_DoCoreLinting dflags }
742 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
745 ; flat_expr <- flattenExpr hsc_env ds_expr
748 ; simpl_expr <- simplifyExpr dflags flat_expr
750 -- Tidy it (temporary, until coreSat does cloning)
751 ; tidy_expr <- tidyCoreExpr simpl_expr
753 -- Prepare for codegen
754 ; prepd_expr <- corePrepExpr dflags tidy_expr
757 -- ToDo: improve SrcLoc
759 case lintUnfolding noSrcLoc [] prepd_expr of
760 Just err -> pprPanic "compileExpr" err
766 ; bcos <- coreExprToBCOs dflags prepd_expr
769 ; hval <- linkExpr hsc_env bcos
777 %************************************************************************
779 Statistics on reading interfaces
781 %************************************************************************
784 dumpIfaceStats :: HscEnv -> IO ()
785 dumpIfaceStats hsc_env
786 = do { eps <- readIORef (hsc_EPS hsc_env)
787 ; dumpIfSet (dump_if_trace || dump_rn_stats)
788 "Interface statistics"
791 dflags = hsc_dflags hsc_env
792 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
793 dump_if_trace = dopt Opt_D_dump_if_trace dflags