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 ( rdrNameOcc )
30 import OccName ( occNameUserString )
32 import PrelNames ( iNTERACTIVE )
33 import StringBuffer ( stringToStringBuffer )
36 import CoreLint ( lintUnfolding )
37 import DsMeta ( templateHaskellNames )
38 import BasicTypes ( Fixity )
41 import RdrName ( RdrName )
42 import HsSyn ( HsModule )
43 import SrcLoc ( SrcLoc, noSrcLoc, Located(..) )
44 import StringBuffer ( hGetStringBuffer )
46 import Lexer ( P(..), ParseResult(..), mkPState )
47 import SrcLoc ( mkSrcLoc )
48 import TcRnDriver ( tcRnModule, tcRnExtCore )
49 import TcIface ( typecheckIface )
50 import IfaceEnv ( initNameCache )
51 import LoadIface ( ifaceStats, initExternalPackageState )
52 import PrelInfo ( wiredInThings, basicKnownKeyNames )
53 import RdrName ( GlobalRdrEnv )
54 import MkIface ( checkOldIface, mkIface )
56 import Flattening ( flatten )
58 import TidyPgm ( tidyCorePgm )
59 import CorePrep ( corePrepPgm )
60 import CoreToStg ( coreToStg )
61 import Name ( Name, NamedThing(..) )
62 import SimplStg ( stg2stg )
63 import CodeGen ( codeGen )
64 import CmmParse ( parseCmmFile )
65 import CodeOutput ( codeOutput )
68 import DriverPhases ( isExtCoreFilename )
70 import UniqSupply ( mkSplitUniqSupply )
73 import HscStats ( ppSourceStats )
75 import MkExternalCore ( emitExternalCore )
77 import ParserCoreUtils
78 import Module ( Module, ModLocation(..), showModMsg )
80 import Maybes ( expectJust )
81 import StringBuffer ( StringBuffer )
82 import Bag ( unitBag, emptyBag )
85 import Maybe ( isJust, fromJust )
87 import DATA_IOREF ( newIORef, readIORef )
91 %************************************************************************
95 %************************************************************************
98 newHscEnv :: GhciMode -> DynFlags -> IO HscEnv
99 newHscEnv ghci_mode dflags
100 = do { eps_var <- newIORef initExternalPackageState
101 ; us <- mkSplitUniqSupply 'r'
102 ; nc_var <- newIORef (initNameCache us knownKeyNames)
103 ; return (HscEnv { hsc_mode = ghci_mode,
105 hsc_HPT = emptyHomePackageTable,
107 hsc_NC = nc_var } ) }
110 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
111 -- where templateHaskellNames are defined
112 knownKeyNames = map getName wiredInThings
113 ++ basicKnownKeyNames
115 ++ templateHaskellNames
120 %************************************************************************
122 The main compiler pipeline
124 %************************************************************************
128 -- Compilation failed
131 -- In IDE mode: we just do the static/dynamic checks
132 | HscChecked (Located (HsModule RdrName))
134 -- Concluded that it wasn't necessary
135 | HscNoRecomp ModDetails -- new details (HomeSymbolTable additions)
136 ModIface -- new iface (if any compilation was done)
139 | HscRecomp ModDetails -- new details (HomeSymbolTable additions)
141 ModIface -- new iface (if any compilation was done)
142 Bool -- stub_h exists
143 Bool -- stub_c exists
144 (Maybe CompiledByteCode)
147 -- What to do when we have compiler error or warning messages
148 type MessageAction = Messages -> IO ()
150 -- no errors or warnings; the individual passes
151 -- (parse/rename/typecheck) print messages themselves
155 -> MessageAction -- what to do with errors/warnings
157 -> ModLocation -- location info
158 -> Bool -- True <=> source unchanged
159 -> Bool -- True <=> have an object file (for msgs only)
160 -> Maybe ModIface -- old interface, if available
163 hscMain hsc_env msg_act mod location
164 source_unchanged have_object maybe_old_iface
166 (recomp_reqd, maybe_checked_iface) <-
167 _scc_ "checkOldIface"
168 checkOldIface hsc_env mod
169 (ml_hi_file location)
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 have_object
177 mod location maybe_checked_iface
181 -- hscNoRecomp definitely expects to have the old interface available
182 hscNoRecomp hsc_env msg_act have_object
183 mod location (Just old_iface)
184 | isOneShot (hsc_mode hsc_env)
186 compilationProgressMsg (hsc_dflags hsc_env) $
187 "compilation IS NOT required";
188 dumpIfaceStats hsc_env ;
190 let { bomb = panic "hscNoRecomp:OneShot" };
191 return (HscNoRecomp bomb bomb)
195 compilationProgressMsg (hsc_dflags hsc_env) $
196 ("Skipping " ++ showModMsg have_object mod location);
198 new_details <- _scc_ "tcRnIface"
199 typecheckIface hsc_env old_iface ;
200 dumpIfaceStats hsc_env ;
202 return (HscNoRecomp new_details old_iface)
205 hscRecomp hsc_env msg_act have_object
206 mod location maybe_checked_iface
208 -- what target are we shooting for?
209 ; let one_shot = isOneShot (hsc_mode hsc_env)
210 ; let dflags = hsc_dflags hsc_env
211 ; let toInterp = dopt_HscLang dflags == HscInterpreted
212 ; let toCore = isJust (ml_hs_file location) &&
213 isExtCoreFilename (fromJust (ml_hs_file location))
215 ; when (not one_shot) $
216 compilationProgressMsg dflags $
217 ("Compiling " ++ showModMsg (not toInterp) mod location);
219 ; front_res <- if toCore then
220 hscCoreFrontEnd hsc_env msg_act location
222 hscFileFrontEnd hsc_env msg_act location
225 Left flure -> return flure;
226 Right ds_result -> do {
230 -- ; seqList imported_modules (return ())
235 ; flat_result <- _scc_ "Flattening"
236 flatten hsc_env ds_result
239 {- TEMP: need to review space-leak fixing here
240 NB: even the code generator can force one of the
241 thunks for constructor arguments, for newtypes in particular
243 ; let -- Rule-base accumulated from imported packages
244 pkg_rule_base = eps_rule_base (hsc_EPS hsc_env)
246 -- In one-shot mode, ZAP the external package state at
247 -- this point, because we aren't going to need it from
248 -- now on. We keep the name cache, however, because
249 -- tidyCore needs it.
251 | one_shot = pcs_tc{ pcs_EPS = error "pcs_EPS missing" }
254 ; pkg_rule_base `seq` pcs_middle `seq` return ()
257 -- alive at this point:
265 ; simpl_result <- _scc_ "Core2Core"
266 core2core hsc_env flat_result
271 ; tidy_result <- _scc_ "CoreTidy"
272 tidyCorePgm hsc_env simpl_result
274 -- Emit external core
275 ; emitExternalCore dflags tidy_result
277 -- Alive at this point:
278 -- tidy_result, pcs_final
282 -- BUILD THE NEW ModIface and ModDetails
283 -- and emit external core if necessary
284 -- This has to happen *after* code gen so that the back-end
285 -- info has been set. Not yet clear if it matters waiting
286 -- until after code output
287 ; new_iface <- _scc_ "MkFinalIface"
288 mkIface hsc_env location
289 maybe_checked_iface tidy_result
292 -- Space leak reduction: throw away the new interface if
293 -- we're in one-shot mode; we won't be needing it any
296 if one_shot then return (error "no final iface")
297 else return new_iface
298 ; let { final_globals | one_shot = Nothing
299 | otherwise = Just $! (mg_rdr_env tidy_result) }
300 ; final_globals `seq` return ()
302 -- Build the final ModDetails (except in one-shot mode, where
303 -- we won't need this information after compilation).
305 if one_shot then return (error "no final details")
306 else return $! ModDetails {
307 md_types = mg_types tidy_result,
308 md_insts = mg_insts tidy_result,
309 md_rules = mg_rules tidy_result }
312 -- CONVERT TO STG and COMPLETE CODE GENERATION
313 ; (stub_h_exists, stub_c_exists, maybe_bcos)
314 <- hscBackEnd dflags tidy_result
316 -- And the answer is ...
317 ; dumpIfaceStats hsc_env
319 ; return (HscRecomp final_details
322 stub_h_exists stub_c_exists
326 hscCoreFrontEnd hsc_env msg_act location = do {
330 ; inp <- readFile (expectJust "hscCoreFrontEnd:hspp" (ml_hspp_file location))
331 ; case parseCore inp 1 of
332 FailP s -> putMsg s{-ToDo: wrong-} >> return (Left HscFail)
333 OkP rdr_module -> do {
336 -- RENAME and TYPECHECK
338 ; (tc_msgs, maybe_tc_result) <- _scc_ "TypeCheck"
339 tcRnExtCore hsc_env rdr_module
341 ; case maybe_tc_result of {
342 Nothing -> return (Left HscFail);
343 Just mod_guts -> return (Right mod_guts)
344 -- No desugaring to do!
348 hscFileFrontEnd hsc_env msg_act location = do {
352 ; maybe_parsed <- myParseModule (hsc_dflags hsc_env)
353 (expectJust "hscFrontEnd:hspp" (ml_hspp_file location))
355 ; case maybe_parsed of {
356 Left err -> do { msg_act (unitBag err, emptyBag) ;
357 ; return (Left HscFail) ;
359 Right rdr_module -> hscFrontEnd hsc_env msg_act rdr_module
362 -- Perform static/dynamic checks on the source code in a StringBuffer
363 -- This is a temporary solution: it'll read in interface files lazily, whereas
364 -- we probably want to use the compilation manager to load in all the modules
366 hscBufferFrontEnd :: HscEnv -> StringBuffer -> MessageAction -> IO HscResult
367 hscBufferFrontEnd hsc_env buffer msg_act = do
368 let loc = mkSrcLoc (mkFastString "*edit*") 1 0
369 showPass (hsc_dflags hsc_env) "Parser"
370 case unP parseModule (mkPState buffer loc (hsc_dflags hsc_env)) of
371 PFailed span err -> do
372 msg_act (emptyBag, unitBag (mkPlainErrMsg span err))
374 POk _ rdr_module -> do
375 r <- hscFrontEnd hsc_env msg_act rdr_module
378 Right _ -> return (HscChecked rdr_module)
382 hscFrontEnd hsc_env msg_act rdr_module = do {
384 -- RENAME and TYPECHECK
386 ; (tc_msgs, maybe_tc_result) <- _scc_ "Typecheck-Rename"
387 tcRnModule hsc_env rdr_module
389 ; case maybe_tc_result of {
390 Nothing -> return (Left HscFail);
391 Just tc_result -> do {
396 ; (warns, maybe_ds_result) <- _scc_ "DeSugar"
397 deSugar hsc_env tc_result
398 ; msg_act (warns, emptyBag)
399 ; case maybe_ds_result of
400 Nothing -> return (Left HscFail);
401 Just ds_result -> return (Right ds_result);
405 ModGuts{ -- This is the last use of the ModGuts in a compilation.
406 -- From now on, we just use the bits we need.
407 mg_module = this_mod,
408 mg_binds = core_binds,
410 mg_dir_imps = dir_imps,
411 mg_foreign = foreign_stubs,
412 mg_deps = dependencies } = do {
415 -- PREPARE FOR CODE GENERATION
416 -- Do saturation and convert to A-normal form
417 prepd_binds <- _scc_ "CorePrep"
418 corePrepPgm dflags core_binds type_env;
420 case dopt_HscLang dflags of
421 HscNothing -> return (False, False, Nothing)
425 do ----------------- Generate byte code ------------------
426 comp_bc <- byteCodeGen dflags prepd_binds type_env
428 ------------------ Create f-x-dynamic C-side stuff ---
429 (istub_h_exists, istub_c_exists)
430 <- outputForeignStubs dflags foreign_stubs
432 return ( istub_h_exists, istub_c_exists, Just comp_bc )
434 panic "GHC not compiled with interpreter"
439 ----------------- Convert to STG ------------------
440 (stg_binds, cost_centre_info) <- _scc_ "CoreToStg"
441 myCoreToStg dflags this_mod prepd_binds
443 ------------------ Code generation ------------------
444 abstractC <- _scc_ "CodeGen"
445 codeGen dflags this_mod type_env foreign_stubs
446 dir_imps cost_centre_info stg_binds
448 ------------------ Code output -----------------------
449 (stub_h_exists, stub_c_exists)
450 <- codeOutput dflags this_mod foreign_stubs
451 dependencies abstractC
453 return (stub_h_exists, stub_c_exists, Nothing)
457 hscCmmFile :: DynFlags -> FilePath -> IO Bool
458 hscCmmFile dflags filename = do
459 maybe_cmm <- parseCmmFile dflags filename
461 Nothing -> return False
463 codeOutput dflags no_mod NoStubs noDependencies [cmm]
466 no_mod = panic "hscCmmFile: no_mod"
469 myParseModule dflags src_filename
470 = do -------------------------- Parser ----------------
471 showPass dflags "Parser"
473 buf <- hGetStringBuffer src_filename
475 let loc = mkSrcLoc (mkFastString src_filename) 1 0
477 case unP parseModule (mkPState buf loc dflags) of {
479 PFailed span err -> return (Left (mkPlainErrMsg span err));
481 POk _ rdr_module -> do {
483 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
485 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
486 (ppSourceStats False rdr_module) ;
488 return (Right rdr_module)
489 -- ToDo: free the string buffer later.
493 myCoreToStg dflags this_mod prepd_binds
495 stg_binds <- _scc_ "Core2Stg"
496 coreToStg dflags prepd_binds
498 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
499 stg2stg dflags this_mod stg_binds
501 return (stg_binds2, cost_centre_info)
505 %************************************************************************
507 \subsection{Compiling a do-statement}
509 %************************************************************************
511 When the UnlinkedBCOExpr is linked you get an HValue of type
513 When you run it you get a list of HValues that should be
514 the same length as the list of names; add them to the ClosureEnv.
516 A naked expression returns a singleton Name [it].
518 What you type The IO [HValue] that hscStmt returns
519 ------------- ------------------------------------
520 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
523 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
526 expr (of IO type) ==> expr >>= \ v -> return [v]
527 [NB: result not printed] bindings: [it]
530 expr (of non-IO type,
531 result showable) ==> let v = expr in print v >> return [v]
534 expr (of non-IO type,
535 result not showable) ==> error
539 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
541 -> InteractiveContext -- Context for compiling
542 -> String -- The statement
543 -> IO (Maybe (InteractiveContext, [Name], HValue))
545 hscStmt hsc_env icontext stmt
546 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
547 ; case maybe_stmt of {
548 Nothing -> return Nothing ; -- Parse error
549 Just Nothing -> return Nothing ; -- Empty line
550 Just (Just parsed_stmt) -> do { -- The real stuff
552 -- Rename and typecheck it
554 <- tcRnStmt hsc_env icontext parsed_stmt
556 ; case maybe_tc_result of {
557 Nothing -> return Nothing ;
558 Just (new_ic, bound_names, tc_expr) -> do {
560 -- Then desugar, code gen, and link it
561 ; hval <- compileExpr hsc_env iNTERACTIVE
562 (ic_rn_gbl_env new_ic)
566 ; return (Just (new_ic, bound_names, hval))
569 hscTcExpr -- Typecheck an expression (but don't run it)
571 -> InteractiveContext -- Context for compiling
572 -> String -- The expression
575 hscTcExpr hsc_env icontext expr
576 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
577 ; case maybe_stmt of {
578 Nothing -> return Nothing ; -- Parse error
579 Just (Just (L _ (ExprStmt expr _)))
580 -> tcRnExpr hsc_env icontext expr ;
581 Just other -> do { errorMsg ("not an expression: `" ++ expr ++ "'") ;
585 hscKcType -- Find the kind of a type
587 -> InteractiveContext -- Context for compiling
588 -> String -- The type
591 hscKcType hsc_env icontext str
592 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
593 ; case maybe_type of {
594 Just ty -> tcRnType hsc_env icontext ty ;
595 Just other -> do { errorMsg ("not an type: `" ++ str ++ "'") ;
597 Nothing -> return Nothing } }
601 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
602 hscParseStmt = hscParseThing parseStmt
604 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
605 hscParseType = hscParseThing parseType
607 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
608 hscParseIdentifier = hscParseThing parseIdentifier
610 hscParseThing :: Outputable thing
612 -> DynFlags -> String
614 -- Nothing => Parse error (message already printed)
616 hscParseThing parser dflags str
617 = do showPass dflags "Parser"
620 buf <- stringToStringBuffer str
622 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
624 case unP parser (mkPState buf loc dflags) of {
626 PFailed span err -> do { printError span err;
631 --ToDo: can't free the string buffer until we've finished this
632 -- compilation sweep and all the identifiers have gone away.
633 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
639 %************************************************************************
641 \subsection{Getting information about an identifer}
643 %************************************************************************
647 type GetInfoResult = (String, (IfaceDecl, Fixity, SrcLoc, [(IfaceInst,SrcLoc)]))
649 hscGetInfo -- like hscStmt, but deals with a single identifier
651 -> InteractiveContext -- Context for compiling
652 -> String -- The identifier
653 -> IO [GetInfoResult]
655 hscGetInfo hsc_env ic str
656 = do maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
657 case maybe_rdr_name of {
658 Nothing -> return [];
659 Just (L _ rdr_name) -> do
661 maybe_tc_result <- tcRnGetInfo hsc_env ic rdr_name
663 let -- str' is the the naked occurrence name
664 -- after stripping off qualification and parens (+)
665 str' = occNameUserString (rdrNameOcc rdr_name)
667 case maybe_tc_result of {
668 Nothing -> return [] ;
669 Just things -> return [(str', t) | t <- things]
674 %************************************************************************
676 Desugar, simplify, convert to bytecode, and link an expression
678 %************************************************************************
682 compileExpr :: HscEnv
683 -> Module -> GlobalRdrEnv -> TypeEnv
687 compileExpr hsc_env this_mod rdr_env type_env tc_expr
688 = do { let { dflags = hsc_dflags hsc_env ;
689 lint_on = dopt Opt_DoCoreLinting dflags }
692 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
695 ; flat_expr <- flattenExpr hsc_env ds_expr
698 ; simpl_expr <- simplifyExpr dflags flat_expr
700 -- Tidy it (temporary, until coreSat does cloning)
701 ; tidy_expr <- tidyCoreExpr simpl_expr
703 -- Prepare for codegen
704 ; prepd_expr <- corePrepExpr dflags tidy_expr
707 -- ToDo: improve SrcLoc
709 case lintUnfolding noSrcLoc [] prepd_expr of
710 Just err -> pprPanic "compileExpr" err
716 ; bcos <- coreExprToBCOs dflags prepd_expr
719 ; hval <- linkExpr hsc_env bcos
727 %************************************************************************
729 Statistics on reading interfaces
731 %************************************************************************
734 dumpIfaceStats :: HscEnv -> IO ()
735 dumpIfaceStats hsc_env
736 = do { eps <- readIORef (hsc_EPS hsc_env)
737 ; dumpIfSet (dump_if_trace || dump_rn_stats)
738 "Interface statistics"
741 dflags = hsc_dflags hsc_env
742 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
743 dump_if_trace = dopt Opt_D_dump_if_trace dflags