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 Unique ( Uniquable(..) )
48 import PrelNames ( ioTyConKey )
49 import UniqSupply ( mkSplitUniqSupply )
51 import Bag ( emptyBag )
54 import CmStaticInfo ( GhciMode(..) )
55 import HscStats ( ppSourceStats )
56 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
57 PersistentRenamerState(..), ModuleLocation(..),
59 OrigNameEnv(..), PackageRuleBase, HomeIfaceTable,
60 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
61 import Type ( splitTyConApp_maybe )
62 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
63 import OccName ( OccName )
64 import Name ( Name, nameModule, nameOccName, getName )
65 import Name ( emptyNameEnv )
66 import Module ( Module, lookupModuleEnvByName )
69 import Maybe ( isJust )
70 import IO ( hPutStrLn, stderr )
74 %************************************************************************
76 \subsection{The main compiler pipeline}
78 %************************************************************************
83 = HscFail PersistentCompilerState -- updated PCS
84 -- concluded that it wasn't necessary
85 | HscNoRecomp PersistentCompilerState -- updated PCS
86 ModDetails -- new details (HomeSymbolTable additions)
87 ModIface -- new iface (if any compilation was done)
89 | HscRecomp PersistentCompilerState -- updated PCS
90 ModDetails -- new details (HomeSymbolTable additions)
91 ModIface -- new iface (if any compilation was done)
92 (Maybe String) -- generated stub_h filename (in /tmp)
93 (Maybe String) -- generated stub_c filename (in /tmp)
94 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
97 -- no errors or warnings; the individual passes
98 -- (parse/rename/typecheck) print messages themselves
103 -> Bool -- source unchanged?
104 -> ModuleLocation -- location info
105 -> Maybe ModIface -- old interface, if available
106 -> HomeSymbolTable -- for home module ModDetails
108 -> PersistentCompilerState -- IN: persistent compiler state
111 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
113 showPass dflags ("Checking old interface for hs = "
114 ++ show (ml_hs_file location)
115 ++ ", hspp = " ++ show (ml_hspp_file location));
117 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
118 <- checkOldIface dflags hit hst pcs
119 (unJust "hscMain" (ml_hi_file location))
120 source_unchanged maybe_old_iface;
123 return (HscFail pcs_ch)
126 let no_old_iface = not (isJust maybe_checked_iface)
127 what_next | recomp_reqd || no_old_iface = hscRecomp
128 | otherwise = hscNoRecomp
130 what_next ghci_mode dflags location maybe_checked_iface
135 -- we definitely expect to have the old interface available
136 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
137 | ghci_mode == OneShot
138 = let bomb = panic "hscNoRecomp:OneShot"
139 in return (HscNoRecomp pcs_ch bomb bomb)
142 hPutStrLn stderr "compilation not required";
145 (pcs_cl, closure_errs, cl_hs_decls)
146 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
148 return (HscFail pcs_cl)
152 maybe_tc_result <- typecheckModule dflags pcs_cl hst
153 old_iface alwaysQualify cl_hs_decls;
154 case maybe_tc_result of {
155 Nothing -> return (HscFail pcs_cl);
156 Just (pcs_tc, tc_result) -> do {
158 let env_tc = tc_env tc_result
159 local_insts = tc_insts tc_result
160 local_rules = tc_rules tc_result
162 -- create a new details from the closed, typechecked, old iface
163 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
165 return (HscNoRecomp pcs_tc new_details old_iface)
169 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
171 ; hPutStrLn stderr "compilation IS required";
173 -- what target are we shooting for?
174 ; let toInterp = dopt_HscLang dflags == HscInterpreted
179 ; maybe_parsed <- myParseModule dflags
180 (unJust "hscRecomp:hspp" (ml_hspp_file location))
181 ; case maybe_parsed of {
182 Nothing -> return (HscFail pcs_ch);
183 Just rdr_module -> do {
184 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
189 ; showPass dflags "Rename"
190 ; (pcs_rn, maybe_rn_result)
191 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
192 ; case maybe_rn_result of {
193 Nothing -> return (HscFail pcs_rn);
194 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
199 ; showPass dflags "Typecheck"
200 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
201 print_unqualified rn_hs_decls
202 ; case maybe_tc_result of {
203 Nothing -> do { hPutStrLn stderr "Typecheck failed"
204 ; return (HscFail pcs_rn) } ;
205 Just (pcs_tc, tc_result) -> do {
207 ; let env_tc = tc_env tc_result
208 local_insts = tc_insts tc_result
211 -- DESUGAR, SIMPLIFY, TIDY-CORE
213 -- We grab the the unfoldings at this point.
214 ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod
215 print_unqualified is_exported tc_result
216 ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
221 ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
222 <- myCoreToStg dflags this_mod tidy_binds
226 -- BUILD THE NEW ModDetails AND ModIface
228 ; let new_details = mkModDetails env_tc local_insts tidy_binds
229 top_level_ids orphan_rules
230 ; final_iface <- mkFinalIface ghci_mode dflags location
231 maybe_checked_iface new_iface new_details
234 -- COMPLETE CODE GENERATION
236 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
237 <- restOfCodeGeneration dflags toInterp this_mod
238 (map ideclName (hsModuleImports rdr_module))
239 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
242 -- and the answer is ...
243 ; return (HscRecomp pcs_tc new_details final_iface
244 maybe_stub_h_filename maybe_stub_c_filename
250 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
251 = case completeIface maybe_old_iface new_iface new_details of
252 (new_iface, Nothing) -- no change in the interfacfe
253 -> do when (dopt Opt_D_dump_hi_diffs dflags)
254 (printDump (text "INTERFACE UNCHANGED"))
255 dumpIfSet_dyn dflags Opt_D_dump_hi
256 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
258 (new_iface, Just sdoc_diffs)
259 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
261 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
263 -- Write the interface file
264 when (ghci_mode /= Interactive)
265 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
270 myParseModule dflags src_filename
271 = do -------------------------- Parser ----------------
272 showPass dflags "Parser"
275 buf <- hGetStringBuffer True{-expand tabs-} src_filename
277 let glaexts | dopt Opt_GlasgowExts dflags = 1#
280 case parse buf PState{ bol = 0#, atbol = 1#,
281 context = [], glasgow_exts = glaexts,
282 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
284 PFailed err -> do { hPutStrLn stderr (showSDoc err);
287 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
289 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
291 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
292 (ppSourceStats False rdr_module) ;
294 return (Just rdr_module)
298 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
299 foreign_stuff env_tc stg_binds oa_tidy_binds
300 hit pit -- these last two for mapping ModNames to Modules
302 = do (ibinds,itbl_env)
303 <- stgBindsToInterpSyn dflags (map fst stg_binds)
304 local_tycons local_classes
305 return (Nothing, Nothing, Just (ibinds,itbl_env))
308 = do -------------------------- Code generation -------------------------------
310 abstractC <- codeGen dflags this_mod imported_modules
311 cost_centre_info fe_binders
312 local_tycons stg_binds
314 -------------------------- Code output -------------------------------
315 -- _scc_ "CodeOutput"
316 (maybe_stub_h_name, maybe_stub_c_name)
317 <- codeOutput dflags this_mod local_tycons
318 oa_tidy_binds stg_binds
319 c_code h_code abstractC
321 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
323 local_tycons = typeEnvTyCons env_tc
324 local_classes = typeEnvClasses env_tc
325 imported_modules = map mod_name_to_Module imported_module_names
326 (fe_binders,h_code,c_code) = foreign_stuff
328 mod_name_to_Module :: ModuleName -> Module
329 mod_name_to_Module nm
330 = let str_mi = case lookupModuleEnvByName hit nm of
332 Nothing -> case lookupModuleEnvByName pit nm of
336 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
340 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
341 = do -------------------------- Desugaring ----------------
342 showPass dflags "DeSugar"
344 (desugared, rules, h_code, c_code, fe_binders)
345 <- deSugar dflags pcs hst this_mod print_unqual tc_result
347 -------------------------- Main Core-language transformations ----------------
349 (simplified, orphan_rules)
350 <- core2core dflags pcs hst is_exported desugared rules
352 -- Do the final tidy-up
353 showPass dflags "TidyCore"
354 (tidy_binds, tidy_orphan_rules)
355 <- tidyCorePgm dflags this_mod simplified orphan_rules
357 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
360 myCoreToStg dflags this_mod tidy_binds
362 st_uniqs <- mkSplitUniqSupply 'g'
363 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
365 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
366 -- TEMP: the above call zaps some space usage allocated by the
367 -- simplifier, which for reasons I don't understand, persists
368 -- thoroughout code generation
371 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
373 showPass dflags "Stg2Stg"
375 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
376 let final_ids = collectFinalStgBinders (map fst stg_binds2)
378 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
382 %************************************************************************
384 \subsection{Compiling an expression}
386 %************************************************************************
393 -> PersistentCompilerState -- IN: persistent compiler state
394 -> Module -- Context for compiling
395 -> String -- The expression
396 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
399 hscExpr dflags hst hit pcs this_module expr
400 = panic "hscExpr: non-interactive build"
403 hscExpr dflags hst hit pcs0 this_module expr
405 maybe_parsed <- hscParseExpr dflags expr;
407 Nothing -> return (pcs0, Nothing)
408 Just parsed_expr -> do {
411 (pcs1, maybe_renamed_expr) <-
412 renameExpr dflags hit hst pcs0 this_module parsed_expr;
413 case maybe_renamed_expr of
414 Nothing -> return (pcs1, Nothing)
415 Just (print_unqual, rn_expr) -> do {
419 <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
420 case maybe_tc_return of
421 Nothing -> return (pcs1, Nothing)
422 Just (pcs2, tc_expr, ty) -> do {
424 let { is_IO_type = case splitTyConApp_maybe ty of {
425 Just (tycon, _) -> getUnique tycon == ioTyConKey;
430 then hscExpr dflags hst hit pcs2 this_module
431 ("print (" ++ expr ++ ")")
435 ds_expr <- deSugarExpr dflags pcs2 hst this_module
436 print_unqual tc_expr;
439 simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
442 stg_expr <- coreToStgExpr dflags simpl_expr;
444 -- ToDo: need to do StgVarInfo? or SRTs?
446 -- Convert to InterpSyn
447 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
449 return (pcs2, Just unlinked_iexpr);
452 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
453 hscParseExpr dflags str
454 = do -------------------------- Parser ----------------
455 showPass dflags "Parser"
458 buf <- stringToStringBuffer ("__expr " ++ str)
460 -- glaexts is True for now (because of the daft __expr at the front
463 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
466 case parse buf PState{ bol = 0#, atbol = 1#,
467 context = [], glasgow_exts = glaexts,
468 loc = mkSrcLoc SLIT("<no file>") 0 } of {
470 PFailed err -> do { freeStringBuffer buf;
471 hPutStrLn stderr (showSDoc err);
474 POk _ (PExpr rdr_expr) -> do {
476 --ToDo: can't free the string buffer until we've finished this
477 -- compilation sweep and all the identifiers have gone away.
478 --freeStringBuffer buf;
479 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
480 return (Just rdr_expr)
485 %************************************************************************
487 \subsection{Initial persistent state}
489 %************************************************************************
492 initPersistentCompilerState :: IO PersistentCompilerState
493 initPersistentCompilerState
494 = do prs <- initPersistentRenamerState
496 PCS { pcs_PIT = emptyIfaceTable,
497 pcs_PTE = wiredInThingEnv,
498 pcs_insts = emptyInstEnv,
499 pcs_rules = emptyRuleBase,
504 initPersistentRenamerState :: IO PersistentRenamerState
505 = do ns <- mkSplitUniqSupply 'r'
507 PRS { prsOrig = Orig { origNames = initOrigNames,
508 origIParam = emptyFM },
509 prsDecls = (emptyNameEnv, 0),
510 prsInsts = (emptyBag, 0),
511 prsRules = (emptyBag, 0),
516 initOrigNames :: FiniteMap (ModuleName,OccName) Name
518 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
520 grab names = foldl add emptyFM names
522 = addToFM env (moduleName (nameModule name), nameOccName name) name
525 initRules :: PackageRuleBase
526 initRules = emptyRuleBase
528 foldl add emptyVarEnv builtinRules
531 = extendRuleBase env name rule