2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
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
136 (Located (HsModule RdrName)) -- parse tree
137 (Maybe TcGblEnv) -- typechecker output, if succeeded
139 -- Concluded that it wasn't necessary
140 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
141 ModIface -- new iface (if any compilation was done)
144 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
146 ModIface -- new iface (if any compilation was done)
147 Bool -- stub_h exists
148 Bool -- stub_c exists
149 (Maybe CompiledByteCode)
152 -- What to do when we have compiler error or warning messages
153 type MessageAction = Messages -> IO ()
155 -- no errors or warnings; the individual passes
156 -- (parse/rename/typecheck) print messages themselves
160 -> MessageAction -- what to do with errors/warnings
162 -> ModLocation -- location info
163 -> Bool -- True <=> source unchanged
164 -> Bool -- True <=> have an object file (for msgs only)
165 -> Maybe ModIface -- old interface, if available
168 hscMain hsc_env msg_act mod location
169 source_unchanged have_object maybe_old_iface
171 (recomp_reqd, maybe_checked_iface) <-
172 _scc_ "checkOldIface"
173 checkOldIface hsc_env mod
174 (ml_hi_file location)
175 source_unchanged maybe_old_iface;
177 let no_old_iface = not (isJust maybe_checked_iface)
178 what_next | recomp_reqd || no_old_iface = hscRecomp
179 | otherwise = hscNoRecomp
181 ; what_next hsc_env msg_act have_object
182 mod location maybe_checked_iface
186 -- hscNoRecomp definitely expects to have the old interface available
187 hscNoRecomp hsc_env msg_act have_object
188 mod location (Just old_iface)
189 | isOneShot (hsc_mode hsc_env)
191 compilationProgressMsg (hsc_dflags hsc_env) $
192 "compilation IS NOT required";
193 dumpIfaceStats hsc_env ;
195 let { bomb = panic "hscNoRecomp:OneShot" };
196 return (HscNoRecomp bomb bomb)
200 compilationProgressMsg (hsc_dflags hsc_env) $
201 ("Skipping " ++ showModMsg have_object mod location);
203 new_details <- _scc_ "tcRnIface"
204 typecheckIface hsc_env old_iface ;
205 dumpIfaceStats hsc_env ;
207 return (HscNoRecomp new_details old_iface)
210 hscRecomp hsc_env msg_act have_object
211 mod location maybe_checked_iface
213 -- what target are we shooting for?
214 ; let one_shot = isOneShot (hsc_mode hsc_env)
215 ; let dflags = hsc_dflags hsc_env
216 ; let toInterp = dopt_HscLang dflags == HscInterpreted
217 ; let toCore = isJust (ml_hs_file location) &&
218 isExtCoreFilename (fromJust (ml_hs_file location))
220 ; when (not one_shot) $
221 compilationProgressMsg dflags $
222 ("Compiling " ++ showModMsg (not toInterp) mod location);
224 ; front_res <- if toCore then
225 hscCoreFrontEnd hsc_env msg_act location
227 hscFileFrontEnd hsc_env msg_act location
230 Left flure -> return flure;
231 Right ds_result -> do {
235 -- ; seqList imported_modules (return ())
240 ; flat_result <- _scc_ "Flattening"
241 flatten hsc_env ds_result
244 {- TEMP: need to review space-leak fixing here
245 NB: even the code generator can force one of the
246 thunks for constructor arguments, for newtypes in particular
248 ; let -- Rule-base accumulated from imported packages
249 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
251 -- In one-shot mode, ZAP the external package state at
252 -- this point, because we aren't going to need it from
253 -- now on. We keep the name cache, however, because
254 -- tidyCore needs it.
256 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
259 ; pkg_rule_base `seq` pcs_middle `seq` return ()
262 -- alive at this point:
270 ; simpl_result <- _scc_ "Core2Core"
271 core2core hsc_env flat_result
276 ; tidy_result <- _scc_ "CoreTidy"
277 tidyCorePgm hsc_env simpl_result
279 -- Emit external core
280 ; emitExternalCore dflags tidy_result
282 -- Alive at this point:
283 -- tidy_result, pcs_final
287 -- BUILD THE NEW ModIface and ModDetails
288 -- and emit external core if necessary
289 -- This has to happen *after* code gen so that the back-end
290 -- info has been set. Not yet clear if it matters waiting
291 -- until after code output
292 ; new_iface <- _scc_ "MkFinalIface"
293 mkIface hsc_env location
294 maybe_checked_iface tidy_result
297 -- Space leak reduction: throw away the new interface if
298 -- we're in one-shot mode; we won't be needing it any
301 if one_shot then return (error "no final iface")
302 else return new_iface
303 ; let { final_globals | one_shot = Nothing
304 | otherwise = Just $! (mg_rdr_env tidy_result) }
305 ; final_globals `seq` return ()
307 -- Build the final ModDetails (except in one-shot mode, where
308 -- we won't need this information after compilation).
310 if one_shot then return (error "no final details")
311 else return $! ModDetails {
312 md_types = mg_types tidy_result,
313 md_insts = mg_insts tidy_result,
314 md_rules = mg_rules tidy_result }
317 -- CONVERT TO STG and COMPLETE CODE GENERATION
318 ; (stub_h_exists, stub_c_exists, maybe_bcos)
319 <- hscBackEnd dflags tidy_result
321 -- And the answer is ...
322 ; dumpIfaceStats hsc_env
324 ; return (HscRecomp final_details
327 stub_h_exists stub_c_exists
331 hscCoreFrontEnd hsc_env msg_act location = do {
335 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
336 ; case parseCore inp 1 of
337 FailP s -> putMsg s{-ToDo: wrong-} >> return (Left HscFail)
338 OkP rdr_module -> do {
341 -- RENAME and TYPECHECK
343 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
344 tcRnExtCore hsc_env rdr_module
346 ; case maybe_tc_result of {
347 Nothing -> return (Left HscFail);
348 Just mod_guts -> return (Right mod_guts)
349 -- No desugaring to do!
353 hscFileFrontEnd hsc_env msg_act location = do {
357 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
358 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
360 ; case maybe_parsed of {
361 Left err -> do { msg_act (unitBag err, emptyBag) ;
362 ; return (Left HscFail) ;
364 Right rdr_module -> hscFrontEnd hsc_env msg_act rdr_module
367 -- Perform static/dynamic checks on the source code in a StringBuffer
368 -- This is a temporary solution: it'll read in interface files lazily, whereas
369 -- we probably want to use the compilation manager to load in all the modules
371 hscBufferFrontEnd :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
372 hscBufferFrontEnd hsc_env buffer msg_act = do
373 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
374 showPass (hsc_dflags hsc_env) "Parser"
375 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
376 PFailed span err -> do
377 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
379 POk _ rdr_module -> do
380 hscBufferTypecheck hsc_env rdr_module msg_act
382 hscBufferTypecheck hsc_env rdr_module msg_act = do
383 (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
384 tcRnModule hsc_env rdr_module
386 case maybe_tc_result of
387 Nothing -> return (HscChecked rdr_module Nothing)
388 Just r -> return (HscChecked rdr_module (Just r))
389 -- space leak on rdr_module!
392 hscFrontEnd hsc_env msg_act rdr_module = do {
394 -- RENAME and TYPECHECK
396 ; (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
397 tcRnModule hsc_env rdr_module
399 ; case maybe_tc_result of {
400 Nothing -> return (Left HscFail);
401 Just tc_result -> do {
406 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
407 deSugar hsc_env tc_result
408 ; msg_act (warns, emptyBag)
409 ; case maybe_ds_result of
410 Nothing -> return (Left HscFail);
411 Just ds_result -> return (Right ds_result);
415 ModGuts{ -- This is the last use of the ModGuts in a compilation.
416 -- From now on, we just use the bits we need.
417 mg_module = this_mod,
418 mg_binds = core_binds,
420 mg_dir_imps = dir_imps,
421 mg_foreign = foreign_stubs,
422 mg_deps = dependencies } = do {
425 -- PREPARE FOR CODE GENERATION
426 -- Do saturation and convert to A-normal form
427 prepd_binds <- _scc_ "CorePrep"
428 corePrepPgm dflags core_binds type_env;
430 case dopt_HscLang dflags of
431 HscNothing -> return (False, False, Nothing)
435 do ----------------- Generate byte code ------------------
436 comp_bc <- byteCodeGen dflags prepd_binds type_env
438 ------------------ Create f-x-dynamic C-side stuff ---
439 (istub_h_exists, istub_c_exists)
440 <- outputForeignStubs dflags foreign_stubs
442 return ( istub_h_exists, istub_c_exists, Just comp_bc )
444 panic "GHC not compiled with interpreter"
449 ----------------- Convert to STG ------------------
450 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
451 myCoreToStg dflags this_mod prepd_binds
453 ------------------ Code generation ------------------
454 abstractC <- _scc_ "CodeGen"
455 codeGen dflags this_mod type_env foreign_stubs
456 dir_imps cost_centre_info stg_binds
458 ------------------ Code output -----------------------
459 (stub_h_exists, stub_c_exists)
460 <- codeOutput dflags this_mod foreign_stubs
461 dependencies abstractC
463 return (stub_h_exists, stub_c_exists, Nothing)
467 hscCmmFile :: DynFlags -> FilePath -> IO Bool
468 hscCmmFile dflags filename = do
469 maybe_cmm <- parseCmmFile dflags filename
471 Nothing -> return False
473 codeOutput dflags no_mod NoStubs noDependencies [cmm]
476 no_mod = panic "hscCmmFile: no_mod"
479 myParseModule dflags src_filename
480 = do -------------------------- Parser ----------------
481 showPass dflags "Parser"
483 buf <- hGetStringBuffer src_filename
485 let loc = mkSrcLoc (mkFastString src_filename) 1 0
487 case unP parseModule (mkPState buf loc dflags) of {
489 PFailed span err -> return (Left (mkPlainErrMsg span err));
491 POk _ rdr_module -> do {
493 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
495 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
496 (ppSourceStats False rdr_module) ;
498 return (Right rdr_module)
499 -- ToDo: free the string buffer later.
503 myCoreToStg dflags this_mod prepd_binds
505 stg_binds <- _scc_ "Core2Stg"
506 coreToStg dflags prepd_binds
508 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
509 stg2stg dflags this_mod stg_binds
511 return (stg_binds2, cost_centre_info)
515 %************************************************************************
517 \subsection{Compiling a do-statement}
519 %************************************************************************
521 When the UnlinkedBCOExpr is linked you get an HValue of type
523 When you run it you get a list of HValues that should be
524 the same length as the list of names; add them to the ClosureEnv.
526 A naked expression returns a singleton Name [it].
528 What you type The IO [HValue] that hscStmt returns
529 ------------- ------------------------------------
530 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
533 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
536 expr (of IO type) ==> expr >>= \ v -> return [v]
537 [NB: result not printed] bindings: [it]
540 expr (of non-IO type,
541 result showable) ==> let v = expr in print v >> return [v]
544 expr (of non-IO type,
545 result not showable) ==> error
549 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
551 -> InteractiveContext -- Context for compiling
552 -> String -- The statement
553 -> IO (Maybe (InteractiveContext, [Name], HValue))
555 hscStmt hsc_env icontext stmt
556 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
557 ; case maybe_stmt of {
558 Nothing -> return Nothing ; -- Parse error
559 Just Nothing -> return Nothing ; -- Empty line
560 Just (Just parsed_stmt) -> do { -- The real stuff
562 -- Rename and typecheck it
564 <- tcRnStmt hsc_env icontext parsed_stmt
566 ; case maybe_tc_result of {
567 Nothing -> return Nothing ;
568 Just (new_ic, bound_names, tc_expr) -> do {
570 -- Then desugar, code gen, and link it
571 ; hval <- compileExpr hsc_env iNTERACTIVE
572 (ic_rn_gbl_env new_ic)
576 ; return (Just (new_ic, bound_names, hval))
579 hscTcExpr -- Typecheck an expression (but don't run it)
581 -> InteractiveContext -- Context for compiling
582 -> String -- The expression
585 hscTcExpr hsc_env icontext expr
586 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
587 ; case maybe_stmt of {
588 Nothing -> return Nothing ; -- Parse error
589 Just (Just (L _ (ExprStmt expr _)))
590 -> tcRnExpr hsc_env icontext expr ;
591 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
595 hscKcType -- Find the kind of a type
597 -> InteractiveContext -- Context for compiling
598 -> String -- The type
601 hscKcType hsc_env icontext str
602 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
603 ; case maybe_type of {
604 Just ty -> tcRnType hsc_env icontext ty ;
605 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
607 Nothing -> return Nothing } }
611 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
612 hscParseStmt = hscParseThing parseStmt
614 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
615 hscParseType = hscParseThing parseType
617 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
618 hscParseIdentifier = hscParseThing parseIdentifier
620 hscParseThing :: Outputable thing
622 -> DynFlags -> String
624 -- Nothing => Parse error (message already printed)
626 hscParseThing parser dflags str
627 = do showPass dflags "Parser"
630 buf <- stringToStringBuffer str
632 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
634 case unP parser (mkPState buf loc dflags) of {
636 PFailed span err -> do { printError span err;
641 --ToDo: can't free the string buffer until we've finished this
642 -- compilation sweep and all the identifiers have gone away.
643 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
649 %************************************************************************
651 \subsection{Getting information about an identifer}
653 %************************************************************************
657 type GetInfoResult = (String, (IfaceDecl, Fixity, SrcLoc, [(IfaceInst,SrcLoc)]))
659 hscGetInfo -- like hscStmt, but deals with a single identifier
661 -> InteractiveContext -- Context for compiling
662 -> String -- The identifier
663 -> IO [GetInfoResult]
665 hscGetInfo hsc_env ic str
666 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
667 case maybe_rdr_name of {
668 Nothing -> return [];
669 Just (L _ rdr_name) -> do
671 maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
673 let -- str' is the the naked occurrence name
674 -- after stripping off qualification and parens (+)
675 str' = occNameUserString (rdrNameOcc rdr_name)
677 case maybe_tc_result of {
678 Nothing -> return [] ;
679 Just things -> return [(str', t) | t <- things]
684 %************************************************************************
686 Desugar, simplify, convert to bytecode, and link an expression
688 %************************************************************************
692 compileExpr :: HscEnv
693 -> Module -> GlobalRdrEnv -> TypeEnv
697 compileExpr hsc_env this_mod rdr_env type_env tc_expr
698 = do { let { dflags = hsc_dflags hsc_env ;
699 lint_on = dopt Opt_DoCoreLinting dflags }
702 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
705 ; flat_expr <- flattenExpr hsc_env ds_expr
708 ; simpl_expr <- simplifyExpr dflags flat_expr
710 -- Tidy it (temporary, until coreSat does cloning)
711 ; tidy_expr <- tidyCoreExpr simpl_expr
713 -- Prepare for codegen
714 ; prepd_expr <- corePrepExpr dflags tidy_expr
717 -- ToDo: improve SrcLoc
719 case lintUnfolding noSrcLoc [] prepd_expr of
720 Just err -> pprPanic "compileExpr" err
726 ; bcos <- coreExprToBCOs dflags prepd_expr
729 ; hval <- linkExpr hsc_env bcos
737 %************************************************************************
739 Statistics on reading interfaces
741 %************************************************************************
744 dumpIfaceStats :: HscEnv -> IO ()
745 dumpIfaceStats hsc_env
746 = do { eps <- readIORef (hsc_EPS hsc_env)
747 ; dumpIfSet (dump_if_trace || dump_rn_stats)
748 "Interface statistics"
751 dflags = hsc_dflags hsc_env
752 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
753 dump_if_trace = dopt Opt_D_dump_if_trace dflags