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 "hscMain" (ml_hi_file location))
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
176 (unJust "hscRecomp:hspp" (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 ghci_mode dflags location
227 maybe_checked_iface 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 ghci_mode 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"
257 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
259 -- Write the interface file
260 when (ghci_mode /= Interactive)
261 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
266 myParseModule dflags src_filename
267 = do -------------------------- Parser ----------------
268 showPass dflags "Parser"
271 buf <- hGetStringBuffer True{-expand tabs-} src_filename
273 let glaexts | dopt Opt_GlasgowExts dflags = 1#
276 case parse buf PState{ bol = 0#, atbol = 1#,
277 context = [], glasgow_exts = glaexts,
278 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
280 PFailed err -> do { hPutStrLn stderr (showSDoc err);
283 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
285 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
287 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
288 (ppSourceStats False rdr_module) ;
290 return (Just rdr_module)
294 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
295 foreign_stuff env_tc stg_binds oa_tidy_binds
296 hit pit -- these last two for mapping ModNames to Modules
298 = do (ibinds,itbl_env)
299 <- stgBindsToInterpSyn dflags (map fst stg_binds)
300 local_tycons local_classes
301 return (Nothing, Nothing, Just (ibinds,itbl_env))
304 = do -------------------------- Code generation -------------------------------
306 abstractC <- codeGen dflags this_mod imported_modules
307 cost_centre_info fe_binders
308 local_tycons stg_binds
310 -------------------------- Code output -------------------------------
311 -- _scc_ "CodeOutput"
312 (maybe_stub_h_name, maybe_stub_c_name)
313 <- codeOutput dflags this_mod local_tycons
314 oa_tidy_binds stg_binds
315 c_code h_code abstractC
317 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
319 local_tycons = typeEnvTyCons env_tc
320 local_classes = typeEnvClasses env_tc
321 imported_modules = map mod_name_to_Module imported_module_names
322 (fe_binders,h_code,c_code) = foreign_stuff
324 mod_name_to_Module :: ModuleName -> Module
325 mod_name_to_Module nm
326 = let str_mi = case lookupModuleEnvByName hit nm of
328 Nothing -> case lookupModuleEnvByName pit nm of
332 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
336 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
337 = do -------------------------- Desugaring ----------------
338 showPass dflags "DeSugar"
340 (desugared, rules, h_code, c_code, fe_binders)
341 <- deSugar dflags pcs hst this_mod print_unqual tc_result
343 -------------------------- Main Core-language transformations ----------------
345 (simplified, orphan_rules)
346 <- core2core dflags pcs hst is_exported desugared rules
348 -- Do the final tidy-up
349 showPass dflags "TidyCore"
350 (tidy_binds, tidy_orphan_rules)
351 <- tidyCorePgm dflags this_mod simplified orphan_rules
353 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
356 myCoreToStg dflags this_mod tidy_binds
358 st_uniqs <- mkSplitUniqSupply 'g'
359 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
361 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
362 -- TEMP: the above call zaps some space usage allocated by the
363 -- simplifier, which for reasons I don't understand, persists
364 -- thoroughout code generation
367 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
369 showPass dflags "Stg2Stg"
371 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
372 let final_ids = collectFinalStgBinders (map fst stg_binds2)
374 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
378 %************************************************************************
380 \subsection{Compiling an expression}
382 %************************************************************************
389 -> PersistentCompilerState -- IN: persistent compiler state
390 -> Module -- Context for compiling
391 -> String -- The expression
392 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
394 hscExpr dflags hst hit pcs0 this_module expr
396 maybe_parsed <- hscParseExpr dflags expr;
398 Nothing -> return (pcs0, Nothing)
399 Just parsed_expr -> do {
402 (pcs1, maybe_renamed_expr) <-
403 renameExpr dflags hit hst pcs0 this_module parsed_expr;
404 case maybe_renamed_expr of
405 Nothing -> return (pcs1, Nothing)
406 Just (print_unqual, rn_expr) -> do {
409 maybe_tc_expr <- typecheckExpr dflags pcs1 hst print_unqual rn_expr;
410 case maybe_tc_expr of
411 Nothing -> return (pcs1, Nothing)
415 ds_expr <- deSugarExpr dflags pcs1 hst this_module
416 print_unqual tc_expr;
419 simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
422 stg_expr <- coreToStgExpr dflags simpl_expr;
424 -- ToDo: need to do StgVarInfo? or SRTs?
426 -- Convert to InterpSyn
427 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
429 return (pcs1, Just unlinked_iexpr);
432 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
433 hscParseExpr dflags str
434 = do -------------------------- Parser ----------------
435 showPass dflags "Parser"
438 buf <- stringToStringBuffer ("__expr " ++ str)
440 -- glaexts is True for now (because of the daft __expr at the front
443 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
446 case parse buf PState{ bol = 0#, atbol = 1#,
447 context = [], glasgow_exts = glaexts,
448 loc = mkSrcLoc SLIT("<no file>") 0 } of {
450 PFailed err -> do { freeStringBuffer buf
451 ; hPutStrLn stderr (showSDoc err)
454 POk _ (PExpr rdr_expr) -> do {
457 -- freeStringBuffer buf;
459 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
461 return (Just rdr_expr)
465 %************************************************************************
467 \subsection{Initial persistent state}
469 %************************************************************************
472 initPersistentCompilerState :: IO PersistentCompilerState
473 initPersistentCompilerState
474 = do prs <- initPersistentRenamerState
476 PCS { pcs_PIT = emptyIfaceTable,
477 pcs_PTE = wiredInThingEnv,
478 pcs_insts = emptyInstEnv,
479 pcs_rules = emptyRuleBase,
484 initPersistentRenamerState :: IO PersistentRenamerState
485 = do ns <- mkSplitUniqSupply 'r'
487 PRS { prsOrig = Orig { origNames = initOrigNames,
488 origIParam = emptyFM },
489 prsDecls = (emptyNameEnv, 0),
490 prsInsts = (emptyBag, 0),
491 prsRules = (emptyBag, 0),
496 initOrigNames :: FiniteMap (ModuleName,OccName) Name
498 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
500 grab names = foldl add emptyFM names
502 = addToFM env (moduleName (nameModule name), nameOccName name) name
505 initRules :: PackageRuleBase
506 initRules = emptyRuleBase
508 foldl add emptyVarEnv builtinRules
511 = extendRuleBase env name rule