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 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 :: DynFlags -> IO HscEnv
104 = do { eps_var <- newIORef initExternalPackageState
105 ; us <- mkSplitUniqSupply 'r'
106 ; nc_var <- newIORef (initNameCache us knownKeyNames)
107 ; return (HscEnv { hsc_dflags = dflags,
108 hsc_HPT = emptyHomePackageTable,
110 hsc_NC = nc_var } ) }
113 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
114 -- where templateHaskellNames are defined
115 knownKeyNames = map getName wiredInThings
116 ++ basicKnownKeyNames
118 ++ templateHaskellNames
123 %************************************************************************
125 The main compiler pipeline
127 %************************************************************************
131 -- Compilation failed
134 -- In IDE mode: we just do the static/dynamic checks
135 | HscChecked (Located (HsModule RdrName)) (Maybe TcGblEnv)
137 -- Concluded that it wasn't necessary
138 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
139 ModIface -- new iface (if any compilation was done)
142 | 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 -- What to do when we have compiler error or warning messages
150 type MessageAction = Messages -> IO ()
152 -- no errors or warnings; the individual passes
153 -- (parse/rename/typecheck) print messages themselves
157 -> MessageAction -- What to do with errors/warnings
159 -> Bool -- True <=> source unchanged
160 -> Bool -- True <=> have an object file (for msgs only)
161 -> Maybe ModIface -- Old interface, if available
164 hscMain hsc_env msg_act mod_summary
165 source_unchanged have_object maybe_old_iface
167 (recomp_reqd, maybe_checked_iface) <-
168 _scc_ "checkOldIface"
169 checkOldIface hsc_env mod_summary
170 source_unchanged maybe_old_iface;
172 let no_old_iface = not (isJust maybe_checked_iface)
173 what_next | recomp_reqd || no_old_iface = hscRecomp
174 | otherwise = hscNoRecomp
176 ; what_next hsc_env msg_act mod_summary have_object
181 ------------------------------
182 -- hscNoRecomp definitely expects to have the old interface available
183 hscNoRecomp hsc_env msg_act mod_summary
184 have_object (Just old_iface)
185 | isOneShot (ghcMode (hsc_dflags hsc_env))
187 compilationProgressMsg (hsc_dflags hsc_env) $
188 "compilation IS NOT required";
189 dumpIfaceStats hsc_env ;
191 let { bomb = panic "hscNoRecomp:OneShot" };
192 return (HscNoRecomp bomb bomb)
195 = do { compilationProgressMsg (hsc_dflags hsc_env) $
196 ("Skipping " ++ showModMsg have_object mod_summary)
198 ; new_details <- _scc_ "tcRnIface"
199 typecheckIface hsc_env old_iface ;
200 ; dumpIfaceStats hsc_env
202 ; return (HscNoRecomp new_details old_iface)
205 ------------------------------
206 hscRecomp hsc_env msg_act mod_summary
207 have_object maybe_checked_iface
208 = case ms_hsc_src mod_summary of
209 HsSrcFile -> do { front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
210 ; hscBackEnd hsc_env mod_summary maybe_checked_iface front_res }
212 HsBootFile -> do { front_res <- hscFileFrontEnd hsc_env msg_act mod_summary
213 ; hscBootBackEnd hsc_env mod_summary maybe_checked_iface front_res }
215 ExtCoreFile -> do { front_res <- hscCoreFrontEnd hsc_env msg_act mod_summary
216 ; hscBackEnd hsc_env mod_summary maybe_checked_iface front_res }
218 hscCoreFrontEnd hsc_env msg_act mod_summary = do {
222 ; inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
223 ; case parseCore inp 1 of
224 FailP s -> putMsg s{-ToDo: wrong-} >> return Nothing
225 OkP rdr_module -> do {
228 -- RENAME and TYPECHECK
230 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
231 tcRnExtCore hsc_env rdr_module
233 ; case maybe_tc_result of
234 Nothing -> return Nothing
235 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
239 hscFileFrontEnd hsc_env msg_act mod_summary = do {
241 -- DISPLAY PROGRESS MESSAGE
243 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
244 ; let dflags = hsc_dflags hsc_env
245 ; let toInterp = hscTarget dflags == HscInterpreted
246 ; when (not one_shot) $
247 compilationProgressMsg dflags $
248 ("Compiling " ++ showModMsg (not toInterp) mod_summary)
253 ; let hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
254 hspp_buf = ms_hspp_buf mod_summary
256 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file hspp_buf
258 ; case maybe_parsed of {
259 Left err -> do { msg_act (unitBag err, emptyBag)
261 Right rdr_module -> do {
264 -- RENAME and TYPECHECK
266 (tc_msgs, maybe_tc_result)
267 <- _scc_ "Typecheck-Rename"
268 tcRnModule hsc_env (ms_hsc_src mod_summary) rdr_module
271 ; case maybe_tc_result of {
272 Nothing -> return Nothing ;
273 Just tc_result -> do {
278 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
279 deSugar hsc_env tc_result
280 ; msg_act (warns, emptyBag)
281 ; case maybe_ds_result of
282 Nothing -> return Nothing
283 Just ds_result -> return (Just ds_result)
286 ------------------------------
287 hscBootBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
288 -- For hs-boot files, there's no code generation to do
290 hscBootBackEnd hsc_env mod_summary maybe_checked_iface Nothing
292 hscBootBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
293 = do { final_iface <- _scc_ "MkFinalIface"
294 mkIface hsc_env (ms_location mod_summary)
295 maybe_checked_iface ds_result
297 ; let { final_details = ModDetails { md_types = mg_types ds_result,
298 md_insts = mg_insts ds_result,
299 md_rules = mg_rules ds_result } }
300 -- And the answer is ...
301 ; dumpIfaceStats hsc_env
303 ; return (HscRecomp final_details
308 ------------------------------
309 hscBackEnd :: HscEnv -> ModSummary -> Maybe ModIface -> Maybe ModGuts -> IO HscResult
311 hscBackEnd hsc_env mod_summary maybe_checked_iface Nothing
314 hscBackEnd hsc_env mod_summary maybe_checked_iface (Just ds_result)
316 -- ; seqList imported_modules (return ())
318 let one_shot = isOneShot (ghcMode (hsc_dflags hsc_env))
319 dflags = hsc_dflags hsc_env
324 ; flat_result <- _scc_ "Flattening"
325 flatten hsc_env ds_result
328 {- TEMP: need to review space-leak fixing here
329 NB: even the code generator can force one of the
330 thunks for constructor arguments, for newtypes in particular
332 ; let -- Rule-base accumulated from imported packages
333 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
335 -- In one-shot mode, ZAP the external package state at
336 -- this point, because we aren't going to need it from
337 -- now on. We keep the name cache, however, because
338 -- tidyCore needs it.
340 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
343 ; pkg_rule_base `seq` pcs_middle `seq` return ()
346 -- alive at this point:
354 ; simpl_result <- _scc_ "Core2Core"
355 core2core hsc_env flat_result
360 ; tidy_result <- _scc_ "CoreTidy"
361 tidyCorePgm hsc_env simpl_result
363 -- Emit external core
364 ; emitExternalCore dflags tidy_result
366 -- Alive at this point:
367 -- tidy_result, pcs_final
371 -- BUILD THE NEW ModIface and ModDetails
372 -- and emit external core if necessary
373 -- This has to happen *after* code gen so that the back-end
374 -- info has been set. Not yet clear if it matters waiting
375 -- until after code output
376 ; new_iface <- _scc_ "MkFinalIface"
377 mkIface hsc_env (ms_location mod_summary)
378 maybe_checked_iface tidy_result
380 -- Space leak reduction: throw away the new interface if
381 -- we're in one-shot mode; we won't be needing it any
384 if one_shot then return (error "no final iface")
385 else return new_iface
387 -- Build the final ModDetails (except in one-shot mode, where
388 -- we won't need this information after compilation).
390 if one_shot then return (error "no final details")
391 else return $! ModDetails {
392 md_types = mg_types tidy_result,
393 md_insts = mg_insts tidy_result,
394 md_rules = mg_rules tidy_result }
397 -- CONVERT TO STG and COMPLETE CODE GENERATION
398 ; (stub_h_exists, stub_c_exists, maybe_bcos)
399 <- hscCodeGen dflags tidy_result
401 -- And the answer is ...
402 ; dumpIfaceStats hsc_env
404 ; return (HscRecomp final_details
406 stub_h_exists stub_c_exists
411 hscFileCheck hsc_env msg_act hspp_file = do {
415 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env) hspp_file Nothing
417 ; case maybe_parsed of {
418 Left err -> do { msg_act (unitBag err, emptyBag) ;
421 Right rdr_module -> hscBufferTypecheck hsc_env rdr_module msg_act
425 -- Perform static/dynamic checks on the source code in a StringBuffer
426 -- This is a temporary solution: it'll read in interface files lazily, whereas
427 -- we probably want to use the compilation manager to load in all the modules
429 hscBufferCheck :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
430 hscBufferCheck hsc_env buffer msg_act = do
431 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
432 showPass (hsc_dflags hsc_env) "Parser"
433 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
434 PFailed span err -> do
435 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
437 POk _ rdr_module -> do
438 hscBufferTypecheck hsc_env rdr_module msg_act
440 hscBufferTypecheck hsc_env rdr_module msg_act = do
441 (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
442 tcRnModule hsc_env HsSrcFile rdr_module
444 case maybe_tc_result of
445 Nothing -> return (HscChecked rdr_module Nothing)
446 -- space leak on rdr_module!
447 Just r -> return (HscChecked rdr_module (Just r))
451 ModGuts{ -- This is the last use of the ModGuts in a compilation.
452 -- From now on, we just use the bits we need.
453 mg_module = this_mod,
454 mg_binds = core_binds,
456 mg_dir_imps = dir_imps,
457 mg_foreign = foreign_stubs,
458 mg_deps = dependencies } = do {
461 -- PREPARE FOR CODE GENERATION
462 -- Do saturation and convert to A-normal form
463 prepd_binds <- _scc_ "CorePrep"
464 corePrepPgm dflags core_binds type_env;
466 case hscTarget dflags of
467 HscNothing -> return (False, False, Nothing)
471 do ----------------- Generate byte code ------------------
472 comp_bc <- byteCodeGen dflags prepd_binds type_env
474 ------------------ Create f-x-dynamic C-side stuff ---
475 (istub_h_exists, istub_c_exists)
476 <- outputForeignStubs dflags foreign_stubs
478 return ( istub_h_exists, istub_c_exists, Just comp_bc )
480 panic "GHC not compiled with interpreter"
485 ----------------- Convert to STG ------------------
486 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
487 myCoreToStg dflags this_mod prepd_binds
489 ------------------ Code generation ------------------
490 abstractC <- _scc_ "CodeGen"
491 codeGen dflags this_mod type_env foreign_stubs
492 dir_imps cost_centre_info stg_binds
494 ------------------ Code output -----------------------
495 (stub_h_exists, stub_c_exists)
496 <- codeOutput dflags this_mod foreign_stubs
497 dependencies abstractC
499 return (stub_h_exists, stub_c_exists, Nothing)
503 hscCmmFile :: DynFlags -> FilePath -> IO Bool
504 hscCmmFile dflags filename = do
505 maybe_cmm <- parseCmmFile dflags filename
507 Nothing -> return False
509 codeOutput dflags no_mod NoStubs noDependencies [cmm]
512 no_mod = panic "hscCmmFile: no_mod"
515 myParseModule dflags src_filename maybe_src_buf
516 = do -------------------------- Parser ----------------
517 showPass dflags "Parser"
520 -- sometimes we already have the buffer in memory, perhaps
521 -- because we needed to parse the imports out of it, or get the
523 buf <- case maybe_src_buf of
525 Nothing -> hGetStringBuffer src_filename
527 let loc = mkSrcLoc (mkFastString src_filename) 1 0
529 case unP parseModule (mkPState buf loc dflags) of {
531 PFailed span err -> return (Left (mkPlainErrMsg span err));
533 POk _ rdr_module -> do {
535 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
537 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
538 (ppSourceStats False rdr_module) ;
540 return (Right rdr_module)
541 -- ToDo: free the string buffer later.
545 myCoreToStg dflags this_mod prepd_binds
547 stg_binds <- _scc_ "Core2Stg"
548 coreToStg dflags prepd_binds
550 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
551 stg2stg dflags this_mod stg_binds
553 return (stg_binds2, cost_centre_info)
557 %************************************************************************
559 \subsection{Compiling a do-statement}
561 %************************************************************************
563 When the UnlinkedBCOExpr is linked you get an HValue of type
565 When you run it you get a list of HValues that should be
566 the same length as the list of names; add them to the ClosureEnv.
568 A naked expression returns a singleton Name [it].
570 What you type The IO [HValue] that hscStmt returns
571 ------------- ------------------------------------
572 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
575 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
578 expr (of IO type) ==> expr >>= \ v -> return [v]
579 [NB: result not printed] bindings: [it]
582 expr (of non-IO type,
583 result showable) ==> let v = expr in print v >> return [v]
586 expr (of non-IO type,
587 result not showable) ==> error
591 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
593 -> InteractiveContext -- Context for compiling
594 -> String -- The statement
595 -> IO (Maybe (InteractiveContext, [Name], HValue))
597 hscStmt hsc_env icontext stmt
598 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
599 ; case maybe_stmt of {
600 Nothing -> return Nothing ; -- Parse error
601 Just Nothing -> return Nothing ; -- Empty line
602 Just (Just parsed_stmt) -> do { -- The real stuff
604 -- Rename and typecheck it
606 <- tcRnStmt hsc_env icontext parsed_stmt
608 ; case maybe_tc_result of {
609 Nothing -> return Nothing ;
610 Just (new_ic, bound_names, tc_expr) -> do {
612 -- Then desugar, code gen, and link it
613 ; hval <- compileExpr hsc_env iNTERACTIVE
614 (ic_rn_gbl_env new_ic)
618 ; return (Just (new_ic, bound_names, hval))
621 hscTcExpr -- Typecheck an expression (but don't run it)
623 -> InteractiveContext -- Context for compiling
624 -> String -- The expression
627 hscTcExpr hsc_env icontext expr
628 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
629 ; case maybe_stmt of {
630 Nothing -> return Nothing ; -- Parse error
631 Just (Just (L _ (ExprStmt expr _)))
632 -> tcRnExpr hsc_env icontext expr ;
633 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
637 hscKcType -- Find the kind of a type
639 -> InteractiveContext -- Context for compiling
640 -> String -- The type
643 hscKcType hsc_env icontext str
644 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
645 ; case maybe_type of {
646 Just ty -> tcRnType hsc_env icontext ty ;
647 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
649 Nothing -> return Nothing } }
653 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
654 hscParseStmt = hscParseThing parseStmt
656 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
657 hscParseType = hscParseThing parseType
659 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
660 hscParseIdentifier = hscParseThing parseIdentifier
662 hscParseThing :: Outputable thing
664 -> DynFlags -> String
666 -- Nothing => Parse error (message already printed)
668 hscParseThing parser dflags str
669 = do showPass dflags "Parser"
672 buf <- stringToStringBuffer str
674 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
676 case unP parser (mkPState buf loc dflags) of {
678 PFailed span err -> do { printError span err;
683 --ToDo: can't free the string buffer until we've finished this
684 -- compilation sweep and all the identifiers have gone away.
685 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
691 %************************************************************************
693 \subsection{Getting information about an identifer}
695 %************************************************************************
699 hscGetInfo -- like hscStmt, but deals with a single identifier
701 -> InteractiveContext -- Context for compiling
702 -> String -- The identifier
703 -> IO [GetInfoResult]
705 hscGetInfo hsc_env ic str
706 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
707 case maybe_rdr_name of {
708 Nothing -> return [];
709 Just (L _ rdr_name) -> do
711 maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
713 case maybe_tc_result of
715 Just things -> return things
720 %************************************************************************
722 Desugar, simplify, convert to bytecode, and link an expression
724 %************************************************************************
728 compileExpr :: HscEnv
729 -> Module -> GlobalRdrEnv -> TypeEnv
733 compileExpr hsc_env this_mod rdr_env type_env tc_expr
734 = do { let { dflags = hsc_dflags hsc_env ;
735 lint_on = dopt Opt_DoCoreLinting dflags }
738 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
741 ; flat_expr <- flattenExpr hsc_env ds_expr
744 ; simpl_expr <- simplifyExpr dflags flat_expr
746 -- Tidy it (temporary, until coreSat does cloning)
747 ; tidy_expr <- tidyCoreExpr simpl_expr
749 -- Prepare for codegen
750 ; prepd_expr <- corePrepExpr dflags tidy_expr
753 -- ToDo: improve SrcLoc
755 case lintUnfolding noSrcLoc [] prepd_expr of
756 Just err -> pprPanic "compileExpr" err
762 ; bcos <- coreExprToBCOs dflags prepd_expr
765 ; hval <- linkExpr hsc_env bcos
773 %************************************************************************
775 Statistics on reading interfaces
777 %************************************************************************
780 dumpIfaceStats :: HscEnv -> IO ()
781 dumpIfaceStats hsc_env
782 = do { eps <- readIORef (hsc_EPS hsc_env)
783 ; dumpIfSet (dump_if_trace || dump_rn_stats)
784 "Interface statistics"
787 dflags = hsc_dflags hsc_env
788 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
789 dump_if_trace = dopt Opt_D_dump_if_trace dflags