2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 HscResult(..), hscMain, newHscEnv, hscCmmFile, hscBufferFrontEnd
11 , hscStmt, hscTcExpr, hscKcType
12 , hscGetInfo, GetInfoResult
17 #include "HsVersions.h"
20 import HsSyn ( Stmt(..), LStmt, LHsExpr, LHsType )
21 import IfaceSyn ( IfaceDecl, IfaceInst )
22 import CodeOutput ( outputForeignStubs )
23 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
24 import Linker ( HValue, linkExpr )
25 import TidyPgm ( tidyCoreExpr )
26 import CorePrep ( corePrepExpr )
27 import Flattening ( flattenExpr )
28 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnGetInfo, tcRnType )
29 import RdrName ( RdrName, rdrNameOcc )
30 import OccName ( occNameUserString )
32 import PrelNames ( iNTERACTIVE )
33 import StringBuffer ( stringToStringBuffer )
34 import SrcLoc ( SrcLoc, noSrcLoc, Located(..) )
37 import CoreLint ( lintUnfolding )
38 import DsMeta ( templateHaskellNames )
39 import BasicTypes ( Fixity )
42 import StringBuffer ( hGetStringBuffer )
44 import Lexer ( P(..), ParseResult(..), mkPState )
45 import SrcLoc ( mkSrcLoc )
46 import TcRnDriver ( tcRnModule, tcRnExtCore )
47 import TcIface ( typecheckIface )
48 import IfaceEnv ( initNameCache )
49 import LoadIface ( ifaceStats, initExternalPackageState )
50 import PrelInfo ( wiredInThings, basicKnownKeyNames )
51 import RdrName ( GlobalRdrEnv )
52 import MkIface ( checkOldIface, mkIface )
54 import Flattening ( flatten )
56 import TidyPgm ( tidyCorePgm )
57 import CorePrep ( corePrepPgm )
58 import CoreToStg ( coreToStg )
59 import Name ( Name, NamedThing(..) )
60 import SimplStg ( stg2stg )
61 import CodeGen ( codeGen )
62 import CmmParse ( parseCmmFile )
63 import CodeOutput ( codeOutput )
66 import DriverPhases ( isExtCoreFilename )
68 import UniqSupply ( mkSplitUniqSupply )
71 import HscStats ( ppSourceStats )
73 import MkExternalCore ( emitExternalCore )
75 import ParserCoreUtils
76 import Module ( Module, ModLocation(..), showModMsg )
78 import Maybes ( expectJust )
79 import StringBuffer ( StringBuffer )
80 import Bag ( unitBag, emptyBag )
83 import Maybe ( isJust, fromJust )
85 import DATA_IOREF ( newIORef, readIORef )
89 %************************************************************************
93 %************************************************************************
96 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
97 newHscEnv ghci_mode dflags
98 = do { eps_var <- newIORef initExternalPackageState
99 ; us <- mkSplitUniqSupply 'r'
100 ; nc_var <- newIORef (initNameCache us knownKeyNames)
101 ; return (HscEnv { hsc_mode = ghci_mode,
103 hsc_HPT = emptyHomePackageTable,
105 hsc_NC = nc_var } ) }
108 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
109 -- where templateHaskellNames are defined
110 knownKeyNames = map getName wiredInThings
111 ++ basicKnownKeyNames
113 ++ templateHaskellNames
118 %************************************************************************
120 The main compiler pipeline
122 %************************************************************************
126 -- Compilation failed
129 -- In IDE mode: we just do the static/dynamic checks
132 -- Concluded that it wasn't necessary
133 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
134 ModIface -- new iface (if any compilation was done)
137 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
139 ModIface -- new iface (if any compilation was done)
140 Bool -- stub_h exists
141 Bool -- stub_c exists
142 (Maybe CompiledByteCode)
145 -- What to do when we have compiler error or warning messages
146 type MessageAction = Messages -> IO ()
148 -- no errors or warnings; the individual passes
149 -- (parse/rename/typecheck) print messages themselves
153 -> MessageAction -- what to do with errors/warnings
155 -> ModLocation -- location info
156 -> Bool -- True <=> source unchanged
157 -> Bool -- True <=> have an object file (for msgs only)
158 -> Maybe ModIface -- old interface, if available
161 hscMain hsc_env msg_act mod location
162 source_unchanged have_object maybe_old_iface
164 (recomp_reqd, maybe_checked_iface) <-
165 _scc_ "checkOldIface"
166 checkOldIface hsc_env mod
167 (ml_hi_file location)
168 source_unchanged maybe_old_iface;
170 let no_old_iface = not (isJust maybe_checked_iface)
171 what_next | recomp_reqd || no_old_iface = hscRecomp
172 | otherwise = hscNoRecomp
174 ; what_next hsc_env msg_act have_object
175 mod location maybe_checked_iface
179 -- hscNoRecomp definitely expects to have the old interface available
180 hscNoRecomp hsc_env msg_act have_object
181 mod location (Just old_iface)
182 | isOneShot (hsc_mode hsc_env)
184 when (verbosity (hsc_dflags hsc_env) > 0) $
185 hPutStrLn stderr "compilation IS NOT required";
186 dumpIfaceStats hsc_env ;
188 let { bomb = panic "hscNoRecomp:OneShot" };
189 return (HscNoRecomp bomb bomb)
193 when (verbosity (hsc_dflags hsc_env) >= 1) $
194 hPutStrLn stderr ("Skipping " ++
195 showModMsg have_object mod location);
197 new_details <- _scc_ "tcRnIface"
198 typecheckIface hsc_env old_iface ;
199 dumpIfaceStats hsc_env ;
201 return (HscNoRecomp new_details old_iface)
204 hscRecomp hsc_env msg_act have_object
205 mod location maybe_checked_iface
207 -- what target are we shooting for?
208 ; let one_shot = isOneShot (hsc_mode hsc_env)
209 ; let dflags = hsc_dflags hsc_env
210 ; let toInterp = dopt_HscLang dflags == HscInterpreted
211 ; let toCore = isJust (ml_hs_file location) &&
212 isExtCoreFilename (fromJust (ml_hs_file location))
214 ; when (not one_shot && verbosity dflags >= 1) $
215 hPutStrLn stderr ("Compiling " ++
216 showModMsg (not toInterp) mod location);
218 ; front_res <- if toCore then
219 hscCoreFrontEnd hsc_env msg_act location
221 hscFileFrontEnd hsc_env msg_act location
224 Left flure -> return flure;
225 Right ds_result -> do {
229 -- ; seqList imported_modules (return ())
234 ; flat_result <- _scc_ "Flattening"
235 flatten hsc_env ds_result
238 {- TEMP: need to review space-leak fixing here
239 NB: even the code generator can force one of the
240 thunks for constructor arguments, for newtypes in particular
242 ; let -- Rule-base accumulated from imported packages
243 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
245 -- In one-shot mode, ZAP the external package state at
246 -- this point, because we aren't going to need it from
247 -- now on. We keep the name cache, however, because
248 -- tidyCore needs it.
250 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
253 ; pkg_rule_base `seq` pcs_middle `seq` return ()
256 -- alive at this point:
264 ; simpl_result <- _scc_ "Core2Core"
265 core2core hsc_env flat_result
270 ; tidy_result <- _scc_ "CoreTidy"
271 tidyCorePgm hsc_env simpl_result
273 -- Emit external core
274 ; emitExternalCore dflags tidy_result
276 -- Alive at this point:
277 -- tidy_result, pcs_final
281 -- BUILD THE NEW ModIface and ModDetails
282 -- and emit external core if necessary
283 -- This has to happen *after* code gen so that the back-end
284 -- info has been set. Not yet clear if it matters waiting
285 -- until after code output
286 ; new_iface <- _scc_ "MkFinalIface"
287 mkIface hsc_env location
288 maybe_checked_iface tidy_result
291 -- Space leak reduction: throw away the new interface if
292 -- we're in one-shot mode; we won't be needing it any
295 if one_shot then return (error "no final iface")
296 else return new_iface
297 ; let { final_globals | one_shot = Nothing
298 | otherwise = Just $! (mg_rdr_env tidy_result) }
299 ; final_globals `seq` return ()
301 -- Build the final ModDetails (except in one-shot mode, where
302 -- we won't need this information after compilation).
304 if one_shot then return (error "no final details")
305 else return $! ModDetails {
306 md_types = mg_types tidy_result,
307 md_insts = mg_insts tidy_result,
308 md_rules = mg_rules tidy_result }
311 -- CONVERT TO STG and COMPLETE CODE GENERATION
312 ; (stub_h_exists, stub_c_exists, maybe_bcos)
313 <- hscBackEnd dflags tidy_result
315 -- And the answer is ...
316 ; dumpIfaceStats hsc_env
318 ; return (HscRecomp final_details
321 stub_h_exists stub_c_exists
325 hscCoreFrontEnd hsc_env msg_act location = do {
329 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
330 ; case parseCore inp 1 of
331 FailP s -> hPutStrLn stderr s >> return (Left HscFail)
332 OkP rdr_module -> do {
335 -- RENAME and TYPECHECK
337 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
338 tcRnExtCore hsc_env rdr_module
340 ; case maybe_tc_result of {
341 Nothing -> return (Left HscFail);
342 Just mod_guts -> return (Right mod_guts)
343 -- No desugaring to do!
347 hscFileFrontEnd hsc_env msg_act location = do {
351 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
352 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
354 ; case maybe_parsed of {
355 Left err -> do { msg_act (unitBag err, emptyBag) ;
356 ; return (Left HscFail) ;
358 Right rdr_module -> hscFrontEnd hsc_env msg_act rdr_module
361 -- Perform static/dynamic checks on the source code in a StringBuffer
362 -- This is a temporary solution: it'll read in interface files lazily, whereas
363 -- we probably want to use the compilation manager to load in all the modules
365 hscBufferFrontEnd :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
366 hscBufferFrontEnd hsc_env buffer msg_act = do
367 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
368 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
369 PFailed span err -> do
370 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
372 POk _ rdr_module -> do
373 r <- hscFrontEnd hsc_env msg_act rdr_module
376 Right _ -> return HscChecked
380 hscFrontEnd hsc_env msg_act rdr_module = do {
382 -- RENAME and TYPECHECK
384 ; (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
385 tcRnModule hsc_env rdr_module
387 ; case maybe_tc_result of {
388 Nothing -> return (Left HscFail);
389 Just tc_result -> do {
394 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
395 deSugar hsc_env tc_result
396 ; msg_act (warns, emptyBag)
397 ; case maybe_ds_result of
398 Nothing -> return (Left HscFail);
399 Just ds_result -> return (Right ds_result);
403 ModGuts{ -- This is the last use of the ModGuts in a compilation.
404 -- From now on, we just use the bits we need.
405 mg_module = this_mod,
406 mg_binds = core_binds,
408 mg_dir_imps = dir_imps,
409 mg_foreign = foreign_stubs,
410 mg_deps = dependencies } = do {
413 -- PREPARE FOR CODE GENERATION
414 -- Do saturation and convert to A-normal form
415 prepd_binds <- _scc_ "CorePrep"
416 corePrepPgm dflags core_binds type_env;
418 case dopt_HscLang dflags of
419 HscNothing -> return (False, False, Nothing)
423 do ----------------- Generate byte code ------------------
424 comp_bc <- byteCodeGen dflags prepd_binds type_env
426 ------------------ Create f-x-dynamic C-side stuff ---
427 (istub_h_exists, istub_c_exists)
428 <- outputForeignStubs dflags foreign_stubs
430 return ( istub_h_exists, istub_c_exists, Just comp_bc )
432 panic "GHC not compiled with interpreter"
437 ----------------- Convert to STG ------------------
438 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
439 myCoreToStg dflags this_mod prepd_binds
441 ------------------ Code generation ------------------
442 abstractC <- _scc_ "CodeGen"
443 codeGen dflags this_mod type_env foreign_stubs
444 dir_imps cost_centre_info stg_binds
446 ------------------ Code output -----------------------
447 (stub_h_exists, stub_c_exists)
448 <- codeOutput dflags this_mod foreign_stubs
449 dependencies abstractC
451 return (stub_h_exists, stub_c_exists, Nothing)
455 hscCmmFile :: DynFlags -> FilePath -> IO Bool
456 hscCmmFile dflags filename = do
457 maybe_cmm <- parseCmmFile dflags filename
459 Nothing -> return False
461 codeOutput dflags no_mod NoStubs noDependencies [cmm]
464 no_mod = panic "hscCmmFile: no_mod"
467 myParseModule dflags src_filename
468 = do -------------------------- Parser ----------------
469 showPass dflags "Parser"
471 buf <- hGetStringBuffer src_filename
473 let loc = mkSrcLoc (mkFastString src_filename) 1 0
475 case unP parseModule (mkPState buf loc dflags) of {
477 PFailed span err -> return (Left (mkPlainErrMsg span err));
479 POk _ rdr_module -> do {
481 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
483 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
484 (ppSourceStats False rdr_module) ;
486 return (Right rdr_module)
487 -- ToDo: free the string buffer later.
491 myCoreToStg dflags this_mod prepd_binds
493 stg_binds <- _scc_ "Core2Stg"
494 coreToStg dflags prepd_binds
496 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
497 stg2stg dflags this_mod stg_binds
499 return (stg_binds2, cost_centre_info)
503 %************************************************************************
505 \subsection{Compiling a do-statement}
507 %************************************************************************
509 When the UnlinkedBCOExpr is linked you get an HValue of type
511 When you run it you get a list of HValues that should be
512 the same length as the list of names; add them to the ClosureEnv.
514 A naked expression returns a singleton Name [it].
516 What you type The IO [HValue] that hscStmt returns
517 ------------- ------------------------------------
518 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
521 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
524 expr (of IO type) ==> expr >>= \ v -> return [v]
525 [NB: result not printed] bindings: [it]
528 expr (of non-IO type,
529 result showable) ==> let v = expr in print v >> return [v]
532 expr (of non-IO type,
533 result not showable) ==> error
537 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
539 -> InteractiveContext -- Context for compiling
540 -> String -- The statement
541 -> IO (Maybe (InteractiveContext, [Name], HValue))
543 hscStmt hsc_env icontext stmt
544 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
545 ; case maybe_stmt of {
546 Nothing -> return Nothing ; -- Parse error
547 Just Nothing -> return Nothing ; -- Empty line
548 Just (Just parsed_stmt) -> do { -- The real stuff
550 -- Rename and typecheck it
552 <- tcRnStmt hsc_env icontext parsed_stmt
554 ; case maybe_tc_result of {
555 Nothing -> return Nothing ;
556 Just (new_ic, bound_names, tc_expr) -> do {
558 -- Then desugar, code gen, and link it
559 ; hval <- compileExpr hsc_env iNTERACTIVE
560 (ic_rn_gbl_env new_ic)
564 ; return (Just (new_ic, bound_names, hval))
567 hscTcExpr -- Typecheck an expression (but don't run it)
569 -> InteractiveContext -- Context for compiling
570 -> String -- The expression
573 hscTcExpr hsc_env icontext expr
574 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
575 ; case maybe_stmt of {
576 Nothing -> return Nothing ; -- Parse error
577 Just (Just (L _ (ExprStmt expr _)))
578 -> tcRnExpr hsc_env icontext expr ;
579 Just other -> do { hPutStrLn stderr ("not an expression: `" ++ expr ++ "'") ;
583 hscKcType -- Find the kind of a type
585 -> InteractiveContext -- Context for compiling
586 -> String -- The type
589 hscKcType hsc_env icontext str
590 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
591 ; case maybe_type of {
592 Just ty -> tcRnType hsc_env icontext ty ;
593 Just other -> do { hPutStrLn stderr ("not an type: `" ++ str ++ "'") ;
595 Nothing -> return Nothing } }
599 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
600 hscParseStmt = hscParseThing parseStmt
602 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
603 hscParseType = hscParseThing parseType
605 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
606 hscParseIdentifier = hscParseThing parseIdentifier
608 hscParseThing :: Outputable thing
610 -> DynFlags -> String
612 -- Nothing => Parse error (message already printed)
614 hscParseThing parser dflags str
615 = do showPass dflags "Parser"
618 buf <- stringToStringBuffer str
620 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
622 case unP parser (mkPState buf loc dflags) of {
624 PFailed span err -> do { printError span err;
629 --ToDo: can't free the string buffer until we've finished this
630 -- compilation sweep and all the identifiers have gone away.
631 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
637 %************************************************************************
639 \subsection{Getting information about an identifer}
641 %************************************************************************
645 type GetInfoResult = (String, (IfaceDecl, Fixity, SrcLoc, [(IfaceInst,SrcLoc)]))
647 hscGetInfo -- like hscStmt, but deals with a single identifier
649 -> InteractiveContext -- Context for compiling
650 -> String -- The identifier
651 -> IO [GetInfoResult]
653 hscGetInfo hsc_env ic str
654 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
655 case maybe_rdr_name of {
656 Nothing -> return [];
657 Just (L _ rdr_name) -> do
659 maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
661 let -- str' is the the naked occurrence name
662 -- after stripping off qualification and parens (+)
663 str' = occNameUserString (rdrNameOcc rdr_name)
665 case maybe_tc_result of {
666 Nothing -> return [] ;
667 Just things -> return [(str', t) | t <- things]
672 %************************************************************************
674 Desugar, simplify, convert to bytecode, and link an expression
676 %************************************************************************
680 compileExpr :: HscEnv
681 -> Module -> GlobalRdrEnv -> TypeEnv
685 compileExpr hsc_env this_mod rdr_env type_env tc_expr
686 = do { let { dflags = hsc_dflags hsc_env ;
687 lint_on = dopt Opt_DoCoreLinting dflags }
690 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
693 ; flat_expr <- flattenExpr hsc_env ds_expr
696 ; simpl_expr <- simplifyExpr dflags flat_expr
698 -- Tidy it (temporary, until coreSat does cloning)
699 ; tidy_expr <- tidyCoreExpr simpl_expr
701 -- Prepare for codegen
702 ; prepd_expr <- corePrepExpr dflags tidy_expr
705 -- ToDo: improve SrcLoc
707 case lintUnfolding noSrcLoc [] prepd_expr of
708 Just err -> pprPanic "compileExpr" err
714 ; bcos <- coreExprToBCOs dflags prepd_expr
717 ; hval <- linkExpr hsc_env bcos
725 %************************************************************************
727 Statistics on reading interfaces
729 %************************************************************************
732 dumpIfaceStats :: HscEnv -> IO ()
733 dumpIfaceStats hsc_env
734 = do { eps <- readIORef (hsc_EPS hsc_env)
735 ; dumpIfSet (dump_if_trace || dump_rn_stats)
736 "Interface statistics"
739 dflags = hsc_dflags hsc_env
740 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
741 dump_if_trace = dopt Opt_D_dump_if_trace dflags