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 )
13 import IO ( hPutStrLn, stderr )
16 import StringBuffer ( hGetStringBuffer )
18 import Lex ( PState(..), ParseResult(..) )
19 import SrcLoc ( mkSrcLoc )
21 import Rename ( renameModule, checkOldIface, closeIfaceDecls )
22 import Rules ( emptyRuleBase )
23 import PrelInfo ( wiredInThingEnv, wiredInThings )
24 import PrelNames ( knownKeyNames )
25 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
26 writeIface, pprIface )
27 import TcModule ( TcResults(..), typecheckModule )
28 import InstEnv ( emptyInstEnv )
29 import Desugar ( deSugar )
30 import SimplCore ( core2core )
31 import OccurAnal ( occurAnalyseBinds )
32 import CoreUtils ( coreBindsSize )
33 import CoreTidy ( tidyCorePgm )
34 import CoreToStg ( topCoreBindsToStg )
35 import StgSyn ( collectFinalStgBinders )
36 import SimplStg ( stg2stg )
37 import CodeGen ( codeGen )
38 import CodeOutput ( codeOutput )
40 import Module ( ModuleName, moduleName, mkModuleInThisPackage )
42 import ErrUtils ( dumpIfSet_dyn, showPass )
43 import Util ( unJust )
44 import UniqSupply ( mkSplitUniqSupply )
46 import Bag ( emptyBag )
48 import Interpreter ( UnlinkedIBind, ItblEnv, stgToInterpSyn )
49 import CmStaticInfo ( GhciMode(..) )
50 import HscStats ( ppSourceStats )
51 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
52 PersistentRenamerState(..), ModuleLocation(..),
54 OrigNameEnv(..), PackageRuleBase, HomeIfaceTable,
55 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
56 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
57 import OccName ( OccName )
58 import Name ( Name, nameModule, nameOccName, getName )
59 import Name ( emptyNameEnv )
60 import Module ( Module, lookupModuleEnvByName )
66 %************************************************************************
68 \subsection{The main compiler pipeline}
70 %************************************************************************
74 = HscOK ModDetails -- new details (HomeSymbolTable additions)
75 (Maybe ModIface) -- new iface (if any compilation was done)
76 (Maybe String) -- generated stub_h filename (in /tmp)
77 (Maybe String) -- generated stub_c filename (in /tmp)
78 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
79 PersistentCompilerState -- updated PCS
81 | HscFail PersistentCompilerState -- updated PCS
82 -- no errors or warnings; the individual passes
83 -- (parse/rename/typecheck) print messages themselves
88 -> Bool -- source unchanged?
89 -> ModuleLocation -- location info
90 -> Maybe ModIface -- old interface, if available
91 -> HomeSymbolTable -- for home module ModDetails
93 -> PersistentCompilerState -- IN: persistent compiler state
96 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
98 putStrLn ("CHECKING OLD IFACE for hs = " ++ show (ml_hs_file location)
99 ++ ", hspp = " ++ show (ml_hspp_file location));
101 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
102 <- checkOldIface dflags hit hst pcs (unJust (ml_hi_file location) "hscMain")
103 source_unchanged maybe_old_iface;
106 return (HscFail pcs_ch)
109 let no_old_iface = not (isJust maybe_checked_iface)
110 what_next | recomp_reqd || no_old_iface = hscRecomp
111 | otherwise = hscNoRecomp
113 what_next ghci_mode dflags location maybe_checked_iface
118 -- we definitely expect to have the old interface available
119 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
120 | ghci_mode == OneShot
122 (panic "hscNoRecomp:OneShot") -- no details
123 Nothing -- makes run_phase Hsc stop
124 Nothing Nothing -- foreign export stuff
129 hPutStrLn stderr "COMPILATION NOT REQUIRED";
130 let this_mod = mi_module old_iface
133 (pcs_cl, closure_errs, cl_hs_decls)
134 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
136 return (HscFail pcs_cl)
140 maybe_tc_result <- typecheckModule dflags pcs_cl hst
141 old_iface alwaysQualify cl_hs_decls;
142 case maybe_tc_result of {
143 Nothing -> return (HscFail pcs_cl);
144 Just (pcs_tc, tc_result) -> do {
146 let env_tc = tc_env tc_result
147 local_insts = tc_insts tc_result
148 local_rules = tc_rules tc_result
150 -- create a new details from the closed, typechecked, old iface
151 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
153 return (HscOK new_details
154 Nothing -- tells CM to use old iface and linkables
155 Nothing Nothing -- foreign export stuff
161 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
163 ; hPutStrLn stderr "COMPILATION IS REQUIRED";
165 -- what target are we shooting for?
166 ; let toInterp = dopt_HscLang dflags == HscInterpreted
171 ; maybe_parsed <- myParseModule dflags (unJust (ml_hspp_file location) "hscRecomp:hspp")
172 ; case maybe_parsed of {
173 Nothing -> return (HscFail pcs_ch);
174 Just rdr_module -> do {
175 ; let this_mod = mkModuleInThisPackage (hsModuleName rdr_module)
180 ; (pcs_rn, maybe_rn_result)
181 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
182 ; case maybe_rn_result of {
183 Nothing -> return (HscFail pcs_rn);
184 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
189 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
190 print_unqualified rn_hs_decls
191 ; case maybe_tc_result of {
192 Nothing -> do { hPutStrLn stderr "Typecheck failed"
193 ; return (HscFail pcs_rn) } ;
194 Just (pcs_tc, tc_result) -> do {
196 ; let env_tc = tc_env tc_result
197 local_insts = tc_insts tc_result
200 -- DESUGAR, SIMPLIFY, TIDY-CORE
202 -- We grab the the unfoldings at this point.
203 ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod
204 print_unqualified is_exported tc_result
205 ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
210 ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
211 <- myCoreToStg dflags this_mod tidy_binds
215 -- BUILD THE NEW ModDetails AND ModIface
217 ; let new_details = mkModDetails env_tc local_insts tidy_binds
218 top_level_ids orphan_rules
219 ; final_iface <- mkFinalIface dflags location maybe_checked_iface
220 new_iface new_details
223 -- COMPLETE CODE GENERATION
225 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
226 <- restOfCodeGeneration dflags toInterp this_mod
227 (map ideclName (hsModuleImports rdr_module))
228 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
231 -- and the answer is ...
232 ; return (HscOK new_details (Just final_iface)
233 maybe_stub_h_filename maybe_stub_c_filename
239 mkFinalIface dflags location maybe_old_iface new_iface new_details
240 = case completeIface maybe_old_iface new_iface new_details of
241 (new_iface, Nothing) -- no change in the interfacfe
242 -> do when (dopt Opt_D_dump_hi_diffs dflags)
243 (printDump (text "INTERFACE UNCHANGED"))
244 dumpIfSet_dyn dflags Opt_D_dump_hi
245 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
247 (new_iface, Just sdoc_diffs)
248 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
249 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
250 -- Write the interface file
251 writeIface (unJust (ml_hi_file location) "hscRecomp:hi") new_iface
255 myParseModule dflags src_filename
256 = do -------------------------- Parser ----------------
257 showPass dflags "Parser"
260 buf <- hGetStringBuffer True{-expand tabs-} src_filename
262 let glaexts | dopt Opt_GlasgowExts dflags = 1#
265 case parse buf PState{ bol = 0#, atbol = 1#,
266 context = [], glasgow_exts = glaexts,
267 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
269 PFailed err -> do { hPutStrLn stderr (showSDoc err);
272 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
274 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
276 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
277 (ppSourceStats False rdr_module) ;
279 return (Just rdr_module)
283 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
284 foreign_stuff env_tc stg_binds oa_tidy_binds
285 hit pit -- these last two for mapping ModNames to Modules
287 = do (ibinds,itbl_env)
288 <- stgToInterpSyn (map fst stg_binds) local_tycons local_classes
289 return (Nothing, Nothing, Just (ibinds,itbl_env))
292 = do -------------------------- Code generation -------------------------------
294 abstractC <- codeGen dflags this_mod imported_modules
295 cost_centre_info fe_binders
296 local_tycons stg_binds
298 -------------------------- Code output -------------------------------
299 -- _scc_ "CodeOutput"
300 (maybe_stub_h_name, maybe_stub_c_name)
301 <- codeOutput dflags this_mod local_tycons
302 oa_tidy_binds stg_binds
303 c_code h_code abstractC
305 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
307 local_tycons = typeEnvTyCons env_tc
308 local_classes = typeEnvClasses env_tc
309 imported_modules = map mod_name_to_Module imported_module_names
310 (fe_binders,h_code,c_code) = foreign_stuff
312 mod_name_to_Module :: ModuleName -> Module
313 mod_name_to_Module nm
314 = let str_mi = case lookupModuleEnvByName hit nm of
316 Nothing -> case lookupModuleEnvByName pit nm of
320 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
324 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
325 = do -------------------------- Desugaring ----------------
327 (desugared, rules, h_code, c_code, fe_binders)
328 <- deSugar dflags pcs hst this_mod print_unqual tc_result
330 -------------------------- Main Core-language transformations ----------------
332 (simplified, orphan_rules)
333 <- core2core dflags pcs hst is_exported desugared rules
335 -- Do the final tidy-up
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 showPass dflags "Core2Stg"
355 let stg_binds = topCoreBindsToStg c2s_uniqs occ_anal_tidy_binds
357 showPass 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)
366 %************************************************************************
368 \subsection{Compiling an expression}
370 %************************************************************************
376 -> PersistentCompilerState -- IN: persistent compiler state
377 -> Module -- Context for compiling
378 -> String -- The expression
381 hscExpr dflags hst hit pcs this_module expr
383 maybe_parsed <- myParseExpr dflags expr
384 ; case maybe_parsed of {
385 Nothing -> return (HscFail pcs_ch);
386 Just parsed_expr -> do {
389 (new_pcs, maybe_renamed_expr) <- renameExpr dflags hit hst pcs this_module parsed_expr ;
390 ; case maybe_renamed_expr of {
392 Just (print_unqual, rn_expr) ->
395 maybe_tc_expr <- typecheckExpr dflags pcs hst print_unqual rn_expr
396 ; case maybe_tc_expr of
401 ; ds_expr <- deSugarExpr dflags pcs hst this_module print_unqual tc_expr
404 ; simpl_expr <- simplifyExpr dflags pcs hst ds_expr
406 ; return I'M NOT SURE
412 %************************************************************************
414 \subsection{Initial persistent state}
416 %************************************************************************
419 initPersistentCompilerState :: IO PersistentCompilerState
420 initPersistentCompilerState
421 = do prs <- initPersistentRenamerState
423 PCS { pcs_PIT = emptyIfaceTable,
424 pcs_PTE = wiredInThingEnv,
425 pcs_insts = emptyInstEnv,
426 pcs_rules = emptyRuleBase,
431 initPersistentRenamerState :: IO PersistentRenamerState
432 = do ns <- mkSplitUniqSupply 'r'
434 PRS { prsOrig = Orig { origNames = initOrigNames,
435 origIParam = emptyFM },
436 prsDecls = (emptyNameEnv, 0),
437 prsInsts = (emptyBag, 0),
438 prsRules = (emptyBag, 0),
443 initOrigNames :: FiniteMap (ModuleName,OccName) Name
445 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
447 grab names = foldl add emptyFM names
449 = addToFM env (moduleName (nameModule name), nameOccName name) name
452 initRules :: PackageRuleBase
453 initRules = emptyRuleBase
455 foldl add emptyVarEnv builtinRules
458 = extendRuleBase env name rule