2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
4 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
7 module HscMain ( HscResult(..), hscMain,
11 initPersistentCompilerState ) where
13 #include "HsVersions.h"
16 import ByteCodeGen ( byteCodeGen )
17 import CoreTidy ( tidyCoreExpr )
18 import CorePrep ( corePrepExpr )
19 import Rename ( renameStmt )
20 import RdrHsSyn ( RdrNameStmt )
22 import Id ( Id, idName, setGlobalIdDetails )
23 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
24 import HscTypes ( InteractiveContext(..), TyThing(..) )
25 import PrelNames ( iNTERACTIVE )
26 import StringBuffer ( stringToStringBuffer )
32 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
33 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
35 import Lex ( PState(..), ParseResult(..) )
36 import SrcLoc ( mkSrcLoc )
37 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
38 import Rules ( emptyRuleBase )
39 import PrelInfo ( wiredInThingEnv, wiredInThings )
40 import PrelNames ( vanillaSyntaxMap, knownKeyNames )
41 import MkIface ( mkFinalIface )
43 import InstEnv ( emptyInstEnv )
46 import CoreUtils ( coreBindsSize )
47 import CoreTidy ( tidyCorePgm )
48 import CorePrep ( corePrepPgm )
50 import CoreToStg ( coreToStg )
51 import SimplStg ( stg2stg )
52 import CodeGen ( codeGen )
53 import CodeOutput ( codeOutput )
55 import Module ( ModuleName, moduleName, mkHomeModule,
58 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
59 import Util ( unJust )
60 import UniqSupply ( mkSplitUniqSupply )
62 import Bag ( emptyBag )
65 import CmStaticInfo ( GhciMode(..) )
66 import HscStats ( ppSourceStats )
68 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
69 import OccName ( OccName )
70 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
71 import NameEnv ( emptyNameEnv, mkNameEnv )
72 import Module ( Module, lookupModuleEnvByName )
73 import Maybes ( orElse )
75 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
78 import Maybe ( isJust )
83 %************************************************************************
85 \subsection{The main compiler pipeline}
87 %************************************************************************
92 = HscFail PersistentCompilerState -- updated PCS
93 -- concluded that it wasn't necessary
94 | HscNoRecomp PersistentCompilerState -- updated PCS
95 ModDetails -- new details (HomeSymbolTable additions)
96 ModIface -- new iface (if any compilation was done)
98 | HscRecomp PersistentCompilerState -- updated PCS
99 ModDetails -- new details (HomeSymbolTable additions)
100 ModIface -- new iface (if any compilation was done)
101 (Maybe String) -- generated stub_h filename (in TMPDIR)
102 (Maybe String) -- generated stub_c filename (in TMPDIR)
103 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
106 -- no errors or warnings; the individual passes
107 -- (parse/rename/typecheck) print messages themselves
113 -> ModuleLocation -- location info
114 -> Bool -- True <=> source unchanged
115 -> Bool -- True <=> have an object file (for msgs only)
116 -> Maybe ModIface -- old interface, if available
117 -> HomeSymbolTable -- for home module ModDetails
119 -> PersistentCompilerState -- IN: persistent compiler state
122 hscMain ghci_mode dflags mod location source_unchanged have_object
123 maybe_old_iface hst hit pcs
125 showPass dflags ("Checking old interface for hs = "
126 ++ show (ml_hs_file location)
127 ++ ", hspp = " ++ show (ml_hspp_file location));
129 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
130 <- checkOldIface ghci_mode dflags hit hst pcs
131 (unJust "hscMain" (ml_hi_file location))
132 source_unchanged maybe_old_iface;
135 return (HscFail pcs_ch)
138 let no_old_iface = not (isJust maybe_checked_iface)
139 what_next | recomp_reqd || no_old_iface = hscRecomp
140 | otherwise = hscNoRecomp
142 what_next ghci_mode dflags have_object mod location
143 maybe_checked_iface hst hit pcs_ch
147 -- we definitely expect to have the old interface available
148 hscNoRecomp ghci_mode dflags have_object
149 mod location (Just old_iface) hst hit pcs_ch
150 | ghci_mode == OneShot
152 hPutStrLn stderr "compilation IS NOT required";
153 let { bomb = panic "hscNoRecomp:OneShot" };
154 return (HscNoRecomp pcs_ch bomb bomb)
158 when (verbosity dflags >= 1) $
159 hPutStrLn stderr ("Skipping " ++
160 compMsg have_object mod location);
163 (pcs_cl, closure_errs, cl_hs_decls)
164 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
166 return (HscFail pcs_cl)
171 <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
173 case maybe_tc_result of {
174 Nothing -> return (HscFail pcs_cl);
175 Just (pcs_tc, new_details) ->
177 return (HscNoRecomp pcs_tc new_details old_iface)
180 compMsg use_object mod location =
181 mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
182 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
184 then unJust "hscRecomp" (ml_obj_file location)
187 where mod_str = moduleUserString mod
190 hscRecomp ghci_mode dflags have_object
191 mod location maybe_checked_iface hst hit pcs_ch
193 -- what target are we shooting for?
194 ; let toInterp = dopt_HscLang dflags == HscInterpreted
196 ; when (verbosity dflags >= 1) $
197 hPutStrLn stderr ("Compiling " ++
198 compMsg (not toInterp) mod location);
203 ; maybe_parsed <- myParseModule dflags
204 (unJust "hscRecomp:hspp" (ml_hspp_file location))
205 ; case maybe_parsed of {
206 Nothing -> return (HscFail pcs_ch);
207 Just rdr_module -> do {
208 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
213 ; (pcs_rn, print_unqualified, maybe_rn_result)
215 renameModule dflags hit hst pcs_ch this_mod rdr_module
216 ; case maybe_rn_result of {
217 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
218 Just (is_exported, new_iface, rn_hs_decls) -> do {
220 -- In interactive mode, we don't want to discard any top-level entities at
221 -- all (eg. do not inline them away during simplification), and retain them
222 -- all in the TypeEnv so they are available from the command line.
224 -- isGlobalName separates the user-defined top-level names from those
225 -- introduced by the type checker.
226 ; let dont_discard | ghci_mode == Interactive = isGlobalName
227 | otherwise = is_exported
233 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
234 print_unqualified rn_hs_decls
235 ; case maybe_tc_result of {
236 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
237 Just (pcs_tc, tc_result) -> do {
242 ; (ds_details, foreign_stuff)
244 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
251 core2core dflags pcs_tc hst dont_discard ds_details
256 ; cg_info_ref <- newIORef Nothing ;
257 ; let cg_info :: CgInfoEnv
258 cg_info = unsafePerformIO $ do {
259 maybe_cg_env <- readIORef cg_info_ref ;
261 Just env -> return env
262 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
263 return emptyNameEnv } }
264 -- cg_info_ref will be filled in just after restOfCodeGeneration
265 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
267 ; (pcs_simpl, tidy_details)
268 <- tidyCorePgm dflags this_mod pcs_tc cg_info simpl_details
271 -- PREPARE FOR CODE GENERATION
273 -- Do saturation and convert to A-normal form
274 ; prepd_details <- corePrepPgm dflags tidy_details
277 -- CONVERT TO STG and COMPLETE CODE GENERATION
280 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
282 local_tycons = typeEnvTyCons env_tc
283 local_classes = typeEnvClasses env_tc
285 imported_module_names = map ideclName (hsModuleImports rdr_module)
286 imported_modules = map mod_name_to_Module imported_module_names
288 (h_code,c_code,fe_binders) = foreign_stuff
290 pit = pcs_PIT pcs_simpl
292 mod_name_to_Module :: ModuleName -> Module
293 mod_name_to_Module nm
294 = let str_mi = lookupModuleEnvByName hit nm `orElse`
295 lookupModuleEnvByName pit nm `orElse`
296 pprPanic "mod_name_to_Module: no hst or pst mapping for"
300 ; (maybe_stub_h_filename, maybe_stub_c_filename,
301 maybe_bcos, final_iface )
304 ----------------- Generate byte code ------------------
305 (bcos,itbl_env) <- byteCodeGen dflags binds
306 local_tycons local_classes
308 -- Fill in the code-gen info
309 writeIORef cg_info_ref (Just emptyNameEnv)
311 ------------------ BUILD THE NEW ModIface ------------
312 final_iface <- _scc_ "MkFinalIface"
313 mkFinalIface ghci_mode dflags location
314 maybe_checked_iface new_iface tidy_details
316 return ( Nothing, Nothing,
317 Just (bcos,itbl_env), final_iface )
320 ----------------- Convert to STG ------------------
321 (stg_binds, cost_centre_info, stg_back_end_info)
323 myCoreToStg dflags this_mod binds
325 -- Fill in the code-gen info for the earlier tidyCorePgm
326 writeIORef cg_info_ref (Just stg_back_end_info)
328 ------------------ BUILD THE NEW ModIface ------------
329 final_iface <- _scc_ "MkFinalIface"
330 mkFinalIface ghci_mode dflags location
331 maybe_checked_iface new_iface tidy_details
333 ------------------ Code generation ------------------
334 abstractC <- _scc_ "CodeGen"
335 codeGen dflags this_mod imported_modules
336 cost_centre_info fe_binders
337 local_tycons stg_binds
339 ------------------ Code output -----------------------
340 (maybe_stub_h_name, maybe_stub_c_name)
341 <- codeOutput dflags this_mod local_tycons
343 c_code h_code abstractC
345 return ( maybe_stub_h_name, maybe_stub_c_name,
346 Nothing, final_iface )
348 ; let final_details = tidy_details {md_binds = []}
351 -- and the answer is ...
352 ; return (HscRecomp pcs_simpl
355 maybe_stub_h_filename maybe_stub_c_filename
359 myParseModule dflags src_filename
360 = do -------------------------- Parser ----------------
361 showPass dflags "Parser"
364 buf <- hGetStringBuffer True{-expand tabs-} src_filename
366 let glaexts | dopt Opt_GlasgowExts dflags = 1#
369 case parseModule buf PState{ bol = 0#, atbol = 1#,
370 context = [], glasgow_exts = glaexts,
371 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
373 PFailed err -> do { hPutStrLn stderr (showSDoc err);
374 freeStringBuffer buf;
377 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
379 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
381 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
382 (ppSourceStats False rdr_module) ;
384 return (Just rdr_module)
385 -- ToDo: free the string buffer later.
389 myCoreToStg dflags this_mod tidy_binds
391 () <- coreBindsSize tidy_binds `seq` return ()
392 -- TEMP: the above call zaps some space usage allocated by the
393 -- simplifier, which for reasons I don't understand, persists
394 -- thoroughout code generation
396 stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
398 (stg_binds2, cost_centre_info)
399 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
401 let env_rhs :: CgInfoEnv
402 env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
403 | (bind,_) <- stg_binds2,
405 | stgBindHasCafRefs bind = MayHaveCafRefs
406 | otherwise = NoCafRefs,
407 (bndr,rhs) <- stgBindPairs bind ]
409 return (stg_binds2, cost_centre_info, env_rhs)
411 stgBindPairs (StgNonRec _ b r) = [(b,r)]
412 stgBindPairs (StgRec _ prs) = prs
416 %************************************************************************
418 \subsection{Compiling a do-statement}
420 %************************************************************************
428 -> PersistentCompilerState -- IN: persistent compiler state
429 -> InteractiveContext -- Context for compiling
430 -> String -- The statement
431 -> Bool -- just treat it as an expression
432 -> IO ( PersistentCompilerState,
438 When the UnlinkedBCOExpr is linked you get an HValue of type
440 When you run it you get a list of HValues that should be
441 the same length as the list of names; add them to the ClosureEnv.
443 A naked expression returns a singleton Name [it].
445 What you type The IO [HValue] that hscStmt returns
446 ------------- ------------------------------------
447 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
450 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
453 expr (of IO type) ==> expr >>= \ v -> return [v]
454 [NB: result not printed] bindings: [it]
457 expr (of non-IO type,
458 result showable) ==> let v = expr in print v >> return [v]
461 expr (of non-IO type,
462 result not showable) ==> error
465 hscStmt dflags hst hit pcs0 icontext stmt just_expr
469 ic_type_env = type_env,
470 ic_module = scope_mod } = icontext
472 do { maybe_stmt <- hscParseStmt dflags stmt
474 Nothing -> return (pcs0, Nothing)
475 Just parsed_stmt -> do {
477 let { notExprStmt (ExprStmt _ _) = False;
481 if (just_expr && notExprStmt parsed_stmt)
482 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
483 return (pcs0, Nothing)
487 (pcs1, print_unqual, maybe_renamed_stmt)
488 <- renameStmt dflags hit hst pcs0 scope_mod
489 iNTERACTIVE rn_env parsed_stmt
491 ; case maybe_renamed_stmt of
492 Nothing -> return (pcs0, Nothing)
493 Just (bound_names, rn_stmt) -> do {
498 then case rn_stmt of { (syn, ExprStmt e _, decls) ->
499 typecheckExpr dflags pcs1 hst type_env
500 print_unqual iNTERACTIVE (syn,e,decls) }
501 else typecheckStmt dflags pcs1 hst type_env
502 print_unqual iNTERACTIVE bound_names rn_stmt
504 ; case maybe_tc_return of
505 Nothing -> return (pcs0, Nothing)
506 Just (pcs2, tc_expr, bound_ids, ty) -> do {
509 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
512 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
514 -- Tidy it (temporary, until coreSat does cloning)
515 ; tidy_expr <- tidyCoreExpr simpl_expr
517 -- Prepare for codegen
518 ; prepd_expr <- corePrepExpr dflags tidy_expr
521 ; bcos <- coreExprToBCOs dflags prepd_expr
524 -- Make all the bound ids "global" ids, now that
525 -- they're notionally top-level bindings. This is
526 -- important: otherwise when we come to compile an expression
527 -- using these ids later, the byte code generator will consider
528 -- the occurrences to be free rather than global.
529 global_bound_ids = map globaliseId bound_ids;
530 globaliseId id = setGlobalIdDetails id VanillaGlobal
532 ; return (pcs2, Just (global_bound_ids, ty, bcos))
536 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
537 hscParseStmt dflags str
538 = do -------------------------- Parser ----------------
539 showPass dflags "Parser"
542 buf <- stringToStringBuffer str
544 let glaexts | dopt Opt_GlasgowExts dflags = 1#
547 case parseStmt buf PState{ bol = 0#, atbol = 1#,
548 context = [], glasgow_exts = glaexts,
549 loc = mkSrcLoc SLIT("<no file>") 0 } of {
551 PFailed err -> do { hPutStrLn stderr (showSDoc err);
552 -- Not yet implemented in <4.11 freeStringBuffer buf;
555 -- no stmt: the line consisted of just space or comments
556 POk _ Nothing -> return Nothing;
558 POk _ (Just rdr_stmt) -> do {
560 --ToDo: can't free the string buffer until we've finished this
561 -- compilation sweep and all the identifiers have gone away.
562 --freeStringBuffer buf;
563 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
564 return (Just rdr_stmt)
569 %************************************************************************
571 \subsection{Initial persistent state}
573 %************************************************************************
576 initPersistentCompilerState :: IO PersistentCompilerState
577 initPersistentCompilerState
578 = do prs <- initPersistentRenamerState
580 PCS { pcs_PIT = emptyIfaceTable,
581 pcs_PTE = wiredInThingEnv,
582 pcs_insts = emptyInstEnv,
583 pcs_rules = emptyRuleBase,
588 initPersistentRenamerState :: IO PersistentRenamerState
589 = do us <- mkSplitUniqSupply 'r'
591 PRS { prsOrig = NameSupply { nsUniqs = us,
592 nsNames = initOrigNames,
594 prsDecls = (emptyNameEnv, 0),
595 prsInsts = (emptyBag, 0),
596 prsRules = (emptyBag, 0),
601 initOrigNames :: FiniteMap (ModuleName,OccName) Name
603 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
605 grab names = foldl add emptyFM names
607 = addToFM env (moduleName (nameModule name), nameOccName name) name
610 initRules :: PackageRuleBase
611 initRules = emptyRuleBase
613 foldl add emptyVarEnv builtinRules
616 = extendRuleBase env name rule