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, mkModuleInThisPackage )
45 import ErrUtils ( dumpIfSet_dyn, showPass )
46 import Util ( unJust )
47 import UniqSupply ( mkSplitUniqSupply )
49 import Bag ( emptyBag )
51 import Interpreter ( stgBindsToInterpSyn, UnlinkedIExpr, UnlinkedIBind, ItblEnv )
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 %************************************************************************
79 = HscOK ModDetails -- new details (HomeSymbolTable additions)
80 (Maybe ModIface) -- new iface (if any compilation was done)
81 (Maybe String) -- generated stub_h filename (in /tmp)
82 (Maybe String) -- generated stub_c filename (in /tmp)
83 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
84 PersistentCompilerState -- updated PCS
86 | HscFail PersistentCompilerState -- updated PCS
87 -- no errors or warnings; the individual passes
88 -- (parse/rename/typecheck) print messages themselves
93 -> Bool -- source unchanged?
94 -> ModuleLocation -- location info
95 -> Maybe ModIface -- old interface, if available
96 -> HomeSymbolTable -- for home module ModDetails
98 -> PersistentCompilerState -- IN: persistent compiler state
101 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
103 showPass dflags ("Checking old interface for hs = "
104 ++ show (ml_hs_file location)
105 ++ ", hspp = " ++ show (ml_hspp_file location));
107 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
108 <- checkOldIface dflags hit hst pcs
109 (unJust "hscMain" (ml_hi_file location))
110 source_unchanged maybe_old_iface;
113 return (HscFail pcs_ch)
116 let no_old_iface = not (isJust maybe_checked_iface)
117 what_next | recomp_reqd || no_old_iface = hscRecomp
118 | otherwise = hscNoRecomp
120 what_next ghci_mode dflags location maybe_checked_iface
125 -- we definitely expect to have the old interface available
126 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
127 | ghci_mode == OneShot
129 (panic "hscNoRecomp:OneShot") -- no details
130 Nothing -- makes run_phase Hsc stop
131 Nothing Nothing -- foreign export stuff
136 hPutStrLn stderr "COMPILATION NOT REQUIRED";
139 (pcs_cl, closure_errs, cl_hs_decls)
140 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
142 return (HscFail pcs_cl)
146 maybe_tc_result <- typecheckModule dflags pcs_cl hst
147 old_iface alwaysQualify cl_hs_decls;
148 case maybe_tc_result of {
149 Nothing -> return (HscFail pcs_cl);
150 Just (pcs_tc, tc_result) -> do {
152 let env_tc = tc_env tc_result
153 local_insts = tc_insts tc_result
154 local_rules = tc_rules tc_result
156 -- create a new details from the closed, typechecked, old iface
157 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
159 return (HscOK new_details
160 Nothing -- tells CM to use old iface and linkables
161 Nothing Nothing -- foreign export stuff
167 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
169 ; hPutStrLn stderr "COMPILATION IS REQUIRED";
171 -- what target are we shooting for?
172 ; let toInterp = dopt_HscLang dflags == HscInterpreted
177 ; maybe_parsed <- myParseModule dflags
178 (unJust "hscRecomp:hspp" (ml_hspp_file location))
179 ; case maybe_parsed of {
180 Nothing -> return (HscFail pcs_ch);
181 Just rdr_module -> do {
182 ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
187 ; showPass dflags "Rename"
188 ; (pcs_rn, maybe_rn_result)
189 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
190 ; case maybe_rn_result of {
191 Nothing -> return (HscFail pcs_rn);
192 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
197 ; showPass dflags "Typecheck"
198 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
199 print_unqualified rn_hs_decls
200 ; case maybe_tc_result of {
201 Nothing -> do { hPutStrLn stderr "Typecheck failed"
202 ; return (HscFail pcs_rn) } ;
203 Just (pcs_tc, tc_result) -> do {
205 ; let env_tc = tc_env tc_result
206 local_insts = tc_insts tc_result
209 -- DESUGAR, SIMPLIFY, TIDY-CORE
211 -- We grab the the unfoldings at this point.
212 ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod
213 print_unqualified is_exported tc_result
214 ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
219 ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
220 <- myCoreToStg dflags this_mod tidy_binds
224 -- BUILD THE NEW ModDetails AND ModIface
226 ; let new_details = mkModDetails env_tc local_insts tidy_binds
227 top_level_ids orphan_rules
228 ; final_iface <- mkFinalIface ghci_mode dflags location
229 maybe_checked_iface new_iface new_details
232 -- COMPLETE CODE GENERATION
234 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
235 <- restOfCodeGeneration dflags toInterp this_mod
236 (map ideclName (hsModuleImports rdr_module))
237 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
240 -- and the answer is ...
241 ; return (HscOK new_details (Just final_iface)
242 maybe_stub_h_filename maybe_stub_c_filename
248 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
249 = case completeIface maybe_old_iface new_iface new_details of
250 (new_iface, Nothing) -- no change in the interfacfe
251 -> do when (dopt Opt_D_dump_hi_diffs dflags)
252 (printDump (text "INTERFACE UNCHANGED"))
253 dumpIfSet_dyn dflags Opt_D_dump_hi
254 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
256 (new_iface, Just sdoc_diffs)
257 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
259 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
261 -- Write the interface file
262 when (ghci_mode /= Interactive)
263 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
268 myParseModule dflags src_filename
269 = do -------------------------- Parser ----------------
270 showPass dflags "Parser"
273 buf <- hGetStringBuffer True{-expand tabs-} src_filename
275 let glaexts | dopt Opt_GlasgowExts dflags = 1#
278 case parse buf PState{ bol = 0#, atbol = 1#,
279 context = [], glasgow_exts = glaexts,
280 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
282 PFailed err -> do { hPutStrLn stderr (showSDoc err);
285 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
287 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
289 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
290 (ppSourceStats False rdr_module) ;
292 return (Just rdr_module)
296 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
297 foreign_stuff env_tc stg_binds oa_tidy_binds
298 hit pit -- these last two for mapping ModNames to Modules
300 = do (ibinds,itbl_env)
301 <- stgBindsToInterpSyn dflags (map fst stg_binds)
302 local_tycons local_classes
303 return (Nothing, Nothing, Just (ibinds,itbl_env))
306 = do -------------------------- Code generation -------------------------------
308 abstractC <- codeGen dflags this_mod imported_modules
309 cost_centre_info fe_binders
310 local_tycons stg_binds
312 -------------------------- Code output -------------------------------
313 -- _scc_ "CodeOutput"
314 (maybe_stub_h_name, maybe_stub_c_name)
315 <- codeOutput dflags this_mod local_tycons
316 oa_tidy_binds stg_binds
317 c_code h_code abstractC
319 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
321 local_tycons = typeEnvTyCons env_tc
322 local_classes = typeEnvClasses env_tc
323 imported_modules = map mod_name_to_Module imported_module_names
324 (fe_binders,h_code,c_code) = foreign_stuff
326 mod_name_to_Module :: ModuleName -> Module
327 mod_name_to_Module nm
328 = let str_mi = case lookupModuleEnvByName hit nm of
330 Nothing -> case lookupModuleEnvByName pit nm of
334 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
338 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
339 = do -------------------------- Desugaring ----------------
340 showPass dflags "DeSugar"
342 (desugared, rules, h_code, c_code, fe_binders)
343 <- deSugar dflags pcs hst this_mod print_unqual tc_result
345 -------------------------- Main Core-language transformations ----------------
347 (simplified, orphan_rules)
348 <- core2core dflags pcs hst is_exported desugared rules
350 -- Do the final tidy-up
351 showPass dflags "TidyCore"
352 (tidy_binds, tidy_orphan_rules)
353 <- tidyCorePgm dflags this_mod simplified orphan_rules
355 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
358 myCoreToStg dflags this_mod tidy_binds
360 st_uniqs <- mkSplitUniqSupply 'g'
361 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
363 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
364 -- TEMP: the above call zaps some space usage allocated by the
365 -- simplifier, which for reasons I don't understand, persists
366 -- thoroughout code generation
369 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
371 showPass dflags "Stg2Stg"
373 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
374 let final_ids = collectFinalStgBinders (map fst stg_binds2)
376 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
380 %************************************************************************
382 \subsection{Compiling an expression}
384 %************************************************************************
391 -> PersistentCompilerState -- IN: persistent compiler state
392 -> Module -- Context for compiling
393 -> String -- The expression
394 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
397 hscExpr dflags hst hit pcs this_module expr
398 = panic "hscExpr: non-interactive build"
401 hscExpr dflags hst hit pcs0 this_module expr
403 maybe_parsed <- hscParseExpr dflags expr;
405 Nothing -> return (pcs0, Nothing)
406 Just parsed_expr -> do {
409 (pcs1, maybe_renamed_expr) <-
410 renameExpr dflags hit hst pcs0 this_module parsed_expr;
411 case maybe_renamed_expr of
412 Nothing -> return (pcs1, Nothing)
413 Just (print_unqual, rn_expr) -> do {
416 maybe_tc_expr <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
417 case maybe_tc_expr of
418 Nothing -> return (pcs1, Nothing)
422 ds_expr <- deSugarExpr dflags pcs1 hst this_module
423 print_unqual tc_expr;
426 simpl_expr <- simplifyExpr dflags pcs1 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 (pcs1, 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