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 )
40 import SrcLoc ( SrcLoc, noSrcLoc )
43 import RdrName ( RdrName )
44 import HsSyn ( HsModule )
45 import SrcLoc ( Located(..) )
46 import StringBuffer ( hGetStringBuffer )
48 import Lexer ( P(..), ParseResult(..), mkPState )
49 import SrcLoc ( mkSrcLoc )
50 import TcRnDriver ( tcRnModule, tcRnExtCore )
51 import TcRnTypes ( TcGblEnv )
52 import TcIface ( typecheckIface )
53 import IfaceEnv ( initNameCache )
54 import LoadIface ( ifaceStats, initExternalPackageState )
55 import PrelInfo ( wiredInThings, basicKnownKeyNames )
56 import RdrName ( GlobalRdrEnv )
57 import MkIface ( checkOldIface, mkIface )
59 import Flattening ( flatten )
61 import TidyPgm ( tidyCorePgm )
62 import CorePrep ( corePrepPgm )
63 import CoreToStg ( coreToStg )
64 import Name ( Name, NamedThing(..) )
65 import SimplStg ( stg2stg )
66 import CodeGen ( codeGen )
67 import CmmParse ( parseCmmFile )
68 import CodeOutput ( codeOutput )
71 import DriverPhases ( isExtCoreFilename )
73 import UniqSupply ( mkSplitUniqSupply )
76 import HscStats ( ppSourceStats )
78 import MkExternalCore ( emitExternalCore )
80 import ParserCoreUtils
81 import Module ( Module, ModLocation(..), showModMsg )
83 import Maybes ( expectJust )
84 import StringBuffer ( StringBuffer )
85 import Bag ( unitBag, emptyBag )
88 import Maybe ( isJust, fromJust )
90 import DATA_IOREF ( newIORef, readIORef )
94 %************************************************************************
98 %************************************************************************
101 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
102 newHscEnv ghci_mode dflags
103 = do { eps_var <- newIORef initExternalPackageState
104 ; us <- mkSplitUniqSupply 'r'
105 ; nc_var <- newIORef (initNameCache us knownKeyNames)
106 ; return (HscEnv { hsc_mode = ghci_mode,
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 HscCheckResult
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)
144 ModIface -- new iface (if any compilation was done)
145 Bool -- stub_h exists
146 Bool -- stub_c exists
147 (Maybe CompiledByteCode)
150 -- The result when we're just checking (in an IDE editor, for example)
152 = HscParsed (Located (HsModule RdrName))
153 -- renaming/typechecking failed, here's the parse tree
154 | HscTypechecked TcGblEnv
155 -- renaming/typechecking succeeded
157 -- What to do when we have compiler error or warning messages
158 type MessageAction = Messages -> IO ()
160 -- no errors or warnings; the individual passes
161 -- (parse/rename/typecheck) print messages themselves
165 -> MessageAction -- what to do with errors/warnings
167 -> ModLocation -- location info
168 -> Bool -- True <=> source unchanged
169 -> Bool -- True <=> have an object file (for msgs only)
170 -> Maybe ModIface -- old interface, if available
173 hscMain hsc_env msg_act mod location
174 source_unchanged have_object maybe_old_iface
176 (recomp_reqd, maybe_checked_iface) <-
177 _scc_ "checkOldIface"
178 checkOldIface hsc_env mod
179 (ml_hi_file location)
180 source_unchanged maybe_old_iface;
182 let no_old_iface = not (isJust maybe_checked_iface)
183 what_next | recomp_reqd || no_old_iface = hscRecomp
184 | otherwise = hscNoRecomp
186 ; what_next hsc_env msg_act have_object
187 mod location maybe_checked_iface
191 -- hscNoRecomp definitely expects to have the old interface available
192 hscNoRecomp hsc_env msg_act have_object
193 mod location (Just old_iface)
194 | isOneShot (hsc_mode hsc_env)
196 compilationProgressMsg (hsc_dflags hsc_env) $
197 "compilation IS NOT required";
198 dumpIfaceStats hsc_env ;
200 let { bomb = panic "hscNoRecomp:OneShot" };
201 return (HscNoRecomp bomb bomb)
205 compilationProgressMsg (hsc_dflags hsc_env) $
206 ("Skipping " ++ showModMsg have_object mod location);
208 new_details <- _scc_ "tcRnIface"
209 typecheckIface hsc_env old_iface ;
210 dumpIfaceStats hsc_env ;
212 return (HscNoRecomp new_details old_iface)
215 hscRecomp hsc_env msg_act have_object
216 mod location maybe_checked_iface
218 -- what target are we shooting for?
219 ; let one_shot = isOneShot (hsc_mode hsc_env)
220 ; let dflags = hsc_dflags hsc_env
221 ; let toInterp = dopt_HscLang dflags == HscInterpreted
222 ; let toCore = isJust (ml_hs_file location) &&
223 isExtCoreFilename (fromJust (ml_hs_file location))
225 ; when (not one_shot) $
226 compilationProgressMsg dflags $
227 ("Compiling " ++ showModMsg (not toInterp) mod location);
229 ; front_res <- if toCore then
230 hscCoreFrontEnd hsc_env msg_act location
232 hscFileFrontEnd hsc_env msg_act location
235 Left flure -> return flure;
236 Right ds_result -> do {
240 -- ; seqList imported_modules (return ())
245 ; flat_result <- _scc_ "Flattening"
246 flatten hsc_env ds_result
249 {- TEMP: need to review space-leak fixing here
250 NB: even the code generator can force one of the
251 thunks for constructor arguments, for newtypes in particular
253 ; let -- Rule-base accumulated from imported packages
254 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
256 -- In one-shot mode, ZAP the external package state at
257 -- this point, because we aren't going to need it from
258 -- now on. We keep the name cache, however, because
259 -- tidyCore needs it.
261 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
264 ; pkg_rule_base `seq` pcs_middle `seq` return ()
267 -- alive at this point:
275 ; simpl_result <- _scc_ "Core2Core"
276 core2core hsc_env flat_result
281 ; tidy_result <- _scc_ "CoreTidy"
282 tidyCorePgm hsc_env simpl_result
284 -- Emit external core
285 ; emitExternalCore dflags tidy_result
287 -- Alive at this point:
288 -- tidy_result, pcs_final
292 -- BUILD THE NEW ModIface and ModDetails
293 -- and emit external core if necessary
294 -- This has to happen *after* code gen so that the back-end
295 -- info has been set. Not yet clear if it matters waiting
296 -- until after code output
297 ; new_iface <- _scc_ "MkFinalIface"
298 mkIface hsc_env location
299 maybe_checked_iface tidy_result
302 -- Space leak reduction: throw away the new interface if
303 -- we're in one-shot mode; we won't be needing it any
306 if one_shot then return (error "no final iface")
307 else return new_iface
308 ; let { final_globals | one_shot = Nothing
309 | otherwise = Just $! (mg_rdr_env tidy_result) }
310 ; final_globals `seq` return ()
312 -- Build the final ModDetails (except in one-shot mode, where
313 -- we won't need this information after compilation).
315 if one_shot then return (error "no final details")
316 else return $! ModDetails {
317 md_types = mg_types tidy_result,
318 md_insts = mg_insts tidy_result,
319 md_rules = mg_rules tidy_result }
322 -- CONVERT TO STG and COMPLETE CODE GENERATION
323 ; (stub_h_exists, stub_c_exists, maybe_bcos)
324 <- hscBackEnd dflags tidy_result
326 -- And the answer is ...
327 ; dumpIfaceStats hsc_env
329 ; return (HscRecomp final_details
332 stub_h_exists stub_c_exists
336 hscCoreFrontEnd hsc_env msg_act location = do {
340 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
341 ; case parseCore inp 1 of
342 FailP s -> putMsg s{-ToDo: wrong-} >> return (Left HscFail)
343 OkP rdr_module -> do {
346 -- RENAME and TYPECHECK
348 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
349 tcRnExtCore hsc_env rdr_module
351 ; case maybe_tc_result of {
352 Nothing -> return (Left HscFail);
353 Just mod_guts -> return (Right mod_guts)
354 -- No desugaring to do!
358 hscFileFrontEnd hsc_env msg_act location = do {
362 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
363 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
365 ; case maybe_parsed of {
366 Left err -> do { msg_act (unitBag err, emptyBag) ;
367 ; return (Left HscFail) ;
369 Right rdr_module -> hscFrontEnd hsc_env msg_act rdr_module
372 -- Perform static/dynamic checks on the source code in a StringBuffer
373 -- This is a temporary solution: it'll read in interface files lazily, whereas
374 -- we probably want to use the compilation manager to load in all the modules
376 hscBufferFrontEnd :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
377 hscBufferFrontEnd hsc_env buffer msg_act = do
378 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
379 showPass (hsc_dflags hsc_env) "Parser"
380 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
381 PFailed span err -> do
382 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
384 POk _ rdr_module -> do
385 hscBufferTypecheck hsc_env rdr_module msg_act
387 hscBufferTypecheck hsc_env rdr_module msg_act = do
388 (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
389 tcRnModule hsc_env rdr_module
391 case maybe_tc_result of
392 Nothing -> return (HscChecked (HscParsed rdr_module))
393 -- space leak on rdr_module!
394 Just r -> return (HscChecked (HscTypechecked r))
397 hscFrontEnd hsc_env msg_act rdr_module = do {
399 -- RENAME and TYPECHECK
401 ; (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
402 tcRnModule hsc_env rdr_module
404 ; case maybe_tc_result of {
405 Nothing -> return (Left HscFail);
406 Just tc_result -> do {
411 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
412 deSugar hsc_env tc_result
413 ; msg_act (warns, emptyBag)
414 ; case maybe_ds_result of
415 Nothing -> return (Left HscFail);
416 Just ds_result -> return (Right ds_result);
420 ModGuts{ -- This is the last use of the ModGuts in a compilation.
421 -- From now on, we just use the bits we need.
422 mg_module = this_mod,
423 mg_binds = core_binds,
425 mg_dir_imps = dir_imps,
426 mg_foreign = foreign_stubs,
427 mg_deps = dependencies } = do {
430 -- PREPARE FOR CODE GENERATION
431 -- Do saturation and convert to A-normal form
432 prepd_binds <- _scc_ "CorePrep"
433 corePrepPgm dflags core_binds type_env;
435 case dopt_HscLang dflags of
436 HscNothing -> return (False, False, Nothing)
440 do ----------------- Generate byte code ------------------
441 comp_bc <- byteCodeGen dflags prepd_binds type_env
443 ------------------ Create f-x-dynamic C-side stuff ---
444 (istub_h_exists, istub_c_exists)
445 <- outputForeignStubs dflags foreign_stubs
447 return ( istub_h_exists, istub_c_exists, Just comp_bc )
449 panic "GHC not compiled with interpreter"
454 ----------------- Convert to STG ------------------
455 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
456 myCoreToStg dflags this_mod prepd_binds
458 ------------------ Code generation ------------------
459 abstractC <- _scc_ "CodeGen"
460 codeGen dflags this_mod type_env foreign_stubs
461 dir_imps cost_centre_info stg_binds
463 ------------------ Code output -----------------------
464 (stub_h_exists, stub_c_exists)
465 <- codeOutput dflags this_mod foreign_stubs
466 dependencies abstractC
468 return (stub_h_exists, stub_c_exists, Nothing)
472 hscCmmFile :: DynFlags -> FilePath -> IO Bool
473 hscCmmFile dflags filename = do
474 maybe_cmm <- parseCmmFile dflags filename
476 Nothing -> return False
478 codeOutput dflags no_mod NoStubs noDependencies [cmm]
481 no_mod = panic "hscCmmFile: no_mod"
484 myParseModule dflags src_filename
485 = do -------------------------- Parser ----------------
486 showPass dflags "Parser"
488 buf <- hGetStringBuffer src_filename
490 let loc = mkSrcLoc (mkFastString src_filename) 1 0
492 case unP parseModule (mkPState buf loc dflags) of {
494 PFailed span err -> return (Left (mkPlainErrMsg span err));
496 POk _ rdr_module -> do {
498 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
500 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
501 (ppSourceStats False rdr_module) ;
503 return (Right rdr_module)
504 -- ToDo: free the string buffer later.
508 myCoreToStg dflags this_mod prepd_binds
510 stg_binds <- _scc_ "Core2Stg"
511 coreToStg dflags prepd_binds
513 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
514 stg2stg dflags this_mod stg_binds
516 return (stg_binds2, cost_centre_info)
520 %************************************************************************
522 \subsection{Compiling a do-statement}
524 %************************************************************************
526 When the UnlinkedBCOExpr is linked you get an HValue of type
528 When you run it you get a list of HValues that should be
529 the same length as the list of names; add them to the ClosureEnv.
531 A naked expression returns a singleton Name [it].
533 What you type The IO [HValue] that hscStmt returns
534 ------------- ------------------------------------
535 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
538 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
541 expr (of IO type) ==> expr >>= \ v -> return [v]
542 [NB: result not printed] bindings: [it]
545 expr (of non-IO type,
546 result showable) ==> let v = expr in print v >> return [v]
549 expr (of non-IO type,
550 result not showable) ==> error
554 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
556 -> InteractiveContext -- Context for compiling
557 -> String -- The statement
558 -> IO (Maybe (InteractiveContext, [Name], HValue))
560 hscStmt hsc_env icontext stmt
561 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
562 ; case maybe_stmt of {
563 Nothing -> return Nothing ; -- Parse error
564 Just Nothing -> return Nothing ; -- Empty line
565 Just (Just parsed_stmt) -> do { -- The real stuff
567 -- Rename and typecheck it
569 <- tcRnStmt hsc_env icontext parsed_stmt
571 ; case maybe_tc_result of {
572 Nothing -> return Nothing ;
573 Just (new_ic, bound_names, tc_expr) -> do {
575 -- Then desugar, code gen, and link it
576 ; hval <- compileExpr hsc_env iNTERACTIVE
577 (ic_rn_gbl_env new_ic)
581 ; return (Just (new_ic, bound_names, hval))
584 hscTcExpr -- Typecheck an expression (but don't run it)
586 -> InteractiveContext -- Context for compiling
587 -> String -- The expression
590 hscTcExpr hsc_env icontext expr
591 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
592 ; case maybe_stmt of {
593 Nothing -> return Nothing ; -- Parse error
594 Just (Just (L _ (ExprStmt expr _)))
595 -> tcRnExpr hsc_env icontext expr ;
596 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
600 hscKcType -- Find the kind of a type
602 -> InteractiveContext -- Context for compiling
603 -> String -- The type
606 hscKcType hsc_env icontext str
607 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
608 ; case maybe_type of {
609 Just ty -> tcRnType hsc_env icontext ty ;
610 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
612 Nothing -> return Nothing } }
616 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
617 hscParseStmt = hscParseThing parseStmt
619 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
620 hscParseType = hscParseThing parseType
622 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
623 hscParseIdentifier = hscParseThing parseIdentifier
625 hscParseThing :: Outputable thing
627 -> DynFlags -> String
629 -- Nothing => Parse error (message already printed)
631 hscParseThing parser dflags str
632 = do showPass dflags "Parser"
635 buf <- stringToStringBuffer str
637 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
639 case unP parser (mkPState buf loc dflags) of {
641 PFailed span err -> do { printError span err;
646 --ToDo: can't free the string buffer until we've finished this
647 -- compilation sweep and all the identifiers have gone away.
648 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
654 %************************************************************************
656 \subsection{Getting information about an identifer}
658 %************************************************************************
662 type GetInfoResult = (String, (IfaceDecl, Fixity, SrcLoc, [(IfaceInst,SrcLoc)]))
664 hscGetInfo -- like hscStmt, but deals with a single identifier
666 -> InteractiveContext -- Context for compiling
667 -> String -- The identifier
668 -> IO [GetInfoResult]
670 hscGetInfo hsc_env ic str
671 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
672 case maybe_rdr_name of {
673 Nothing -> return [];
674 Just (L _ rdr_name) -> do
676 maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
678 let -- str' is the the naked occurrence name
679 -- after stripping off qualification and parens (+)
680 str' = occNameUserString (rdrNameOcc rdr_name)
682 case maybe_tc_result of {
683 Nothing -> return [] ;
684 Just things -> return [(str', t) | t <- things]
689 %************************************************************************
691 Desugar, simplify, convert to bytecode, and link an expression
693 %************************************************************************
697 compileExpr :: HscEnv
698 -> Module -> GlobalRdrEnv -> TypeEnv
702 compileExpr hsc_env this_mod rdr_env type_env tc_expr
703 = do { let { dflags = hsc_dflags hsc_env ;
704 lint_on = dopt Opt_DoCoreLinting dflags }
707 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
710 ; flat_expr <- flattenExpr hsc_env ds_expr
713 ; simpl_expr <- simplifyExpr dflags flat_expr
715 -- Tidy it (temporary, until coreSat does cloning)
716 ; tidy_expr <- tidyCoreExpr simpl_expr
718 -- Prepare for codegen
719 ; prepd_expr <- corePrepExpr dflags tidy_expr
722 -- ToDo: improve SrcLoc
724 case lintUnfolding noSrcLoc [] prepd_expr of
725 Just err -> pprPanic "compileExpr" err
731 ; bcos <- coreExprToBCOs dflags prepd_expr
734 ; hval <- linkExpr hsc_env bcos
742 %************************************************************************
744 Statistics on reading interfaces
746 %************************************************************************
749 dumpIfaceStats :: HscEnv -> IO ()
750 dumpIfaceStats hsc_env
751 = do { eps <- readIORef (hsc_EPS hsc_env)
752 ; dumpIfSet (dump_if_trace || dump_rn_stats)
753 "Interface statistics"
756 dflags = hsc_dflags hsc_env
757 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
758 dump_if_trace = dopt Opt_D_dump_if_trace dflags