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, emptyIfaceTable )
66 import RnMonad ( ExportItem, ParsedIface(..) )
67 import CmSummarise ( ModSummary(..), name_of_summary, ms_get_imports,
69 import InterpSyn ( UnlinkedIBind )
70 import StgInterp ( ItblEnv )
71 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
72 import OccName ( OccName, pprOccName )
73 import Name ( Name, nameModule, emptyNameEnv, nameOccName,
74 getName, extendNameEnv_C, nameEnvElts )
75 import VarEnv ( emptyVarEnv )
76 import Module ( Module, mkModuleName, lookupModuleEnvByName )
81 %************************************************************************
83 \subsection{The main compiler pipeline}
85 %************************************************************************
89 = HscOK ModDetails -- new details (HomeSymbolTable additions)
90 (Maybe ModIface) -- new iface (if any compilation was done)
91 (Maybe String) -- generated stub_h filename (in /tmp)
92 (Maybe String) -- generated stub_c filename (in /tmp)
93 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
94 PersistentCompilerState -- updated PCS
96 | HscFail PersistentCompilerState -- updated PCS
97 -- no errors or warnings; the individual passes
98 -- (parse/rename/typecheck) print messages themselves
102 -> ModSummary -- summary, including source filename
103 -> Maybe ModIface -- old interface, if available
104 -> HomeSymbolTable -- for home module ModDetails
106 -> PersistentCompilerState -- IN: persistent compiler state
109 hscMain dflags summary maybe_old_iface hst hit pcs
111 -- ????? source_unchanged :: Bool -- extracted from summary?
112 let source_unchanged = trace "WARNING: source_unchanged?!" False
114 putStrLn "checking old iface ...";
115 (pcs_ch, check_errs, (recomp_reqd, maybe_checked_iface))
116 <- checkOldIface dflags hit hst pcs (ms_mod summary)
117 source_unchanged maybe_old_iface;
119 return (HscFail pcs_ch)
122 let no_old_iface = not (isJust maybe_checked_iface)
123 what_next | recomp_reqd || no_old_iface = hscRecomp
124 | otherwise = hscNoRecomp
126 putStrLn "doing what_next ...";
127 what_next dflags summary maybe_checked_iface
132 hscNoRecomp dflags summary maybe_checked_iface hst hit pcs_ch
134 -- we definitely expect to have the old interface available
135 let old_iface = case maybe_checked_iface of
136 Just old_if -> old_if
137 Nothing -> panic "hscNoRecomp:old_iface"
140 (pcs_cl, closure_errs, cl_hs_decls)
141 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
143 return (HscFail pcs_cl)
148 <- typecheckModule dflags (ms_mod summary) pcs_cl hst hit cl_hs_decls;
149 case maybe_tc_result of {
150 Nothing -> return (HscFail pcs_cl);
151 Just tc_result -> do {
153 let pcs_tc = tc_pcs tc_result
154 env_tc = tc_env tc_result
155 binds_tc = tc_binds tc_result
156 local_insts = tc_insts tc_result
157 local_rules = tc_rules tc_result
159 -- create a new details from the closed, typechecked, old iface
160 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
162 return (HscOK new_details
163 Nothing -- tells CM to use old iface and linkables
164 Nothing Nothing -- foreign export stuff
170 hscRecomp dflags summary maybe_checked_iface hst hit pcs_ch
172 -- what target are we shooting for?
173 let toInterp = dopt_HscLang dflags == HscInterpreted
174 this_mod = ms_mod summary
177 maybe_parsed <- myParseModule dflags summary;
178 case maybe_parsed of {
179 Nothing -> return (HscFail pcs_ch);
180 Just rdr_module -> do {
183 show_pass dflags "Renamer";
184 (pcs_rn, maybe_rn_result)
185 <- renameModule dflags hit hst pcs_ch this_mod rdr_module;
186 case maybe_rn_result of {
187 Nothing -> return (HscFail pcs_rn);
188 Just (new_iface, rn_hs_decls) -> do {
191 show_pass dflags "Typechecker";
193 <- typecheckModule dflags this_mod pcs_rn hst hit rn_hs_decls;
194 case maybe_tc_result of {
195 Nothing -> return (HscFail pcs_rn);
196 Just tc_result -> do {
198 let pcs_tc = tc_pcs tc_result
199 env_tc = tc_env tc_result
200 binds_tc = tc_binds tc_result
201 local_insts = tc_insts tc_result
203 -- DESUGAR, SIMPLIFY, TIDY-CORE
204 -- We grab the the unfoldings at this point.
205 (tidy_binds, orphan_rules, foreign_stuff)
206 <- dsThenSimplThenTidy dflags (pcs_rules pcs_tc) this_mod tc_result hst
209 (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
210 <- myCoreToStg dflags this_mod tidy_binds
212 -- cook up a new ModDetails now we (finally) have all the bits
213 let new_details = mkModDetails env_tc local_insts tidy_binds
214 top_level_ids orphan_rules
216 -- and possibly create a new ModIface
217 let maybe_final_iface_and_sdoc
218 = completeIface maybe_checked_iface new_iface new_details
220 = case maybe_final_iface_and_sdoc of
221 Just (fif, sdoc) -> Just fif; Nothing -> Nothing
223 -- Write the interface file
224 writeIface maybe_final_iface
226 -- do the rest of code generation/emission
227 (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
228 <- restOfCodeGeneration dflags toInterp summary
229 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
232 -- and the answer is ...
233 return (HscOK new_details maybe_final_iface
234 maybe_stub_h_filename maybe_stub_c_filename
239 myParseModule dflags summary
240 = do -------------------------- Parser ----------------
241 show_pass dflags "Parser"
244 let src_filename -- name of the preprocessed source file
245 = case ms_ppsource summary of
246 Just (filename, fingerprint) -> filename
248 "myParseModule:summary is not of a source module"
251 buf <- hGetStringBuffer True{-expand tabs-} src_filename
253 let glaexts | dopt Opt_GlasgowExts dflags = 1#
256 case parse buf PState{ bol = 0#, atbol = 1#,
257 context = [], glasgow_exts = glaexts,
258 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
260 PFailed err -> do { hPutStrLn stderr (showSDoc err);
262 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
264 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
266 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
267 (ppSourceStats False rdr_module) ;
269 return (Just rdr_module)
273 restOfCodeGeneration dflags toInterp summary cost_centre_info
274 foreign_stuff env_tc stg_binds oa_tidy_binds
275 hit pit -- these last two for mapping ModNames to Modules
277 = do (ibinds,itbl_env)
278 <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
279 return (Nothing, Nothing, Just (ibinds,itbl_env))
281 = do -------------------------- Code generation -------------------------------
282 show_pass dflags "CodeGen"
284 abstractC <- codeGen dflags this_mod imported_modules
285 cost_centre_info fe_binders
286 local_tycons local_classes stg_binds
288 -------------------------- Code output -------------------------------
289 show_pass dflags "CodeOutput"
290 -- _scc_ "CodeOutput"
291 ncg_uniqs <- mkSplitUniqSupply 'n'
292 (maybe_stub_h_name, maybe_stub_c_name)
293 <- codeOutput dflags this_mod local_tycons local_classes
294 oa_tidy_binds stg_binds
295 c_code h_code abstractC ncg_uniqs
297 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
299 local_tycons = typeEnvTyCons env_tc
300 local_classes = typeEnvClasses env_tc
301 this_mod = ms_mod summary
302 imported_modules = map (mod_name_to_Module.mimp_name)
303 (ms_get_imports summary)
304 (fe_binders,h_code,c_code) = foreign_stuff
306 mod_name_to_Module :: ModuleName -> Module
307 mod_name_to_Module nm
308 = let str_mi = case lookupModuleEnvByName hit nm of
310 Nothing -> case lookupModuleEnvByName pit nm of
314 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
318 dsThenSimplThenTidy dflags rule_base this_mod tc_result hst
319 = do -------------------------- Desugaring ----------------
321 show_pass dflags "DeSugar"
322 ds_uniqs <- mkSplitUniqSupply 'd'
323 (desugared, rules, h_code, c_code, fe_binders)
324 <- deSugar dflags this_mod ds_uniqs hst tc_result
326 -------------------------- Main Core-language transformations ----------------
328 show_pass dflags "Core2Core"
329 (simplified, orphan_rules)
330 <- core2core dflags rule_base hst desugared rules
332 -- Do the final tidy-up
333 show_pass dflags "CoreTidy"
334 (tidy_binds, tidy_orphan_rules)
335 <- tidyCorePgm dflags this_mod simplified orphan_rules
337 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
340 myCoreToStg dflags this_mod tidy_binds
342 c2s_uniqs <- mkSplitUniqSupply 'c'
343 st_uniqs <- mkSplitUniqSupply 'g'
344 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
346 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
347 -- TEMP: the above call zaps some space usage allocated by the
348 -- simplifier, which for reasons I don't understand, persists
349 -- thoroughout code generation
351 show_pass dflags "Core2Stg"
353 let stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
355 show_pass dflags "Stg2Stg"
357 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
358 let final_ids = collectFinalStgBinders (map fst stg_binds2)
360 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
363 show_pass dflags what
364 = if dopt Opt_D_show_passes dflags
365 then hPutStr stderr ("*** "++what++":\n")
370 %************************************************************************
372 \subsection{Initial persistent state}
374 %************************************************************************
377 initPersistentCompilerState :: IO PersistentCompilerState
378 initPersistentCompilerState
379 = do prs <- initPersistentRenamerState
381 PCS { pcs_PIT = emptyIfaceTable,
382 pcs_PST = initPackageDetails,
383 pcs_insts = emptyInstEnv,
384 pcs_rules = emptyRuleBase,
389 initPackageDetails :: PackageSymbolTable
390 initPackageDetails = extendTypeEnv emptyModuleEnv (groupTyThings wiredInThings)
392 --initPackageDetails = panic "initPackageDetails"
394 initPersistentRenamerState :: IO PersistentRenamerState
395 = do ns <- mkSplitUniqSupply 'r'
397 PRS { prsOrig = Orig { origNames = initOrigNames,
398 origIParam = emptyFM },
399 prsDecls = emptyNameEnv,
406 initOrigNames :: FiniteMap (ModuleName,OccName) Name
408 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
410 grab names = foldl add emptyFM names
412 = addToFM env (moduleName (nameModule name), nameOccName name) name
415 initRules :: PackageRuleBase
416 initRules = emptyRuleBase
418 foldl add emptyVarEnv builtinRules
421 = extendRuleBase env name rule