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"
12 import Maybe ( isJust )
13 import IO ( hPutStrLn, stderr )
16 import StringBuffer ( hGetStringBuffer,
17 stringToStringBuffer, freeStringBuffer )
19 import RdrHsSyn ( RdrNameHsExpr )
20 import Lex ( PState(..), ParseResult(..) )
21 import SrcLoc ( mkSrcLoc )
24 import Rules ( emptyRuleBase )
25 import PrelInfo ( wiredInThingEnv, wiredInThings )
26 import PrelNames ( knownKeyNames )
27 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
28 writeIface, pprIface )
30 import InstEnv ( emptyInstEnv )
33 import OccurAnal ( occurAnalyseBinds )
34 import CoreUtils ( coreBindsSize )
35 import CoreTidy ( tidyCorePgm )
36 import CoreToStg ( topCoreBindsToStg, coreToStgExpr )
37 import StgSyn ( collectFinalStgBinders )
38 import SimplStg ( stg2stg )
39 import CodeGen ( codeGen )
40 import CodeOutput ( codeOutput )
42 import Module ( ModuleName, moduleName, mkModuleInThisPackage )
44 import ErrUtils ( dumpIfSet_dyn, showPass )
45 import Util ( unJust )
46 import UniqSupply ( mkSplitUniqSupply )
48 import Bag ( emptyBag )
51 import CmStaticInfo ( GhciMode(..) )
52 import HscStats ( ppSourceStats )
53 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
54 PersistentRenamerState(..), ModuleLocation(..),
56 OrigNameEnv(..), PackageRuleBase, HomeIfaceTable,
57 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
58 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
59 import OccName ( OccName )
60 import Name ( Name, nameModule, nameOccName, getName )
61 import Name ( emptyNameEnv )
62 import Module ( Module, lookupModuleEnvByName )
68 %************************************************************************
70 \subsection{The main compiler pipeline}
72 %************************************************************************
76 = HscOK ModDetails -- new details (HomeSymbolTable additions)
77 (Maybe ModIface) -- new iface (if any compilation was done)
78 (Maybe String) -- generated stub_h filename (in /tmp)
79 (Maybe String) -- generated stub_c filename (in /tmp)
80 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
81 PersistentCompilerState -- updated PCS
83 | HscFail PersistentCompilerState -- updated PCS
84 -- no errors or warnings; the individual passes
85 -- (parse/rename/typecheck) print messages themselves
90 -> Bool -- source unchanged?
91 -> ModuleLocation -- location info
92 -> Maybe ModIface -- old interface, if available
93 -> HomeSymbolTable -- for home module ModDetails
95 -> PersistentCompilerState -- IN: persistent compiler state
98 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
100 showPass dflags ("Checking old interface for hs = "
101 ++ show (ml_hs_file location)
102 ++ ", hspp = " ++ show (ml_hspp_file location));
104 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
105 <- checkOldIface dflags hit hst pcs
106 (unJust (ml_hi_file location) "hscMain")
107 source_unchanged maybe_old_iface;
110 return (HscFail pcs_ch)
113 let no_old_iface = not (isJust maybe_checked_iface)
114 what_next | recomp_reqd || no_old_iface = hscRecomp
115 | otherwise = hscNoRecomp
117 what_next ghci_mode dflags location maybe_checked_iface
122 -- we definitely expect to have the old interface available
123 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
124 | ghci_mode == OneShot
126 (panic "hscNoRecomp:OneShot") -- no details
127 Nothing -- makes run_phase Hsc stop
128 Nothing Nothing -- foreign export stuff
133 hPutStrLn stderr "COMPILATION NOT REQUIRED";
134 let this_mod = mi_module old_iface
137 (pcs_cl, closure_errs, cl_hs_decls)
138 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
140 return (HscFail pcs_cl)
144 maybe_tc_result <- typecheckModule dflags pcs_cl hst
145 old_iface alwaysQualify cl_hs_decls;
146 case maybe_tc_result of {
147 Nothing -> return (HscFail pcs_cl);
148 Just (pcs_tc, tc_result) -> do {
150 let env_tc = tc_env tc_result
151 local_insts = tc_insts tc_result
152 local_rules = tc_rules tc_result
154 -- create a new details from the closed, typechecked, old iface
155 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
157 return (HscOK new_details
158 Nothing -- tells CM to use old iface and linkables
159 Nothing Nothing -- foreign export stuff
165 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
167 ; hPutStrLn stderr "COMPILATION IS REQUIRED";
169 -- what target are we shooting for?
170 ; let toInterp = dopt_HscLang dflags == HscInterpreted
175 ; maybe_parsed <- myParseModule dflags (unJust (ml_hspp_file location)
177 ; case maybe_parsed of {
178 Nothing -> return (HscFail pcs_ch);
179 Just rdr_module -> do {
180 ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
185 ; showPass dflags "Rename"
186 ; (pcs_rn, maybe_rn_result)
187 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
188 ; case maybe_rn_result of {
189 Nothing -> return (HscFail pcs_rn);
190 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
195 ; showPass dflags "Typecheck"
196 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
197 print_unqualified rn_hs_decls
198 ; case maybe_tc_result of {
199 Nothing -> do { hPutStrLn stderr "Typecheck failed"
200 ; return (HscFail pcs_rn) } ;
201 Just (pcs_tc, tc_result) -> do {
203 ; let env_tc = tc_env tc_result
204 local_insts = tc_insts tc_result
207 -- DESUGAR, SIMPLIFY, TIDY-CORE
209 -- We grab the the unfoldings at this point.
210 ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod
211 print_unqualified is_exported tc_result
212 ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
217 ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
218 <- myCoreToStg dflags this_mod tidy_binds
222 -- BUILD THE NEW ModDetails AND ModIface
224 ; let new_details = mkModDetails env_tc local_insts tidy_binds
225 top_level_ids orphan_rules
226 ; final_iface <- mkFinalIface dflags location maybe_checked_iface
227 new_iface new_details
230 -- COMPLETE CODE GENERATION
232 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
233 <- restOfCodeGeneration dflags toInterp this_mod
234 (map ideclName (hsModuleImports rdr_module))
235 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
238 -- and the answer is ...
239 ; return (HscOK new_details (Just final_iface)
240 maybe_stub_h_filename maybe_stub_c_filename
246 mkFinalIface dflags location maybe_old_iface new_iface new_details
247 = case completeIface maybe_old_iface new_iface new_details of
248 (new_iface, Nothing) -- no change in the interfacfe
249 -> do when (dopt Opt_D_dump_hi_diffs dflags)
250 (printDump (text "INTERFACE UNCHANGED"))
251 dumpIfSet_dyn dflags Opt_D_dump_hi
252 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
254 (new_iface, Just sdoc_diffs)
255 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
256 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
257 -- Write the interface file
258 writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
262 myParseModule dflags src_filename
263 = do -------------------------- Parser ----------------
264 showPass dflags "Parser"
267 buf <- hGetStringBuffer True{-expand tabs-} src_filename
269 let glaexts | dopt Opt_GlasgowExts dflags = 1#
272 case parse buf PState{ bol = 0#, atbol = 1#,
273 context = [], glasgow_exts = glaexts,
274 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
276 PFailed err -> do { hPutStrLn stderr (showSDoc err);
279 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
281 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
283 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
284 (ppSourceStats False rdr_module) ;
286 return (Just rdr_module)
290 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
291 foreign_stuff env_tc stg_binds oa_tidy_binds
292 hit pit -- these last two for mapping ModNames to Modules
294 = do (ibinds,itbl_env)
295 <- stgBindsToInterpSyn dflags (map fst stg_binds)
296 local_tycons local_classes
297 return (Nothing, Nothing, Just (ibinds,itbl_env))
300 = do -------------------------- Code generation -------------------------------
302 abstractC <- codeGen dflags this_mod imported_modules
303 cost_centre_info fe_binders
304 local_tycons stg_binds
306 -------------------------- Code output -------------------------------
307 -- _scc_ "CodeOutput"
308 (maybe_stub_h_name, maybe_stub_c_name)
309 <- codeOutput dflags this_mod local_tycons
310 oa_tidy_binds stg_binds
311 c_code h_code abstractC
313 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
315 local_tycons = typeEnvTyCons env_tc
316 local_classes = typeEnvClasses env_tc
317 imported_modules = map mod_name_to_Module imported_module_names
318 (fe_binders,h_code,c_code) = foreign_stuff
320 mod_name_to_Module :: ModuleName -> Module
321 mod_name_to_Module nm
322 = let str_mi = case lookupModuleEnvByName hit nm of
324 Nothing -> case lookupModuleEnvByName pit nm of
328 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
332 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
333 = do -------------------------- Desugaring ----------------
334 showPass dflags "DeSugar"
336 (desugared, rules, h_code, c_code, fe_binders)
337 <- deSugar dflags pcs hst this_mod print_unqual tc_result
339 -------------------------- Main Core-language transformations ----------------
341 (simplified, orphan_rules)
342 <- core2core dflags pcs hst is_exported desugared rules
344 -- Do the final tidy-up
345 showPass dflags "TidyCore"
346 (tidy_binds, tidy_orphan_rules)
347 <- tidyCorePgm dflags this_mod simplified orphan_rules
349 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
352 myCoreToStg dflags this_mod tidy_binds
354 st_uniqs <- mkSplitUniqSupply 'g'
355 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
357 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
358 -- TEMP: the above call zaps some space usage allocated by the
359 -- simplifier, which for reasons I don't understand, persists
360 -- thoroughout code generation
363 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
365 showPass dflags "Stg2Stg"
367 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
368 let final_ids = collectFinalStgBinders (map fst stg_binds2)
370 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
374 %************************************************************************
376 \subsection{Compiling an expression}
378 %************************************************************************
385 -> PersistentCompilerState -- IN: persistent compiler state
386 -> Module -- Context for compiling
387 -> String -- The expression
388 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
390 hscExpr dflags hst hit pcs0 this_module expr
392 maybe_parsed <- hscParseExpr dflags expr;
394 Nothing -> return (pcs0, Nothing)
395 Just parsed_expr -> do {
398 (pcs1, maybe_renamed_expr) <-
399 renameExpr dflags hit hst pcs0 this_module parsed_expr;
400 case maybe_renamed_expr of
401 Nothing -> return (pcs1, Nothing)
402 Just (print_unqual, rn_expr) -> do {
405 maybe_tc_expr <- typecheckExpr dflags pcs1 hst print_unqual rn_expr;
406 case maybe_tc_expr of
407 Nothing -> return (pcs1, Nothing)
411 ds_expr <- deSugarExpr dflags pcs1 hst this_module
412 print_unqual tc_expr;
415 simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
418 stg_expr <- coreToStgExpr dflags simpl_expr;
420 -- ToDo: need to do StgVarInfo? or SRTs?
422 -- Convert to InterpSyn
423 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
425 return (pcs1, Just unlinked_iexpr);
428 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
429 hscParseExpr dflags str
430 = do -------------------------- Parser ----------------
431 showPass dflags "Parser"
434 buf <- stringToStringBuffer ("__expr " ++ str)
436 -- glaexts is True for now (because of the daft __expr at the front
439 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
442 case parse buf PState{ bol = 0#, atbol = 1#,
443 context = [], glasgow_exts = glaexts,
444 loc = mkSrcLoc SLIT("<no file>") 0 } of {
446 PFailed err -> do { freeStringBuffer buf
447 ; hPutStrLn stderr (showSDoc err)
450 POk _ (PExpr rdr_expr) -> do {
453 -- freeStringBuffer buf;
455 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
457 return (Just rdr_expr)
461 %************************************************************************
463 \subsection{Initial persistent state}
465 %************************************************************************
468 initPersistentCompilerState :: IO PersistentCompilerState
469 initPersistentCompilerState
470 = do prs <- initPersistentRenamerState
472 PCS { pcs_PIT = emptyIfaceTable,
473 pcs_PTE = wiredInThingEnv,
474 pcs_insts = emptyInstEnv,
475 pcs_rules = emptyRuleBase,
480 initPersistentRenamerState :: IO PersistentRenamerState
481 = do ns <- mkSplitUniqSupply 'r'
483 PRS { prsOrig = Orig { origNames = initOrigNames,
484 origIParam = emptyFM },
485 prsDecls = (emptyNameEnv, 0),
486 prsInsts = (emptyBag, 0),
487 prsRules = (emptyBag, 0),
492 initOrigNames :: FiniteMap (ModuleName,OccName) Name
494 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
496 grab names = foldl add emptyFM names
498 = addToFM env (moduleName (nameModule name), nameOccName name) name
501 initRules :: PackageRuleBase
502 initRules = emptyRuleBase
504 foldl add emptyVarEnv builtinRules
507 = extendRuleBase env name rule