2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
8 module HscMain ( HscResult(..), hscMain,
12 initPersistentCompilerState ) where
14 #include "HsVersions.h"
17 import ByteCodeGen ( byteCodeGen )
18 import CoreTidy ( tidyCoreExpr )
19 import CorePrep ( corePrepExpr )
20 import Rename ( renameStmt )
21 import RdrHsSyn ( RdrNameStmt )
23 import Id ( Id, idName, setGlobalIdDetails )
24 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
25 import HscTypes ( InteractiveContext(..) )
26 import PrelNames ( iNTERACTIVE )
27 import StringBuffer ( stringToStringBuffer )
33 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
34 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
36 import Lex ( PState(..), ParseResult(..) )
37 import SrcLoc ( mkSrcLoc )
38 import Finder ( findModule )
39 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
40 import Rules ( emptyRuleBase )
41 import PrelInfo ( wiredInThingEnv, wiredInThings )
42 import PrelNames ( vanillaSyntaxMap, knownKeyNames )
43 import MkIface ( mkFinalIface )
45 import InstEnv ( emptyInstEnv )
48 import CoreUtils ( coreBindsSize )
49 import CoreTidy ( tidyCorePgm )
50 import CorePrep ( corePrepPgm )
52 import CoreToStg ( coreToStg )
53 import SimplStg ( stg2stg )
54 import CodeGen ( codeGen )
55 import CodeOutput ( codeOutput )
57 import Module ( ModuleName, moduleName, mkHomeModule,
60 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
61 import Util ( unJust )
62 import UniqSupply ( mkSplitUniqSupply )
64 import Bag ( emptyBag )
67 import HscStats ( ppSourceStats )
69 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
70 import OccName ( OccName )
71 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
72 import NameEnv ( emptyNameEnv, mkNameEnv )
73 import Module ( Module )
75 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
78 import Maybe ( isJust, fromJust )
81 import MkExternalCore ( emitExternalCore )
85 %************************************************************************
87 \subsection{The main compiler pipeline}
89 %************************************************************************
94 = HscFail PersistentCompilerState -- updated PCS
95 -- concluded that it wasn't necessary
96 | HscNoRecomp PersistentCompilerState -- updated PCS
97 ModDetails -- new details (HomeSymbolTable additions)
98 ModIface -- new iface (if any compilation was done)
100 | HscRecomp PersistentCompilerState -- updated PCS
101 ModDetails -- new details (HomeSymbolTable additions)
102 ModIface -- new iface (if any compilation was done)
103 Bool -- stub_h exists
104 Bool -- stub_c exists
105 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
108 -- no errors or warnings; the individual passes
109 -- (parse/rename/typecheck) print messages themselves
115 -> ModuleLocation -- location info
116 -> Bool -- True <=> source unchanged
117 -> Bool -- True <=> have an object file (for msgs only)
118 -> Maybe ModIface -- old interface, if available
119 -> HomeSymbolTable -- for home module ModDetails
121 -> PersistentCompilerState -- IN: persistent compiler state
124 hscMain ghci_mode dflags mod location source_unchanged have_object
125 maybe_old_iface hst hit pcs
127 showPass dflags ("Checking old interface for hs = "
128 ++ show (ml_hs_file location)
129 ++ ", hspp = " ++ show (ml_hspp_file location));
131 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
132 <- _scc_ "checkOldIface"
133 checkOldIface ghci_mode dflags hit hst pcs (ml_hi_file location)
134 source_unchanged maybe_old_iface;
137 return (HscFail pcs_ch)
140 let no_old_iface = not (isJust maybe_checked_iface)
141 what_next | recomp_reqd || no_old_iface = hscRecomp
142 | otherwise = hscNoRecomp
144 what_next ghci_mode dflags have_object mod location
145 maybe_checked_iface hst hit pcs_ch
149 -- we definitely expect to have the old interface available
150 hscNoRecomp ghci_mode dflags have_object
151 mod location (Just old_iface) hst hit pcs_ch
152 | ghci_mode == OneShot
154 hPutStrLn stderr "compilation IS NOT required";
155 let { bomb = panic "hscNoRecomp:OneShot" };
156 return (HscNoRecomp pcs_ch bomb bomb)
160 when (verbosity dflags >= 1) $
161 hPutStrLn stderr ("Skipping " ++
162 compMsg have_object mod location);
165 (pcs_cl, closure_errs, cl_hs_decls)
166 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
168 return (HscFail pcs_cl)
173 <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
175 case maybe_tc_result of {
176 Nothing -> return (HscFail pcs_cl);
177 Just (pcs_tc, new_details) ->
179 return (HscNoRecomp pcs_tc new_details old_iface)
182 compMsg use_object mod location =
183 mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
184 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
186 then unJust "hscRecomp" (ml_obj_file location)
189 where mod_str = moduleUserString mod
192 hscRecomp ghci_mode dflags have_object
193 mod location maybe_checked_iface hst hit pcs_ch
195 -- what target are we shooting for?
196 ; let toInterp = dopt_HscLang dflags == HscInterpreted
198 ; when (verbosity dflags >= 1) $
199 hPutStrLn stderr ("Compiling " ++
200 compMsg (not toInterp) mod location);
205 ; maybe_parsed <- myParseModule dflags
206 (unJust "hscRecomp:hspp" (ml_hspp_file location))
207 ; case maybe_parsed of {
208 Nothing -> return (HscFail pcs_ch);
209 Just rdr_module -> do {
210 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
215 ; (pcs_rn, print_unqualified, maybe_rn_result)
217 renameModule dflags hit hst pcs_ch this_mod rdr_module
218 ; case maybe_rn_result of {
219 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
220 Just (is_exported, new_iface, rn_hs_decls) -> do {
222 -- In interactive mode, we don't want to discard any top-level entities at
223 -- all (eg. do not inline them away during simplification), and retain them
224 -- all in the TypeEnv so they are available from the command line.
226 -- isGlobalName separates the user-defined top-level names from those
227 -- introduced by the type checker.
228 ; let dont_discard | ghci_mode == Interactive = isGlobalName
229 | otherwise = is_exported
235 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
236 print_unqualified rn_hs_decls
237 ; case maybe_tc_result of {
238 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
239 Just (pcs_tc, tc_result) -> do {
244 ; (ds_details, foreign_stuff)
246 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
249 <- if ghci_mode == OneShot
250 then do init_pcs <- initPersistentCompilerState
251 init_prs <- initPersistentRenamerState
253 rules = pcs_rules pcs_tc
254 orig_tc = prsOrig (pcs_PRS pcs_tc)
255 new_prs = init_prs{ prsOrig=orig_tc }
257 orig_tc `seq` rules `seq` new_prs `seq`
258 return init_pcs{ pcs_PRS = new_prs,
267 core2core dflags pcs_middle hst dont_discard ds_details
272 ; cg_info_ref <- newIORef Nothing ;
273 ; let cg_info :: CgInfoEnv
274 cg_info = unsafePerformIO $ do {
275 maybe_cg_env <- readIORef cg_info_ref ;
277 Just env -> return env
278 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
279 return emptyNameEnv } }
280 -- cg_info_ref will be filled in just after restOfCodeGeneration
281 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
283 ; (pcs_simpl, tidy_details)
285 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
287 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
288 else return pcs_simpl
290 -- alive at this point:
294 ; emitExternalCore dflags new_iface tidy_details
296 -- PREPARE FOR CODE GENERATION
298 -- Do saturation and convert to A-normal form
299 ; prepd_details <- _scc_ "CorePrep" corePrepPgm dflags tidy_details
302 -- CONVERT TO STG and COMPLETE CODE GENERATION
305 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
307 local_tycons = typeEnvTyCons env_tc
308 local_classes = typeEnvClasses env_tc
310 imported_module_names = map ideclName (hsModuleImports rdr_module)
312 mod_name_to_Module nm
313 = do m <- findModule nm ; return (fst (fromJust m))
315 (h_code,c_code,fe_binders) = foreign_stuff
317 ; imported_modules <- mapM mod_name_to_Module imported_module_names
319 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
322 ----------------- Generate byte code ------------------
323 (bcos,itbl_env) <- byteCodeGen dflags binds
324 local_tycons local_classes
326 -- Fill in the code-gen info
327 writeIORef cg_info_ref (Just emptyNameEnv)
329 ------------------ BUILD THE NEW ModIface ------------
330 final_iface <- _scc_ "MkFinalIface"
331 mkFinalIface ghci_mode dflags location
332 maybe_checked_iface new_iface tidy_details
334 return ( False, False, Just (bcos,itbl_env), final_iface )
337 ----------------- Convert to STG ------------------
338 (stg_binds, cost_centre_info, stg_back_end_info)
340 myCoreToStg dflags this_mod binds
342 -- Fill in the code-gen info for the earlier tidyCorePgm
343 writeIORef cg_info_ref (Just stg_back_end_info)
345 ------------------ BUILD THE NEW ModIface ------------
346 final_iface <- _scc_ "MkFinalIface"
347 mkFinalIface ghci_mode dflags location
348 maybe_checked_iface new_iface tidy_details
350 ------------------ Code generation ------------------
351 abstractC <- _scc_ "CodeGen"
352 codeGen dflags this_mod imported_modules
353 cost_centre_info fe_binders
354 local_tycons stg_binds
356 ------------------ Code output -----------------------
357 (stub_h_exists, stub_c_exists)
358 <- codeOutput dflags this_mod local_tycons
360 c_code h_code abstractC
362 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
364 ; let final_details = tidy_details {md_binds = []}
367 -- and the answer is ...
368 ; return (HscRecomp pcs_final
371 stub_h_exists stub_c_exists
375 myParseModule dflags src_filename
376 = do -------------------------- Parser ----------------
377 showPass dflags "Parser"
380 buf <- hGetStringBuffer True{-expand tabs-} src_filename
382 let glaexts | dopt Opt_GlasgowExts dflags = 1#
385 case parseModule buf PState{ bol = 0#, atbol = 1#,
386 context = [], glasgow_exts = glaexts,
387 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
389 PFailed err -> do { hPutStrLn stderr (showSDoc err);
390 freeStringBuffer buf;
393 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
395 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
397 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
398 (ppSourceStats False rdr_module) ;
400 return (Just rdr_module)
401 -- ToDo: free the string buffer later.
405 myCoreToStg dflags this_mod tidy_binds
407 () <- coreBindsSize tidy_binds `seq` return ()
408 -- TEMP: the above call zaps some space usage allocated by the
409 -- simplifier, which for reasons I don't understand, persists
410 -- thoroughout code generation
412 stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
414 (stg_binds2, cost_centre_info)
415 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
417 let env_rhs :: CgInfoEnv
418 env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
419 | (bind,_) <- stg_binds2,
421 | stgBindHasCafRefs bind = MayHaveCafRefs
422 | otherwise = NoCafRefs,
423 (bndr,rhs) <- stgBindPairs bind ]
425 return (stg_binds2, cost_centre_info, env_rhs)
427 stgBindPairs (StgNonRec _ b r) = [(b,r)]
428 stgBindPairs (StgRec _ prs) = prs
434 %************************************************************************
436 \subsection{Compiling a do-statement}
438 %************************************************************************
446 -> PersistentCompilerState -- IN: persistent compiler state
447 -> InteractiveContext -- Context for compiling
448 -> String -- The statement
449 -> Bool -- just treat it as an expression
450 -> IO ( PersistentCompilerState,
456 When the UnlinkedBCOExpr is linked you get an HValue of type
458 When you run it you get a list of HValues that should be
459 the same length as the list of names; add them to the ClosureEnv.
461 A naked expression returns a singleton Name [it].
463 What you type The IO [HValue] that hscStmt returns
464 ------------- ------------------------------------
465 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
468 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
471 expr (of IO type) ==> expr >>= \ v -> return [v]
472 [NB: result not printed] bindings: [it]
475 expr (of non-IO type,
476 result showable) ==> let v = expr in print v >> return [v]
479 expr (of non-IO type,
480 result not showable) ==> error
483 hscStmt dflags hst hit pcs0 icontext stmt just_expr
487 ic_type_env = type_env,
488 ic_module = scope_mod } = icontext
490 do { maybe_stmt <- hscParseStmt dflags stmt
492 Nothing -> return (pcs0, Nothing)
493 Just parsed_stmt -> do {
495 let { notExprStmt (ExprStmt _ _) = False;
499 if (just_expr && notExprStmt parsed_stmt)
500 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
501 return (pcs0, Nothing)
505 (pcs1, print_unqual, maybe_renamed_stmt)
506 <- renameStmt dflags hit hst pcs0 scope_mod
507 iNTERACTIVE rn_env parsed_stmt
509 ; case maybe_renamed_stmt of
510 Nothing -> return (pcs0, Nothing)
511 Just (bound_names, rn_stmt) -> do {
516 then case rn_stmt of { (syn, ExprStmt e _, decls) ->
517 typecheckExpr dflags pcs1 hst type_env
518 print_unqual iNTERACTIVE (syn,e,decls) }
519 else typecheckStmt dflags pcs1 hst type_env
520 print_unqual iNTERACTIVE bound_names rn_stmt
522 ; case maybe_tc_return of
523 Nothing -> return (pcs0, Nothing)
524 Just (pcs2, tc_expr, bound_ids, ty) -> do {
527 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
530 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
532 -- Tidy it (temporary, until coreSat does cloning)
533 ; tidy_expr <- tidyCoreExpr simpl_expr
535 -- Prepare for codegen
536 ; prepd_expr <- corePrepExpr dflags tidy_expr
539 ; bcos <- coreExprToBCOs dflags prepd_expr
542 -- Make all the bound ids "global" ids, now that
543 -- they're notionally top-level bindings. This is
544 -- important: otherwise when we come to compile an expression
545 -- using these ids later, the byte code generator will consider
546 -- the occurrences to be free rather than global.
547 global_bound_ids = map globaliseId bound_ids;
548 globaliseId id = setGlobalIdDetails id VanillaGlobal
550 ; return (pcs2, Just (global_bound_ids, ty, bcos))
554 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
555 hscParseStmt dflags str
556 = do -------------------------- Parser ----------------
557 showPass dflags "Parser"
560 buf <- stringToStringBuffer str
562 let glaexts | dopt Opt_GlasgowExts dflags = 1#
565 case parseStmt buf PState{ bol = 0#, atbol = 1#,
566 context = [], glasgow_exts = glaexts,
567 loc = mkSrcLoc SLIT("<no file>") 0 } of {
569 PFailed err -> do { hPutStrLn stderr (showSDoc err);
570 -- Not yet implemented in <4.11 freeStringBuffer buf;
573 -- no stmt: the line consisted of just space or comments
574 POk _ Nothing -> return Nothing;
576 POk _ (Just rdr_stmt) -> do {
578 --ToDo: can't free the string buffer until we've finished this
579 -- compilation sweep and all the identifiers have gone away.
580 --freeStringBuffer buf;
581 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
582 return (Just rdr_stmt)
587 %************************************************************************
589 \subsection{Initial persistent state}
591 %************************************************************************
594 initPersistentCompilerState :: IO PersistentCompilerState
595 initPersistentCompilerState
596 = do prs <- initPersistentRenamerState
598 PCS { pcs_PIT = emptyIfaceTable,
599 pcs_PTE = wiredInThingEnv,
600 pcs_insts = emptyInstEnv,
601 pcs_rules = emptyRuleBase,
606 initPersistentRenamerState :: IO PersistentRenamerState
607 = do us <- mkSplitUniqSupply 'r'
609 PRS { prsOrig = NameSupply { nsUniqs = us,
610 nsNames = initOrigNames,
612 prsDecls = (emptyNameEnv, 0),
613 prsInsts = (emptyBag, 0),
614 prsRules = (emptyBag, 0),
619 initOrigNames :: FiniteMap (ModuleName,OccName) Name
621 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
623 grab names = foldl add emptyFM names
625 = addToFM env (moduleName (nameModule name), nameOccName name) name