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,
8 initPersistentCompilerState ) where
10 #include "HsVersions.h"
12 import Maybe ( isJust )
14 import IO ( hPutStr, hPutStrLn, hClose, stderr,
15 openFile, IOMode(..) )
18 import RdrHsSyn ( RdrNameHsModule )
19 import FastString ( unpackFS )
20 import StringBuffer ( hGetStringBuffer )
21 import Parser ( parse )
22 import Lex ( PState(..), ParseResult(..) )
23 import SrcLoc ( mkSrcLoc )
25 import Rename ( renameModule, checkOldIface, closeIfaceDecls )
27 import Rules ( emptyRuleBase )
28 import PrelInfo ( wiredInThings )
29 import PrelNames ( knownKeyNames )
30 import PrelRules ( builtinRules )
31 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
33 import TcModule ( TcResults(..), typecheckModule )
34 import TcEnv ( tcEnvTyCons, tcEnvClasses )
35 import InstEnv ( emptyInstEnv )
36 import Desugar ( deSugar )
37 import SimplCore ( core2core )
38 import OccurAnal ( occurAnalyseBinds )
39 import CoreUtils ( coreBindsSize )
40 import CoreTidy ( tidyCorePgm )
41 import CoreToStg ( topCoreBindsToStg )
42 import StgSyn ( collectFinalStgBinders )
43 import SimplStg ( stg2stg )
44 import CodeGen ( codeGen )
45 import CodeOutput ( codeOutput )
47 import Module ( ModuleName, moduleNameUserString,
48 moduleUserString, moduleName, emptyModuleEnv,
51 import ErrUtils ( ghcExit, doIfSet, dumpIfSet_dyn )
52 import UniqSupply ( mkSplitUniqSupply )
54 import Bag ( emptyBag )
56 import Char ( isSpace )
57 import StgInterp ( stgToInterpSyn )
58 import HscStats ( ppSourceStats )
59 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
60 PersistentRenamerState(..), WhatsImported(..),
61 HomeSymbolTable, PackageSymbolTable, ImportVersion,
62 GenAvailInfo(..), RdrAvailInfo, OrigNameEnv(..),
63 PackageRuleBase, HomeIfaceTable, PackageIfaceTable,
64 extendTypeEnv, groupTyThings, TypeEnv, TyThing,
65 typeEnvClasses, typeEnvTyCons )
66 import RnMonad ( ExportItem, ParsedIface(..) )
67 import CmSummarise ( ModSummary(..), name_of_summary, ms_get_imports,
69 import Finder ( Finder )
70 import InterpSyn ( UnlinkedIBind )
71 import StgInterp ( ItblEnv )
72 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
73 import OccName ( OccName, pprOccName )
74 import Name ( Name, nameModule, emptyNameEnv, nameOccName,
75 getName, extendNameEnv_C, nameEnvElts )
76 import VarEnv ( emptyVarEnv )
77 import Module ( Module, mkModuleName, lookupModuleEnvByName )
82 %************************************************************************
84 \subsection{The main compiler pipeline}
86 %************************************************************************
90 = HscOK ModDetails -- new details (HomeSymbolTable additions)
91 (Maybe 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
95 PersistentCompilerState -- updated PCS
97 | HscFail PersistentCompilerState -- updated PCS
98 -- no errors or warnings; the individual passes
99 -- (parse/rename/typecheck) print messages themselves
104 -> ModSummary -- summary, including source filename
105 -> Maybe ModIface -- old interface, if available
106 -> HomeSymbolTable -- for home module ModDetails
109 -> PersistentCompilerState -- IN: persistent compiler state
112 hscMain dflags finder summary maybe_old_iface hst hit pit pcs
114 -- ????? source_unchanged :: Bool -- extracted from summary?
115 let source_unchanged = trace "WARNING: source_unchanged?!" False
117 (pcs_ch, check_errs, (recomp_reqd, maybe_checked_iface))
118 <- checkOldIface dflags finder hit hst pcs (ms_mod summary)
119 source_unchanged maybe_old_iface;
121 return (HscFail pcs_ch)
124 let no_old_iface = not (isJust maybe_checked_iface)
125 what_next | recomp_reqd || no_old_iface = hscRecomp
126 | otherwise = hscNoRecomp
128 what_next dflags finder summary maybe_checked_iface
133 hscNoRecomp dflags finder summary maybe_checked_iface hst hit pit pcs_ch
135 -- we definitely expect to have the old interface available
136 let old_iface = case maybe_checked_iface of
137 Just old_if -> old_if
138 Nothing -> panic "hscNoRecomp:old_iface"
141 (pcs_cl, closure_errs, cl_hs_decls)
142 <- closeIfaceDecls dflags finder hit hst pcs_ch old_iface ;
144 return (HscFail pcs_cl)
149 <- typecheckModule dflags (ms_mod summary) pcs_cl hst hit cl_hs_decls;
150 case maybe_tc_result of {
151 Nothing -> return (HscFail pcs_cl);
152 Just tc_result -> do {
154 let pcs_tc = tc_pcs tc_result
155 env_tc = tc_env tc_result
156 binds_tc = tc_binds tc_result
157 local_insts = tc_insts tc_result
158 local_rules = tc_rules tc_result
160 -- create a new details from the closed, typechecked, old iface
161 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
163 return (HscOK new_details
164 Nothing -- tells CM to use old iface and linkables
165 Nothing Nothing -- foreign export stuff
171 hscRecomp dflags finder summary maybe_checked_iface hst hit pit pcs_ch
173 -- what target are we shooting for?
174 let toInterp = dopt_HscLang dflags == HscInterpreted
175 this_mod = ms_mod summary
178 maybe_parsed <- myParseModule dflags summary;
179 case maybe_parsed of {
180 Nothing -> return (HscFail pcs_ch);
181 Just rdr_module -> do {
184 show_pass dflags "Renamer";
185 (pcs_rn, maybe_rn_result)
186 <- renameModule dflags finder hit hst pcs_ch this_mod rdr_module;
187 case maybe_rn_result of {
188 Nothing -> return (HscFail pcs_rn);
189 Just (new_iface, rn_hs_decls) -> do {
192 show_pass dflags "Typechecker";
194 <- typecheckModule dflags this_mod pcs_rn hst hit rn_hs_decls;
195 case maybe_tc_result of {
196 Nothing -> return (HscFail pcs_rn);
197 Just tc_result -> do {
199 let pcs_tc = tc_pcs tc_result
200 env_tc = tc_env tc_result
201 binds_tc = tc_binds tc_result
202 local_insts = tc_insts tc_result
204 -- DESUGAR, SIMPLIFY, TIDY-CORE
205 -- We grab the the unfoldings at this point.
206 (tidy_binds, orphan_rules, foreign_stuff)
207 <- dsThenSimplThenTidy dflags (pcs_rules pcs_tc) this_mod tc_result hst
210 (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
211 <- myCoreToStg dflags this_mod tidy_binds
213 -- cook up a new ModDetails now we (finally) have all the bits
214 let new_details = mkModDetails env_tc local_insts tidy_binds
215 top_level_ids orphan_rules
217 -- and possibly create a new ModIface
218 let maybe_final_iface_and_sdoc
219 = completeIface maybe_checked_iface new_iface new_details
221 = case maybe_final_iface_and_sdoc of
222 Just (fif, sdoc) -> Just fif; Nothing -> Nothing
224 -- SimonM does this, higher up
225 -- -- Write the interface file
226 -- writeIface finder maybe_final_iface
228 -- do the rest of code generation/emission
229 (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
230 <- restOfCodeGeneration dflags toInterp summary
231 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
234 -- and the answer is ...
235 return (HscOK new_details maybe_final_iface
236 maybe_stub_h_filename maybe_stub_c_filename
241 myParseModule dflags summary
242 = do -------------------------- Parser ----------------
243 show_pass dflags "Parser"
246 let src_filename -- name of the preprocessed source file
247 = case ms_ppsource summary of
248 Just (filename, fingerprint) -> filename
250 "myParseModule:summary is not of a source module"
253 buf <- hGetStringBuffer True{-expand tabs-} src_filename
255 let glaexts | dopt Opt_GlasgowExts dflags = 1#
258 case parse buf PState{ bol = 0#, atbol = 1#,
259 context = [], glasgow_exts = glaexts,
260 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
262 PFailed err -> do { hPutStrLn stderr (showSDoc err);
264 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
266 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
268 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
269 (ppSourceStats False rdr_module) ;
271 return (Just rdr_module)
275 restOfCodeGeneration dflags toInterp summary cost_centre_info
276 foreign_stuff env_tc stg_binds oa_tidy_binds
277 hit pit -- these last two for mapping ModNames to Modules
279 = do (ibinds,itbl_env)
280 <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
281 return (Nothing, Nothing, Just (ibinds,itbl_env))
283 = do -------------------------- Code generation -------------------------------
284 show_pass dflags "CodeGen"
286 abstractC <- codeGen dflags this_mod imported_modules
287 cost_centre_info fe_binders
288 local_tycons local_classes stg_binds
290 -------------------------- Code output -------------------------------
291 show_pass dflags "CodeOutput"
292 -- _scc_ "CodeOutput"
293 ncg_uniqs <- mkSplitUniqSupply 'n'
294 (maybe_stub_h_name, maybe_stub_c_name)
295 <- codeOutput dflags this_mod local_tycons local_classes
296 oa_tidy_binds stg_binds
297 c_code h_code abstractC ncg_uniqs
299 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
301 local_tycons = typeEnvTyCons env_tc
302 local_classes = typeEnvClasses env_tc
303 this_mod = ms_mod summary
304 imported_modules = map (mod_name_to_Module.mimp_name)
305 (ms_get_imports summary)
306 (fe_binders,h_code,c_code) = foreign_stuff
308 mod_name_to_Module :: ModuleName -> Module
309 mod_name_to_Module nm
310 = let str_mi = case lookupModuleEnvByName hit nm of
312 Nothing -> case lookupModuleEnvByName pit nm of
316 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
320 dsThenSimplThenTidy dflags rule_base this_mod tc_result hst
321 = do -------------------------- Desugaring ----------------
323 show_pass dflags "DeSugar"
324 ds_uniqs <- mkSplitUniqSupply 'd'
325 (desugared, rules, h_code, c_code, fe_binders)
326 <- deSugar dflags this_mod ds_uniqs hst tc_result
328 -------------------------- Main Core-language transformations ----------------
330 show_pass dflags "Core2Core"
331 (simplified, orphan_rules)
332 <- core2core dflags rule_base hst desugared rules
334 -- Do the final tidy-up
335 show_pass dflags "CoreTidy"
336 (tidy_binds, tidy_orphan_rules)
337 <- tidyCorePgm dflags this_mod simplified orphan_rules
339 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
342 myCoreToStg dflags this_mod tidy_binds
344 c2s_uniqs <- mkSplitUniqSupply 'c'
345 st_uniqs <- mkSplitUniqSupply 'g'
346 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
348 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
349 -- TEMP: the above call zaps some space usage allocated by the
350 -- simplifier, which for reasons I don't understand, persists
351 -- thoroughout code generation
353 show_pass dflags "Core2Stg"
355 let stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
357 show_pass dflags "Stg2Stg"
359 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
360 let final_ids = collectFinalStgBinders (map fst stg_binds2)
362 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
365 show_pass dflags what
366 = if dopt Opt_D_show_passes dflags
367 then hPutStr stderr ("*** "++what++":\n")
372 %************************************************************************
374 \subsection{Initial persistent state}
376 %************************************************************************
379 initPersistentCompilerState :: IO PersistentCompilerState
380 initPersistentCompilerState
381 = do prs <- initPersistentRenamerState
383 PCS { pcs_PST = initPackageDetails,
384 pcs_insts = emptyInstEnv,
385 pcs_rules = emptyRuleBase,
390 initPackageDetails :: PackageSymbolTable
391 initPackageDetails = extendTypeEnv emptyModuleEnv (groupTyThings wiredInThings)
393 --initPackageDetails = panic "initPackageDetails"
395 initPersistentRenamerState :: IO PersistentRenamerState
396 = do ns <- mkSplitUniqSupply 'r'
398 PRS { prsOrig = Orig { origNames = initOrigNames,
399 origIParam = emptyFM },
400 prsDecls = emptyNameEnv,
407 initOrigNames :: FiniteMap (ModuleName,OccName) Name
409 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
411 grab names = foldl add emptyFM names
413 = addToFM env (moduleName (nameModule name), nameOccName name) name
416 initRules :: PackageRuleBase
417 initRules = emptyRuleBase
419 foldl add emptyVarEnv builtinRules
422 = extendRuleBase env name rule