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, hscExpr,
8 initPersistentCompilerState ) where
10 #include "HsVersions.h"
13 import RdrHsSyn ( RdrNameHsExpr )
14 import CoreToStg ( coreToStgExpr )
15 import StringBuffer ( stringToStringBuffer, freeStringBuffer )
20 import StringBuffer ( hGetStringBuffer )
22 import Lex ( PState(..), ParseResult(..) )
23 import SrcLoc ( mkSrcLoc )
25 import Rules ( emptyRuleBase )
26 import PrelInfo ( wiredInThingEnv, wiredInThings )
27 import PrelNames ( knownKeyNames )
28 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
29 writeIface, pprIface )
31 import InstEnv ( emptyInstEnv )
34 import OccurAnal ( occurAnalyseBinds )
35 import CoreUtils ( coreBindsSize )
36 import CoreTidy ( tidyCorePgm )
37 import CoreToStg ( topCoreBindsToStg )
38 import StgSyn ( collectFinalStgBinders )
39 import SimplStg ( stg2stg )
40 import CodeGen ( codeGen )
41 import CodeOutput ( codeOutput )
43 import Module ( ModuleName, moduleName, mkHomeModule )
45 import ErrUtils ( dumpIfSet_dyn, showPass )
46 import Util ( unJust )
47 import UniqSupply ( mkSplitUniqSupply )
49 import Bag ( emptyBag )
52 import CmStaticInfo ( GhciMode(..) )
53 import HscStats ( ppSourceStats )
54 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
55 PersistentRenamerState(..), ModuleLocation(..),
57 OrigNameEnv(..), PackageRuleBase, HomeIfaceTable,
58 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
59 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
60 import OccName ( OccName )
61 import Name ( Name, nameModule, nameOccName, getName )
62 import Name ( emptyNameEnv )
63 import Module ( Module, lookupModuleEnvByName )
66 import Maybe ( isJust )
67 import IO ( hPutStrLn, stderr )
71 %************************************************************************
73 \subsection{The main compiler pipeline}
75 %************************************************************************
80 = HscFail PersistentCompilerState -- updated PCS
81 -- concluded that it wasn't necessary
82 | HscNoRecomp PersistentCompilerState -- updated PCS
83 ModDetails -- new details (HomeSymbolTable additions)
84 ModIface -- new iface (if any compilation was done)
86 | HscRecomp PersistentCompilerState -- updated PCS
87 ModDetails -- new details (HomeSymbolTable additions)
88 ModIface -- new iface (if any compilation was done)
89 (Maybe String) -- generated stub_h filename (in /tmp)
90 (Maybe String) -- generated stub_c filename (in /tmp)
91 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
94 -- no errors or warnings; the individual passes
95 -- (parse/rename/typecheck) print messages themselves
100 -> Bool -- source unchanged?
101 -> ModuleLocation -- location info
102 -> Maybe ModIface -- old interface, if available
103 -> HomeSymbolTable -- for home module ModDetails
105 -> PersistentCompilerState -- IN: persistent compiler state
108 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
110 showPass dflags ("Checking old interface for hs = "
111 ++ show (ml_hs_file location)
112 ++ ", hspp = " ++ show (ml_hspp_file location));
114 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
115 <- checkOldIface dflags hit hst pcs
116 (unJust "hscMain" (ml_hi_file location))
117 source_unchanged maybe_old_iface;
120 return (HscFail pcs_ch)
123 let no_old_iface = not (isJust maybe_checked_iface)
124 what_next | recomp_reqd || no_old_iface = hscRecomp
125 | otherwise = hscNoRecomp
127 what_next ghci_mode dflags location maybe_checked_iface
132 -- we definitely expect to have the old interface available
133 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
134 | ghci_mode == OneShot
135 = let bomb = panic "hscNoRecomp:OneShot"
136 in return (HscNoRecomp pcs_ch bomb bomb)
139 hPutStrLn stderr "COMPILATION NOT REQUIRED";
142 (pcs_cl, closure_errs, cl_hs_decls)
143 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
145 return (HscFail pcs_cl)
149 maybe_tc_result <- typecheckModule dflags pcs_cl hst
150 old_iface alwaysQualify cl_hs_decls;
151 case maybe_tc_result of {
152 Nothing -> return (HscFail pcs_cl);
153 Just (pcs_tc, tc_result) -> do {
155 let env_tc = tc_env tc_result
156 local_insts = tc_insts tc_result
157 local_rules = tc_rules tc_result
159 -- create a new details from the closed, typechecked, old iface
160 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
162 return (HscNoRecomp pcs_tc new_details old_iface)
166 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
168 ; hPutStrLn stderr "COMPILATION IS REQUIRED";
170 -- what target are we shooting for?
171 ; let toInterp = dopt_HscLang dflags == HscInterpreted
176 ; maybe_parsed <- myParseModule dflags
177 (unJust "hscRecomp:hspp" (ml_hspp_file location))
178 ; case maybe_parsed of {
179 Nothing -> return (HscFail pcs_ch);
180 Just rdr_module -> do {
181 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
186 ; showPass dflags "Rename"
187 ; (pcs_rn, maybe_rn_result)
188 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
189 ; case maybe_rn_result of {
190 Nothing -> return (HscFail pcs_rn);
191 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
196 ; showPass dflags "Typecheck"
197 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
198 print_unqualified rn_hs_decls
199 ; case maybe_tc_result of {
200 Nothing -> do { hPutStrLn stderr "Typecheck failed"
201 ; return (HscFail pcs_rn) } ;
202 Just (pcs_tc, tc_result) -> do {
204 ; let env_tc = tc_env tc_result
205 local_insts = tc_insts tc_result
208 -- DESUGAR, SIMPLIFY, TIDY-CORE
210 -- We grab the the unfoldings at this point.
211 ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod
212 print_unqualified is_exported tc_result
213 ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
218 ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
219 <- myCoreToStg dflags this_mod tidy_binds
223 -- BUILD THE NEW ModDetails AND ModIface
225 ; let new_details = mkModDetails env_tc local_insts tidy_binds
226 top_level_ids orphan_rules
227 ; final_iface <- mkFinalIface ghci_mode dflags location
228 maybe_checked_iface new_iface new_details
231 -- COMPLETE CODE GENERATION
233 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
234 <- restOfCodeGeneration dflags toInterp this_mod
235 (map ideclName (hsModuleImports rdr_module))
236 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
239 -- and the answer is ...
240 ; return (HscRecomp pcs_tc new_details final_iface
241 maybe_stub_h_filename maybe_stub_c_filename
247 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
248 = case completeIface maybe_old_iface new_iface new_details of
249 (new_iface, Nothing) -- no change in the interfacfe
250 -> do when (dopt Opt_D_dump_hi_diffs dflags)
251 (printDump (text "INTERFACE UNCHANGED"))
252 dumpIfSet_dyn dflags Opt_D_dump_hi
253 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
255 (new_iface, Just sdoc_diffs)
256 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
258 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
260 -- Write the interface file
261 when (ghci_mode /= Interactive)
262 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
267 myParseModule dflags src_filename
268 = do -------------------------- Parser ----------------
269 showPass dflags "Parser"
272 buf <- hGetStringBuffer True{-expand tabs-} src_filename
274 let glaexts | dopt Opt_GlasgowExts dflags = 1#
277 case parse buf PState{ bol = 0#, atbol = 1#,
278 context = [], glasgow_exts = glaexts,
279 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
281 PFailed err -> do { hPutStrLn stderr (showSDoc err);
284 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
286 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
288 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
289 (ppSourceStats False rdr_module) ;
291 return (Just rdr_module)
295 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
296 foreign_stuff env_tc stg_binds oa_tidy_binds
297 hit pit -- these last two for mapping ModNames to Modules
299 = do (ibinds,itbl_env)
300 <- stgBindsToInterpSyn dflags (map fst stg_binds)
301 local_tycons local_classes
302 return (Nothing, Nothing, Just (ibinds,itbl_env))
305 = do -------------------------- Code generation -------------------------------
307 abstractC <- codeGen dflags this_mod imported_modules
308 cost_centre_info fe_binders
309 local_tycons stg_binds
311 -------------------------- Code output -------------------------------
312 -- _scc_ "CodeOutput"
313 (maybe_stub_h_name, maybe_stub_c_name)
314 <- codeOutput dflags this_mod local_tycons
315 oa_tidy_binds stg_binds
316 c_code h_code abstractC
318 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
320 local_tycons = typeEnvTyCons env_tc
321 local_classes = typeEnvClasses env_tc
322 imported_modules = map mod_name_to_Module imported_module_names
323 (fe_binders,h_code,c_code) = foreign_stuff
325 mod_name_to_Module :: ModuleName -> Module
326 mod_name_to_Module nm
327 = let str_mi = case lookupModuleEnvByName hit nm of
329 Nothing -> case lookupModuleEnvByName pit nm of
333 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
337 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
338 = do -------------------------- Desugaring ----------------
339 showPass dflags "DeSugar"
341 (desugared, rules, h_code, c_code, fe_binders)
342 <- deSugar dflags pcs hst this_mod print_unqual tc_result
344 -------------------------- Main Core-language transformations ----------------
346 (simplified, orphan_rules)
347 <- core2core dflags pcs hst is_exported desugared rules
349 -- Do the final tidy-up
350 showPass dflags "TidyCore"
351 (tidy_binds, tidy_orphan_rules)
352 <- tidyCorePgm dflags this_mod simplified orphan_rules
354 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
357 myCoreToStg dflags this_mod tidy_binds
359 st_uniqs <- mkSplitUniqSupply 'g'
360 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
362 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
363 -- TEMP: the above call zaps some space usage allocated by the
364 -- simplifier, which for reasons I don't understand, persists
365 -- thoroughout code generation
368 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
370 showPass dflags "Stg2Stg"
372 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
373 let final_ids = collectFinalStgBinders (map fst stg_binds2)
375 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
379 %************************************************************************
381 \subsection{Compiling an expression}
383 %************************************************************************
390 -> PersistentCompilerState -- IN: persistent compiler state
391 -> Module -- Context for compiling
392 -> String -- The expression
393 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
396 hscExpr dflags hst hit pcs this_module expr
397 = panic "hscExpr: non-interactive build"
400 hscExpr dflags hst hit pcs0 this_module expr
402 maybe_parsed <- hscParseExpr dflags expr;
404 Nothing -> return (pcs0, Nothing)
405 Just parsed_expr -> do {
408 (pcs1, maybe_renamed_expr) <-
409 renameExpr dflags hit hst pcs0 this_module parsed_expr;
410 case maybe_renamed_expr of
411 Nothing -> return (pcs1, Nothing)
412 Just (print_unqual, rn_expr) -> do {
416 <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
417 case maybe_tc_return of
418 Nothing -> return (pcs1, Nothing)
419 Just (pcs2, tc_expr) -> do {
422 ds_expr <- deSugarExpr dflags pcs2 hst this_module
423 print_unqual tc_expr;
426 simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
429 stg_expr <- coreToStgExpr dflags simpl_expr;
431 -- ToDo: need to do StgVarInfo? or SRTs?
433 -- Convert to InterpSyn
434 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
436 return (pcs2, Just unlinked_iexpr);
439 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
440 hscParseExpr dflags str
441 = do -------------------------- Parser ----------------
442 showPass dflags "Parser"
445 buf <- stringToStringBuffer ("__expr " ++ str)
447 -- glaexts is True for now (because of the daft __expr at the front
450 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
453 case parse buf PState{ bol = 0#, atbol = 1#,
454 context = [], glasgow_exts = glaexts,
455 loc = mkSrcLoc SLIT("<no file>") 0 } of {
457 PFailed err -> do { freeStringBuffer buf
458 ; hPutStrLn stderr (showSDoc err)
461 POk _ (PExpr rdr_expr) -> do {
464 -- freeStringBuffer buf;
466 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
468 return (Just rdr_expr)
473 %************************************************************************
475 \subsection{Initial persistent state}
477 %************************************************************************
480 initPersistentCompilerState :: IO PersistentCompilerState
481 initPersistentCompilerState
482 = do prs <- initPersistentRenamerState
484 PCS { pcs_PIT = emptyIfaceTable,
485 pcs_PTE = wiredInThingEnv,
486 pcs_insts = emptyInstEnv,
487 pcs_rules = emptyRuleBase,
492 initPersistentRenamerState :: IO PersistentRenamerState
493 = do ns <- mkSplitUniqSupply 'r'
495 PRS { prsOrig = Orig { origNames = initOrigNames,
496 origIParam = emptyFM },
497 prsDecls = (emptyNameEnv, 0),
498 prsInsts = (emptyBag, 0),
499 prsRules = (emptyBag, 0),
504 initOrigNames :: FiniteMap (ModuleName,OccName) Name
506 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
508 grab names = foldl add emptyFM names
510 = addToFM env (moduleName (nameModule name), nameOccName name) name
513 initRules :: PackageRuleBase
514 initRules = emptyRuleBase
516 foldl add emptyVarEnv builtinRules
519 = extendRuleBase env name rule