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 RdrHsSyn ( RdrNameStmt )
17 import Rename ( renameStmt )
18 import ByteCodeGen ( byteCodeGen )
19 import Id ( Id, idName, idFlavour, modifyIdInfo )
20 import IdInfo ( setFlavourInfo, makeConstantFlavour )
21 import HscTypes ( InteractiveContext(..), TyThing(..) )
26 import StringBuffer ( hGetStringBuffer,
27 stringToStringBuffer, freeStringBuffer )
29 import Lex ( PState(..), ParseResult(..) )
30 import SrcLoc ( mkSrcLoc )
31 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
32 import Rules ( emptyRuleBase )
33 import PrelInfo ( wiredInThingEnv, wiredInThings )
34 import PrelNames ( vanillaSyntaxMap, knownKeyNames, iNTERACTIVE )
35 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
36 writeIface, pprIface )
39 import InstEnv ( emptyInstEnv )
42 import CoreUtils ( coreBindsSize )
43 import CoreTidy ( tidyCorePgm )
45 import CoreTidy ( tidyCoreExpr )
46 import CoreToStg ( coreToStg )
47 import SimplStg ( stg2stg )
48 import CodeGen ( codeGen )
49 import CodeOutput ( codeOutput )
51 import Module ( ModuleName, moduleName, mkHomeModule,
54 import ErrUtils ( dumpIfSet_dyn, showPass )
55 import Util ( unJust )
56 import UniqSupply ( mkSplitUniqSupply )
58 import Bag ( emptyBag )
61 import CmStaticInfo ( GhciMode(..) )
62 import HscStats ( ppSourceStats )
63 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
64 PersistentRenamerState(..), ModuleLocation(..),
66 NameSupply(..), PackageRuleBase, HomeIfaceTable,
67 typeEnvClasses, typeEnvTyCons, emptyIfaceTable
69 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
70 import OccName ( OccName )
71 import Name ( Name, nameModule, nameOccName, getName, isGlobalName,
74 import Module ( Module, lookupModuleEnvByName )
77 import Maybe ( isJust )
82 %************************************************************************
84 \subsection{The main compiler pipeline}
86 %************************************************************************
91 = HscFail PersistentCompilerState -- updated PCS
92 -- concluded that it wasn't necessary
93 | HscNoRecomp PersistentCompilerState -- updated PCS
94 ModDetails -- new details (HomeSymbolTable additions)
95 ModIface -- new iface (if any compilation was done)
97 | HscRecomp PersistentCompilerState -- updated PCS
98 ModDetails -- new details (HomeSymbolTable additions)
99 ModIface -- new iface (if any compilation was done)
100 (Maybe String) -- generated stub_h filename (in TMPDIR)
101 (Maybe String) -- generated stub_c filename (in TMPDIR)
102 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
105 -- no errors or warnings; the individual passes
106 -- (parse/rename/typecheck) print messages themselves
112 -> ModuleLocation -- location info
113 -> Bool -- source unchanged?
114 -> Maybe ModIface -- old interface, if available
115 -> HomeSymbolTable -- for home module ModDetails
117 -> PersistentCompilerState -- IN: persistent compiler state
120 hscMain ghci_mode dflags mod location source_unchanged maybe_old_iface hst hit pcs
122 showPass dflags ("Checking old interface for hs = "
123 ++ show (ml_hs_file location)
124 ++ ", hspp = " ++ show (ml_hspp_file location));
126 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
127 <- checkOldIface ghci_mode dflags hit hst pcs
128 (unJust "hscMain" (ml_hi_file location))
129 source_unchanged maybe_old_iface;
132 return (HscFail pcs_ch)
135 let no_old_iface = not (isJust maybe_checked_iface)
136 what_next | recomp_reqd || no_old_iface = hscRecomp
137 | otherwise = hscNoRecomp
139 what_next ghci_mode dflags mod location maybe_checked_iface
144 -- we definitely expect to have the old interface available
145 hscNoRecomp ghci_mode dflags mod location (Just old_iface) hst hit pcs_ch
146 | ghci_mode == OneShot
148 hPutStrLn stderr "compilation IS NOT required";
149 let { bomb = panic "hscNoRecomp:OneShot" };
150 return (HscNoRecomp pcs_ch bomb bomb)
154 when (verbosity dflags >= 1) $
155 hPutStrLn stderr ("Skipping " ++ compMsg mod location);
158 (pcs_cl, closure_errs, cl_hs_decls)
159 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
161 return (HscFail pcs_cl)
166 <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
168 case maybe_tc_result of {
169 Nothing -> return (HscFail pcs_cl);
170 Just (pcs_tc, env_tc, local_rules) -> do {
172 -- create a new details from the closed, typechecked, old iface
173 let new_details = mkModDetailsFromIface env_tc local_rules
175 return (HscNoRecomp pcs_tc new_details old_iface)
178 compMsg mod location =
179 mod_str ++ take (12 - length mod_str) (repeat ' ')
180 ++ " (" ++ unJust "hscRecomp" (ml_hs_file location) ++ ")"
181 where mod_str = moduleUserString mod
184 hscRecomp ghci_mode dflags mod location maybe_checked_iface hst hit pcs_ch
186 ; when (verbosity dflags >= 1) $
187 hPutStrLn stderr ("Compiling " ++ compMsg mod location);
189 -- what target are we shooting for?
190 ; let toInterp = dopt_HscLang dflags == HscInterpreted
195 ; maybe_parsed <- myParseModule dflags
196 (unJust "hscRecomp:hspp" (ml_hspp_file location))
197 ; case maybe_parsed of {
198 Nothing -> return (HscFail pcs_ch);
199 Just rdr_module -> do {
200 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
205 ; (pcs_rn, print_unqualified, maybe_rn_result)
207 renameModule dflags hit hst pcs_ch this_mod rdr_module
208 ; case maybe_rn_result of {
209 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
210 Just (is_exported, new_iface, rn_hs_decls) -> do {
212 -- In interactive mode, we don't want to discard any top-level entities at
213 -- all (eg. do not inline them away during simplification), and retain them
214 -- all in the TypeEnv so they are available from the command line.
216 -- isGlobalName separates the user-defined top-level names from those
217 -- introduced by the type checker.
218 ; let dont_discard | ghci_mode == Interactive = isGlobalName
219 | otherwise = is_exported
225 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
226 print_unqualified rn_hs_decls
227 ; case maybe_tc_result of {
228 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
229 Just (pcs_tc, tc_result) -> do {
231 ; let env_tc = tc_env tc_result
236 ; (ds_binds, ds_rules, foreign_stuff)
238 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
241 -- SIMPLIFY, TIDY-CORE
243 -- We grab the the unfoldings at this point.
244 ; (pcs_simpl, tidy_binds, orphan_rules)
245 <- simplThenTidy dflags pcs_tc hst this_mod dont_discard ds_binds ds_rules
248 -- BUILD THE NEW ModDetails AND ModIface
250 ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
251 ; final_iface <- _scc_ "MkFinalIface"
252 mkFinalIface ghci_mode dflags location
253 maybe_checked_iface new_iface new_details
256 -- CONVERT TO STG and COMPLETE CODE GENERATION
258 -- Do saturation and convert to A-normal form
259 ; saturated <- coreSatPgm dflags tidy_binds
261 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
262 <- restOfCodeGeneration dflags toInterp this_mod
263 (map ideclName (hsModuleImports rdr_module))
264 foreign_stuff env_tc saturated
265 hit (pcs_PIT pcs_simpl)
267 -- and the answer is ...
268 ; return (HscRecomp pcs_simpl new_details final_iface
269 maybe_stub_h_filename maybe_stub_c_filename
275 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
276 = case completeIface maybe_old_iface new_iface new_details of
277 (new_iface, Nothing) -- no change in the interfacfe
278 -> do when (dopt Opt_D_dump_hi_diffs dflags)
279 (printDump (text "INTERFACE UNCHANGED"))
280 dumpIfSet_dyn dflags Opt_D_dump_hi
281 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
283 (new_iface, Just sdoc_diffs)
284 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
286 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
288 -- Write the interface file
289 when (ghci_mode /= Interactive)
290 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
295 myParseModule dflags src_filename
296 = do -------------------------- Parser ----------------
297 showPass dflags "Parser"
300 buf <- hGetStringBuffer True{-expand tabs-} src_filename
302 let glaexts | dopt Opt_GlasgowExts dflags = 1#
305 case parseModule buf PState{ bol = 0#, atbol = 1#,
306 context = [], glasgow_exts = glaexts,
307 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
309 PFailed err -> do { hPutStrLn stderr (showSDoc err);
310 freeStringBuffer buf;
313 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
315 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
317 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
318 (ppSourceStats False rdr_module) ;
320 return (Just rdr_module)
321 -- ToDo: free the string buffer later.
325 simplThenTidy dflags pcs hst this_mod dont_discard binds rules
326 = do -- Do main Core-language transformations ---------
328 (simplified, orphan_rules)
329 <- core2core dflags pcs hst dont_discard binds rules
331 -- Do the final tidy-up
332 (pcs', tidy_binds, tidy_orphan_rules)
333 <- tidyCorePgm dflags this_mod pcs simplified orphan_rules
335 return (pcs', tidy_binds, tidy_orphan_rules)
338 restOfCodeGeneration dflags toInterp this_mod imported_module_names
339 foreign_stuff env_tc tidy_binds
340 hit pit -- these last two for mapping ModNames to Modules
343 <- byteCodeGen dflags tidy_binds local_tycons local_classes
344 return (Nothing, Nothing, Just (bcos,itbl_env))
348 -------------------------- Convert to STG -------------------------------
349 (stg_binds, cost_centre_info)
351 myCoreToStg dflags this_mod tidy_binds env_tc
353 -------------------------- Code generation ------------------------------
354 abstractC <- _scc_ "CodeGen"
355 codeGen dflags this_mod imported_modules
356 cost_centre_info fe_binders
357 local_tycons stg_binds
359 -------------------------- Code output -------------------------------
360 (maybe_stub_h_name, maybe_stub_c_name)
361 <- codeOutput dflags this_mod local_tycons
363 c_code h_code abstractC
365 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
367 local_tycons = typeEnvTyCons env_tc
368 local_classes = typeEnvClasses env_tc
369 imported_modules = map mod_name_to_Module imported_module_names
370 (h_code,c_code,fe_binders) = foreign_stuff
372 mod_name_to_Module :: ModuleName -> Module
373 mod_name_to_Module nm
374 = let str_mi = case lookupModuleEnvByName hit nm of
376 Nothing -> case lookupModuleEnvByName pit nm of
380 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
384 myCoreToStg dflags this_mod tidy_binds env_tc
386 () <- coreBindsSize tidy_binds `seq` return ()
387 -- TEMP: the above call zaps some space usage allocated by the
388 -- simplifier, which for reasons I don't understand, persists
389 -- thoroughout code generation
391 --let bcos = byteCodeGen dflags tidy_binds local_tycons local_classes
394 stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
396 (stg_binds2, cost_centre_info)
397 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
399 return (stg_binds2, cost_centre_info)
401 local_tycons = typeEnvTyCons env_tc
402 local_classes = typeEnvClasses env_tc
406 %************************************************************************
408 \subsection{Compiling a do-statement}
410 %************************************************************************
418 -> PersistentCompilerState -- IN: persistent compiler state
419 -> InteractiveContext -- Context for compiling
420 -> String -- The statement
421 -> Bool -- just treat it as an expression
422 -> IO ( PersistentCompilerState,
428 When the UnlinkedBCOExpr is linked you get an HValue of type
430 When you run it you get a list of HValues that should be
431 the same length as the list of names; add them to the ClosureEnv.
433 A naked expression returns a singleton Name [it].
435 What you type The IO [HValue] that hscStmt returns
436 ------------- ------------------------------------
437 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
440 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
443 expr (of IO type) ==> expr >>= \ v -> return [v]
444 [NB: result not printed] bindings: [it]
447 expr (of non-IO type,
448 result showable) ==> let v = expr in print v >> return [v]
451 expr (of non-IO type,
452 result not showable) ==> error
455 hscStmt dflags hst hit pcs0 icontext stmt just_expr
459 ic_type_env = type_env,
460 ic_module = scope_mod } = icontext
462 do { maybe_stmt <- hscParseStmt dflags stmt
464 Nothing -> return (pcs0, Nothing)
465 Just parsed_stmt -> do {
467 let { notExprStmt (ExprStmt _ _) = False;
471 if (just_expr && notExprStmt parsed_stmt)
472 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
473 return (pcs0, Nothing)
477 (pcs1, print_unqual, maybe_renamed_stmt)
478 <- renameStmt dflags hit hst pcs0 scope_mod
479 iNTERACTIVE rn_env parsed_stmt
481 ; case maybe_renamed_stmt of
482 Nothing -> return (pcs0, Nothing)
483 Just (bound_names, rn_stmt) -> do {
488 then case rn_stmt of { (syn, ExprStmt e _, decls) ->
489 typecheckExpr dflags pcs1 hst type_env
490 print_unqual iNTERACTIVE (syn,e,decls) }
491 else typecheckStmt dflags pcs1 hst type_env
492 print_unqual iNTERACTIVE bound_names rn_stmt
494 ; case maybe_tc_return of
495 Nothing -> return (pcs0, Nothing)
496 Just (pcs2, tc_expr, bound_ids, ty) -> do {
499 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
502 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
504 -- Tidy it (temporary, until coreSat does cloning)
505 ; tidy_expr <- tidyCoreExpr simpl_expr
508 ; sat_expr <- coreSatExpr dflags tidy_expr
511 ; bcos <- coreExprToBCOs dflags sat_expr
514 -- make all the bound ids "constant" ids, now that
515 -- they're notionally top-level bindings. This is
516 -- important: otherwise when we come to compile an expression
517 -- using these ids later, the byte code generator will consider
518 -- the occurrences to be free rather than global.
519 constant_bound_ids = map constantizeId bound_ids;
522 = modifyIdInfo (`setFlavourInfo` makeConstantFlavour
525 ; return (pcs2, Just (constant_bound_ids, ty, bcos))
529 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
530 hscParseStmt dflags str
531 = do -------------------------- Parser ----------------
532 showPass dflags "Parser"
535 buf <- stringToStringBuffer str
537 let glaexts | dopt Opt_GlasgowExts dflags = 1#
540 case parseStmt buf PState{ bol = 0#, atbol = 1#,
541 context = [], glasgow_exts = glaexts,
542 loc = mkSrcLoc SLIT("<no file>") 0 } of {
544 PFailed err -> do { hPutStrLn stderr (showSDoc err);
545 -- Not yet implemented in <4.11 freeStringBuffer buf;
548 -- no stmt: the line consisted of just space or comments
549 POk _ Nothing -> return Nothing;
551 POk _ (Just rdr_stmt) -> do {
553 --ToDo: can't free the string buffer until we've finished this
554 -- compilation sweep and all the identifiers have gone away.
555 --freeStringBuffer buf;
556 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
557 return (Just rdr_stmt)
562 %************************************************************************
564 \subsection{Initial persistent state}
566 %************************************************************************
569 initPersistentCompilerState :: IO PersistentCompilerState
570 initPersistentCompilerState
571 = do prs <- initPersistentRenamerState
573 PCS { pcs_PIT = emptyIfaceTable,
574 pcs_PTE = wiredInThingEnv,
575 pcs_insts = emptyInstEnv,
576 pcs_rules = emptyRuleBase,
581 initPersistentRenamerState :: IO PersistentRenamerState
582 = do us <- mkSplitUniqSupply 'r'
584 PRS { prsOrig = NameSupply { nsUniqs = us,
585 nsNames = initOrigNames,
587 prsDecls = (emptyNameEnv, 0),
588 prsInsts = (emptyBag, 0),
589 prsRules = (emptyBag, 0),
594 initOrigNames :: FiniteMap (ModuleName,OccName) Name
596 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
598 grab names = foldl add emptyFM names
600 = addToFM env (moduleName (nameModule name), nameOccName name) name
603 initRules :: PackageRuleBase
604 initRules = emptyRuleBase
606 foldl add emptyVarEnv builtinRules
609 = extendRuleBase env name rule