2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 HscResult(..), HscCheckResult(..) ,
10 hscMain, newHscEnv, hscCmmFile, hscBufferFrontEnd
12 , hscStmt, hscTcExpr, hscKcType
13 , hscGetInfo, GetInfoResult
18 #include "HsVersions.h"
21 import HsSyn ( Stmt(..), LStmt, LHsExpr, LHsType )
22 import IfaceSyn ( IfaceDecl, IfaceInst )
23 import CodeOutput ( outputForeignStubs )
24 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
25 import Linker ( HValue, linkExpr )
26 import TidyPgm ( tidyCoreExpr )
27 import CorePrep ( corePrepExpr )
28 import Flattening ( flattenExpr )
29 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnGetInfo, tcRnType )
30 import RdrName ( rdrNameOcc )
31 import OccName ( occNameUserString )
33 import PrelNames ( iNTERACTIVE )
34 import StringBuffer ( stringToStringBuffer )
37 import CoreLint ( lintUnfolding )
38 import DsMeta ( templateHaskellNames )
39 import BasicTypes ( Fixity )
42 import RdrName ( RdrName )
43 import HsSyn ( HsModule )
44 import SrcLoc ( SrcLoc, noSrcLoc, Located(..) )
45 import StringBuffer ( hGetStringBuffer )
47 import Lexer ( P(..), ParseResult(..), mkPState )
48 import SrcLoc ( mkSrcLoc )
49 import TcRnDriver ( tcRnModule, tcRnExtCore )
50 import TcRnTypes ( TcGblEnv )
51 import TcIface ( typecheckIface )
52 import IfaceEnv ( initNameCache )
53 import LoadIface ( ifaceStats, initExternalPackageState )
54 import PrelInfo ( wiredInThings, basicKnownKeyNames )
55 import RdrName ( GlobalRdrEnv )
56 import MkIface ( checkOldIface, mkIface )
58 import Flattening ( flatten )
60 import TidyPgm ( tidyCorePgm )
61 import CorePrep ( corePrepPgm )
62 import CoreToStg ( coreToStg )
63 import Name ( Name, NamedThing(..) )
64 import SimplStg ( stg2stg )
65 import CodeGen ( codeGen )
66 import CmmParse ( parseCmmFile )
67 import CodeOutput ( codeOutput )
70 import DriverPhases ( isExtCoreFilename )
72 import UniqSupply ( mkSplitUniqSupply )
75 import HscStats ( ppSourceStats )
77 import MkExternalCore ( emitExternalCore )
79 import ParserCoreUtils
80 import Module ( Module, ModLocation(..), showModMsg )
82 import Maybes ( expectJust )
83 import StringBuffer ( StringBuffer )
84 import Bag ( unitBag, emptyBag )
87 import Maybe ( isJust, fromJust )
89 import DATA_IOREF ( newIORef, readIORef )
93 %************************************************************************
97 %************************************************************************
100 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
101 newHscEnv ghci_mode dflags
102 = do { eps_var <- newIORef initExternalPackageState
103 ; us <- mkSplitUniqSupply 'r'
104 ; nc_var <- newIORef (initNameCache us knownKeyNames)
105 ; return (HscEnv { hsc_mode = ghci_mode,
107 hsc_HPT = emptyHomePackageTable,
109 hsc_NC = nc_var } ) }
112 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
113 -- where templateHaskellNames are defined
114 knownKeyNames = map getName wiredInThings
115 ++ basicKnownKeyNames
117 ++ templateHaskellNames
122 %************************************************************************
124 The main compiler pipeline
126 %************************************************************************
130 -- Compilation failed
133 -- In IDE mode: we just do the static/dynamic checks
134 | HscChecked HscCheckResult
136 -- Concluded that it wasn't necessary
137 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
138 ModIface -- new iface (if any compilation was done)
141 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
143 ModIface -- new iface (if any compilation was done)
144 Bool -- stub_h exists
145 Bool -- stub_c exists
146 (Maybe CompiledByteCode)
149 -- The result when we're just checking (in an IDE editor, for example)
151 = HscParsed (Located (HsModule RdrName))
152 -- renaming/typechecking failed, here's the parse tree
153 | HscTypechecked TcGblEnv
154 -- renaming/typechecking succeeded
156 -- What to do when we have compiler error or warning messages
157 type MessageAction = Messages -> IO ()
159 -- no errors or warnings; the individual passes
160 -- (parse/rename/typecheck) print messages themselves
164 -> MessageAction -- what to do with errors/warnings
166 -> ModLocation -- location info
167 -> Bool -- True <=> source unchanged
168 -> Bool -- True <=> have an object file (for msgs only)
169 -> Maybe ModIface -- old interface, if available
172 hscMain hsc_env msg_act mod location
173 source_unchanged have_object maybe_old_iface
175 (recomp_reqd, maybe_checked_iface) <-
176 _scc_ "checkOldIface"
177 checkOldIface hsc_env mod
178 (ml_hi_file location)
179 source_unchanged maybe_old_iface;
181 let no_old_iface = not (isJust maybe_checked_iface)
182 what_next | recomp_reqd || no_old_iface = hscRecomp
183 | otherwise = hscNoRecomp
185 ; what_next hsc_env msg_act have_object
186 mod location maybe_checked_iface
190 -- hscNoRecomp definitely expects to have the old interface available
191 hscNoRecomp hsc_env msg_act have_object
192 mod location (Just old_iface)
193 | isOneShot (hsc_mode hsc_env)
195 compilationProgressMsg (hsc_dflags hsc_env) $
196 "compilation IS NOT required";
197 dumpIfaceStats hsc_env ;
199 let { bomb = panic "hscNoRecomp:OneShot" };
200 return (HscNoRecomp bomb bomb)
204 compilationProgressMsg (hsc_dflags hsc_env) $
205 ("Skipping " ++ showModMsg have_object mod location);
207 new_details <- _scc_ "tcRnIface"
208 typecheckIface hsc_env old_iface ;
209 dumpIfaceStats hsc_env ;
211 return (HscNoRecomp new_details old_iface)
214 hscRecomp hsc_env msg_act have_object
215 mod location maybe_checked_iface
217 -- what target are we shooting for?
218 ; let one_shot = isOneShot (hsc_mode hsc_env)
219 ; let dflags = hsc_dflags hsc_env
220 ; let toInterp = dopt_HscLang dflags == HscInterpreted
221 ; let toCore = isJust (ml_hs_file location) &&
222 isExtCoreFilename (fromJust (ml_hs_file location))
224 ; when (not one_shot) $
225 compilationProgressMsg dflags $
226 ("Compiling " ++ showModMsg (not toInterp) mod location);
228 ; front_res <- if toCore then
229 hscCoreFrontEnd hsc_env msg_act location
231 hscFileFrontEnd hsc_env msg_act location
234 Left flure -> return flure;
235 Right ds_result -> do {
239 -- ; seqList imported_modules (return ())
244 ; flat_result <- _scc_ "Flattening"
245 flatten hsc_env ds_result
248 {- TEMP: need to review space-leak fixing here
249 NB: even the code generator can force one of the
250 thunks for constructor arguments, for newtypes in particular
252 ; let -- Rule-base accumulated from imported packages
253 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
255 -- In one-shot mode, ZAP the external package state at
256 -- this point, because we aren't going to need it from
257 -- now on. We keep the name cache, however, because
258 -- tidyCore needs it.
260 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
263 ; pkg_rule_base `seq` pcs_middle `seq` return ()
266 -- alive at this point:
274 ; simpl_result <- _scc_ "Core2Core"
275 core2core hsc_env flat_result
280 ; tidy_result <- _scc_ "CoreTidy"
281 tidyCorePgm hsc_env simpl_result
283 -- Emit external core
284 ; emitExternalCore dflags tidy_result
286 -- Alive at this point:
287 -- tidy_result, pcs_final
291 -- BUILD THE NEW ModIface and ModDetails
292 -- and emit external core if necessary
293 -- This has to happen *after* code gen so that the back-end
294 -- info has been set. Not yet clear if it matters waiting
295 -- until after code output
296 ; new_iface <- _scc_ "MkFinalIface"
297 mkIface hsc_env location
298 maybe_checked_iface tidy_result
301 -- Space leak reduction: throw away the new interface if
302 -- we're in one-shot mode; we won't be needing it any
305 if one_shot then return (error "no final iface")
306 else return new_iface
307 ; let { final_globals | one_shot = Nothing
308 | otherwise = Just $! (mg_rdr_env tidy_result) }
309 ; final_globals `seq` return ()
311 -- Build the final ModDetails (except in one-shot mode, where
312 -- we won't need this information after compilation).
314 if one_shot then return (error "no final details")
315 else return $! ModDetails {
316 md_types = mg_types tidy_result,
317 md_insts = mg_insts tidy_result,
318 md_rules = mg_rules tidy_result }
321 -- CONVERT TO STG and COMPLETE CODE GENERATION
322 ; (stub_h_exists, stub_c_exists, maybe_bcos)
323 <- hscBackEnd dflags tidy_result
325 -- And the answer is ...
326 ; dumpIfaceStats hsc_env
328 ; return (HscRecomp final_details
331 stub_h_exists stub_c_exists
335 hscCoreFrontEnd hsc_env msg_act location = do {
339 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
340 ; case parseCore inp 1 of
341 FailP s -> putMsg s{-ToDo: wrong-} >> return (Left HscFail)
342 OkP rdr_module -> do {
345 -- RENAME and TYPECHECK
347 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
348 tcRnExtCore hsc_env rdr_module
350 ; case maybe_tc_result of {
351 Nothing -> return (Left HscFail);
352 Just mod_guts -> return (Right mod_guts)
353 -- No desugaring to do!
357 hscFileFrontEnd hsc_env msg_act location = do {
361 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
362 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
364 ; case maybe_parsed of {
365 Left err -> do { msg_act (unitBag err, emptyBag) ;
366 ; return (Left HscFail) ;
368 Right rdr_module -> hscFrontEnd hsc_env msg_act rdr_module
371 -- Perform static/dynamic checks on the source code in a StringBuffer
372 -- This is a temporary solution: it'll read in interface files lazily, whereas
373 -- we probably want to use the compilation manager to load in all the modules
375 hscBufferFrontEnd :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
376 hscBufferFrontEnd hsc_env buffer msg_act = do
377 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
378 showPass (hsc_dflags hsc_env) "Parser"
379 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
380 PFailed span err -> do
381 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
383 POk _ rdr_module -> do
384 hscBufferTypecheck hsc_env rdr_module msg_act
386 hscBufferTypecheck hsc_env rdr_module msg_act = do
387 (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
388 tcRnModule hsc_env rdr_module
390 case maybe_tc_result of
391 Nothing -> return (HscChecked (HscParsed rdr_module))
392 -- space leak on rdr_module!
393 Just r -> return (HscChecked (HscTypechecked r))
396 hscFrontEnd hsc_env msg_act rdr_module = do {
398 -- RENAME and TYPECHECK
400 ; (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
401 tcRnModule hsc_env rdr_module
403 ; case maybe_tc_result of {
404 Nothing -> return (Left HscFail);
405 Just tc_result -> do {
410 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
411 deSugar hsc_env tc_result
412 ; msg_act (warns, emptyBag)
413 ; case maybe_ds_result of
414 Nothing -> return (Left HscFail);
415 Just ds_result -> return (Right ds_result);
419 ModGuts{ -- This is the last use of the ModGuts in a compilation.
420 -- From now on, we just use the bits we need.
421 mg_module = this_mod,
422 mg_binds = core_binds,
424 mg_dir_imps = dir_imps,
425 mg_foreign = foreign_stubs,
426 mg_deps = dependencies } = do {
429 -- PREPARE FOR CODE GENERATION
430 -- Do saturation and convert to A-normal form
431 prepd_binds <- _scc_ "CorePrep"
432 corePrepPgm dflags core_binds type_env;
434 case dopt_HscLang dflags of
435 HscNothing -> return (False, False, Nothing)
439 do ----------------- Generate byte code ------------------
440 comp_bc <- byteCodeGen dflags prepd_binds type_env
442 ------------------ Create f-x-dynamic C-side stuff ---
443 (istub_h_exists, istub_c_exists)
444 <- outputForeignStubs dflags foreign_stubs
446 return ( istub_h_exists, istub_c_exists, Just comp_bc )
448 panic "GHC not compiled with interpreter"
453 ----------------- Convert to STG ------------------
454 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
455 myCoreToStg dflags this_mod prepd_binds
457 ------------------ Code generation ------------------
458 abstractC <- _scc_ "CodeGen"
459 codeGen dflags this_mod type_env foreign_stubs
460 dir_imps cost_centre_info stg_binds
462 ------------------ Code output -----------------------
463 (stub_h_exists, stub_c_exists)
464 <- codeOutput dflags this_mod foreign_stubs
465 dependencies abstractC
467 return (stub_h_exists, stub_c_exists, Nothing)
471 hscCmmFile :: DynFlags -> FilePath -> IO Bool
472 hscCmmFile dflags filename = do
473 maybe_cmm <- parseCmmFile dflags filename
475 Nothing -> return False
477 codeOutput dflags no_mod NoStubs noDependencies [cmm]
480 no_mod = panic "hscCmmFile: no_mod"
483 myParseModule dflags src_filename
484 = do -------------------------- Parser ----------------
485 showPass dflags "Parser"
487 buf <- hGetStringBuffer src_filename
489 let loc = mkSrcLoc (mkFastString src_filename) 1 0
491 case unP parseModule (mkPState buf loc dflags) of {
493 PFailed span err -> return (Left (mkPlainErrMsg span err));
495 POk _ rdr_module -> do {
497 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
499 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
500 (ppSourceStats False rdr_module) ;
502 return (Right rdr_module)
503 -- ToDo: free the string buffer later.
507 myCoreToStg dflags this_mod prepd_binds
509 stg_binds <- _scc_ "Core2Stg"
510 coreToStg dflags prepd_binds
512 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
513 stg2stg dflags this_mod stg_binds
515 return (stg_binds2, cost_centre_info)
519 %************************************************************************
521 \subsection{Compiling a do-statement}
523 %************************************************************************
525 When the UnlinkedBCOExpr is linked you get an HValue of type
527 When you run it you get a list of HValues that should be
528 the same length as the list of names; add them to the ClosureEnv.
530 A naked expression returns a singleton Name [it].
532 What you type The IO [HValue] that hscStmt returns
533 ------------- ------------------------------------
534 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
537 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
540 expr (of IO type) ==> expr >>= \ v -> return [v]
541 [NB: result not printed] bindings: [it]
544 expr (of non-IO type,
545 result showable) ==> let v = expr in print v >> return [v]
548 expr (of non-IO type,
549 result not showable) ==> error
553 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
555 -> InteractiveContext -- Context for compiling
556 -> String -- The statement
557 -> IO (Maybe (InteractiveContext, [Name], HValue))
559 hscStmt hsc_env icontext stmt
560 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
561 ; case maybe_stmt of {
562 Nothing -> return Nothing ; -- Parse error
563 Just Nothing -> return Nothing ; -- Empty line
564 Just (Just parsed_stmt) -> do { -- The real stuff
566 -- Rename and typecheck it
568 <- tcRnStmt hsc_env icontext parsed_stmt
570 ; case maybe_tc_result of {
571 Nothing -> return Nothing ;
572 Just (new_ic, bound_names, tc_expr) -> do {
574 -- Then desugar, code gen, and link it
575 ; hval <- compileExpr hsc_env iNTERACTIVE
576 (ic_rn_gbl_env new_ic)
580 ; return (Just (new_ic, bound_names, hval))
583 hscTcExpr -- Typecheck an expression (but don't run it)
585 -> InteractiveContext -- Context for compiling
586 -> String -- The expression
589 hscTcExpr hsc_env icontext expr
590 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
591 ; case maybe_stmt of {
592 Nothing -> return Nothing ; -- Parse error
593 Just (Just (L _ (ExprStmt expr _)))
594 -> tcRnExpr hsc_env icontext expr ;
595 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
599 hscKcType -- Find the kind of a type
601 -> InteractiveContext -- Context for compiling
602 -> String -- The type
605 hscKcType hsc_env icontext str
606 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
607 ; case maybe_type of {
608 Just ty -> tcRnType hsc_env icontext ty ;
609 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
611 Nothing -> return Nothing } }
615 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
616 hscParseStmt = hscParseThing parseStmt
618 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
619 hscParseType = hscParseThing parseType
621 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
622 hscParseIdentifier = hscParseThing parseIdentifier
624 hscParseThing :: Outputable thing
626 -> DynFlags -> String
628 -- Nothing => Parse error (message already printed)
630 hscParseThing parser dflags str
631 = do showPass dflags "Parser"
634 buf <- stringToStringBuffer str
636 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
638 case unP parser (mkPState buf loc dflags) of {
640 PFailed span err -> do { printError span err;
645 --ToDo: can't free the string buffer until we've finished this
646 -- compilation sweep and all the identifiers have gone away.
647 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
653 %************************************************************************
655 \subsection{Getting information about an identifer}
657 %************************************************************************
661 type GetInfoResult = (String, (IfaceDecl, Fixity, SrcLoc, [(IfaceInst,SrcLoc)]))
663 hscGetInfo -- like hscStmt, but deals with a single identifier
665 -> InteractiveContext -- Context for compiling
666 -> String -- The identifier
667 -> IO [GetInfoResult]
669 hscGetInfo hsc_env ic str
670 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
671 case maybe_rdr_name of {
672 Nothing -> return [];
673 Just (L _ rdr_name) -> do
675 maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
677 let -- str' is the the naked occurrence name
678 -- after stripping off qualification and parens (+)
679 str' = occNameUserString (rdrNameOcc rdr_name)
681 case maybe_tc_result of {
682 Nothing -> return [] ;
683 Just things -> return [(str', t) | t <- things]
688 %************************************************************************
690 Desugar, simplify, convert to bytecode, and link an expression
692 %************************************************************************
696 compileExpr :: HscEnv
697 -> Module -> GlobalRdrEnv -> TypeEnv
701 compileExpr hsc_env this_mod rdr_env type_env tc_expr
702 = do { let { dflags = hsc_dflags hsc_env ;
703 lint_on = dopt Opt_DoCoreLinting dflags }
706 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
709 ; flat_expr <- flattenExpr hsc_env ds_expr
712 ; simpl_expr <- simplifyExpr dflags flat_expr
714 -- Tidy it (temporary, until coreSat does cloning)
715 ; tidy_expr <- tidyCoreExpr simpl_expr
717 -- Prepare for codegen
718 ; prepd_expr <- corePrepExpr dflags tidy_expr
721 -- ToDo: improve SrcLoc
723 case lintUnfolding noSrcLoc [] prepd_expr of
724 Just err -> pprPanic "compileExpr" err
730 ; bcos <- coreExprToBCOs dflags prepd_expr
733 ; hval <- linkExpr hsc_env bcos
741 %************************************************************************
743 Statistics on reading interfaces
745 %************************************************************************
748 dumpIfaceStats :: HscEnv -> IO ()
749 dumpIfaceStats hsc_env
750 = do { eps <- readIORef (hsc_EPS hsc_env)
751 ; dumpIfSet (dump_if_trace || dump_rn_stats)
752 "Interface statistics"
755 dflags = hsc_dflags hsc_env
756 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
757 dump_if_trace = dopt Opt_D_dump_if_trace dflags