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, hscTypeExpr,
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 )
33 import InstEnv ( emptyInstEnv )
36 import OccurAnal ( occurAnalyseBinds )
37 import CoreUtils ( coreBindsSize )
38 import CoreTidy ( tidyCorePgm )
39 import CoreToStg ( topCoreBindsToStg )
40 import StgSyn ( collectFinalStgBinders )
41 import SimplStg ( stg2stg )
42 import CodeGen ( codeGen )
43 import CodeOutput ( codeOutput )
45 import Module ( ModuleName, moduleName, mkHomeModule )
47 import ErrUtils ( dumpIfSet_dyn, showPass )
48 import Util ( unJust )
49 import Unique ( Uniquable(..) )
50 import PrelNames ( ioTyConKey )
51 import UniqSupply ( mkSplitUniqSupply )
53 import Bag ( emptyBag )
56 import CmStaticInfo ( GhciMode(..) )
57 import HscStats ( ppSourceStats )
58 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
59 PersistentRenamerState(..), ModuleLocation(..),
61 OrigNameEnv(..), PackageRuleBase, HomeIfaceTable,
62 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
63 import Type ( splitTyConApp_maybe )
64 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
65 import OccName ( OccName )
66 import Name ( Name, nameModule, nameOccName, getName )
67 import Name ( emptyNameEnv )
68 import Module ( Module, lookupModuleEnvByName )
71 import Maybe ( isJust )
72 import IO ( hPutStrLn, stderr )
76 %************************************************************************
78 \subsection{The main compiler pipeline}
80 %************************************************************************
85 = HscFail PersistentCompilerState -- updated PCS
86 -- concluded that it wasn't necessary
87 | HscNoRecomp PersistentCompilerState -- updated PCS
88 ModDetails -- new details (HomeSymbolTable additions)
89 ModIface -- new iface (if any compilation was done)
91 | HscRecomp PersistentCompilerState -- updated PCS
92 ModDetails -- new details (HomeSymbolTable additions)
93 ModIface -- new iface (if any compilation was done)
94 (Maybe String) -- generated stub_h filename (in /tmp)
95 (Maybe String) -- generated stub_c filename (in /tmp)
96 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
99 -- no errors or warnings; the individual passes
100 -- (parse/rename/typecheck) print messages themselves
105 -> Bool -- source unchanged?
106 -> ModuleLocation -- location info
107 -> Maybe ModIface -- old interface, if available
108 -> HomeSymbolTable -- for home module ModDetails
110 -> PersistentCompilerState -- IN: persistent compiler state
113 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
115 showPass dflags ("Checking old interface for hs = "
116 ++ show (ml_hs_file location)
117 ++ ", hspp = " ++ show (ml_hspp_file location));
119 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
120 <- checkOldIface dflags hit hst pcs
121 (unJust "hscMain" (ml_hi_file location))
122 source_unchanged maybe_old_iface;
125 return (HscFail pcs_ch)
128 let no_old_iface = not (isJust maybe_checked_iface)
129 what_next | recomp_reqd || no_old_iface = hscRecomp
130 | otherwise = hscNoRecomp
132 what_next ghci_mode dflags location maybe_checked_iface
137 -- we definitely expect to have the old interface available
138 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
139 | ghci_mode == OneShot
140 = let bomb = panic "hscNoRecomp:OneShot"
141 in return (HscNoRecomp pcs_ch bomb bomb)
144 hPutStrLn stderr "compilation IS NOT required";
147 (pcs_cl, closure_errs, cl_hs_decls)
148 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
150 return (HscFail pcs_cl)
154 maybe_tc_result <- typecheckModule dflags pcs_cl hst
155 old_iface alwaysQualify cl_hs_decls;
156 case maybe_tc_result of {
157 Nothing -> return (HscFail pcs_cl);
158 Just (pcs_tc, tc_result) -> do {
160 let env_tc = tc_env tc_result
161 local_insts = tc_insts tc_result
162 local_rules = tc_rules tc_result
164 -- create a new details from the closed, typechecked, old iface
165 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
167 return (HscNoRecomp pcs_tc new_details old_iface)
171 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
173 ; when (verbosity dflags >= 1) $
174 hPutStrLn stderr "compilation IS required";
176 -- what target are we shooting for?
177 ; let toInterp = dopt_HscLang dflags == HscInterpreted
182 ; maybe_parsed <- myParseModule dflags
183 (unJust "hscRecomp:hspp" (ml_hspp_file location))
184 ; case maybe_parsed of {
185 Nothing -> return (HscFail pcs_ch);
186 Just rdr_module -> do {
187 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
192 ; (pcs_rn, maybe_rn_result)
193 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
194 ; case maybe_rn_result of {
195 Nothing -> return (HscFail pcs_rn);
196 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
201 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
202 print_unqualified rn_hs_decls
203 ; case maybe_tc_result of {
204 Nothing -> 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 ----------------
343 (desugared, rules, h_code, c_code, fe_binders)
344 <- deSugar dflags pcs hst this_mod print_unqual tc_result
346 -------------------------- Main Core-language transformations ----------------
348 (simplified, orphan_rules)
349 <- core2core dflags pcs hst is_exported desugared rules
351 -- Do the final tidy-up
352 (tidy_binds, tidy_orphan_rules)
353 <- tidyCorePgm dflags this_mod simplified orphan_rules
355 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
358 myCoreToStg dflags this_mod tidy_binds
360 st_uniqs <- mkSplitUniqSupply 'g'
361 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
363 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
364 -- TEMP: the above call zaps some space usage allocated by the
365 -- simplifier, which for reasons I don't understand, persists
366 -- thoroughout code generation
369 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
371 showPass dflags "Stg2Stg"
373 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
374 let final_ids = collectFinalStgBinders (map fst stg_binds2)
376 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
380 %************************************************************************
382 \subsection{Compiling an expression}
384 %************************************************************************
388 hscExpr dflags hst hit pcs this_module expr
389 = panic "hscExpr: non-interactive build"
390 hscTypeExpr dflags hst hit pcs0 this_module expr
391 = panic "hscTypeExpr: non-interactive build"
398 -> PersistentCompilerState -- IN: persistent compiler state
399 -> Module -- Context for compiling
400 -> String -- The expression
401 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
403 hscExpr dflags hst hit pcs0 this_module expr
405 -- parse, rename & typecheck the expression
406 (pcs1, maybe_tc_result)
407 <- hscExprFrontEnd dflags hst hit pcs0 this_module expr;
409 case maybe_tc_result of {
410 Nothing -> return (pcs1, Nothing);
411 Just (print_unqual, tc_expr, ty) -> do {
413 -- if it isn't an IO-typed expression,
414 -- wrap "print" around it & recompile...
415 let { is_IO_type = case splitTyConApp_maybe ty of {
416 Just (tycon, _) -> getUnique tycon == ioTyConKey;
421 then hscExpr dflags hst hit pcs1 this_module
422 ("print (" ++ expr ++ ")")
426 ds_expr <- deSugarExpr dflags pcs1 hst this_module
427 print_unqual tc_expr;
430 simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
433 stg_expr <- coreToStgExpr dflags simpl_expr;
435 -- ToDo: need to do StgVarInfo? or SRTs?
437 -- Convert to InterpSyn
438 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
440 return (pcs1, Just unlinked_iexpr);
447 -> PersistentCompilerState -- IN: persistent compiler state
448 -> Module -- Context for compiling
449 -> String -- The expression
450 -> IO ( PersistentCompilerState,
451 Maybe (PrintUnqualified,TypecheckedHsExpr,Type)
453 hscExprFrontEnd dflags hst hit pcs0 this_module expr
455 maybe_parsed <- hscParseExpr dflags expr;
457 Nothing -> return (pcs0, Nothing)
458 Just parsed_expr -> do {
461 (pcs1, maybe_renamed_expr) <-
462 renameExpr dflags hit hst pcs0 this_module parsed_expr;
463 case maybe_renamed_expr of
464 Nothing -> return (pcs1, Nothing)
465 Just (print_unqual, rn_expr) -> do {
469 <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
470 case maybe_tc_return of
471 Nothing -> return (pcs1, Nothing)
472 Just (pcs2, tc_expr, ty) ->
473 return (pcs2, Just (print_unqual, tc_expr, ty))
480 -> PersistentCompilerState -- IN: persistent compiler state
481 -> Module -- Context for compiling
482 -> String -- The expression
483 -> IO (PersistentCompilerState, Maybe (PrintUnqualified, Type))
484 hscTypeExpr dflags hst hit pcs0 this_module expr
485 = do (pcs1, maybe_tc_result)
486 <- hscExprFrontEnd dflags hst hit pcs0 this_module expr
487 case maybe_tc_result of
488 Nothing -> return (pcs1, Nothing)
489 Just (print_unqual,_,ty) -> return (pcs1, Just (print_unqual,ty))
491 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
492 hscParseExpr dflags str
493 = do -------------------------- Parser ----------------
494 showPass dflags "Parser"
497 buf <- stringToStringBuffer ("__expr " ++ str)
499 -- glaexts is True for now (because of the daft __expr at the front
502 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
505 case parse buf PState{ bol = 0#, atbol = 1#,
506 context = [], glasgow_exts = glaexts,
507 loc = mkSrcLoc SLIT("<no file>") 0 } of {
509 PFailed err -> do { freeStringBuffer buf;
510 hPutStrLn stderr (showSDoc err);
513 POk _ (PExpr rdr_expr) -> do {
515 --ToDo: can't free the string buffer until we've finished this
516 -- compilation sweep and all the identifiers have gone away.
517 --freeStringBuffer buf;
518 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
519 return (Just rdr_expr)
524 %************************************************************************
526 \subsection{Initial persistent state}
528 %************************************************************************
531 initPersistentCompilerState :: IO PersistentCompilerState
532 initPersistentCompilerState
533 = do prs <- initPersistentRenamerState
535 PCS { pcs_PIT = emptyIfaceTable,
536 pcs_PTE = wiredInThingEnv,
537 pcs_insts = emptyInstEnv,
538 pcs_rules = emptyRuleBase,
543 initPersistentRenamerState :: IO PersistentRenamerState
544 = do ns <- mkSplitUniqSupply 'r'
546 PRS { prsOrig = Orig { origNames = initOrigNames,
547 origIParam = emptyFM },
548 prsDecls = (emptyNameEnv, 0),
549 prsInsts = (emptyBag, 0),
550 prsRules = (emptyBag, 0),
555 initOrigNames :: FiniteMap (ModuleName,OccName) Name
557 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
559 grab names = foldl add emptyFM names
561 = addToFM env (moduleName (nameModule name), nameOccName name) name
564 initRules :: PackageRuleBase
565 initRules = emptyRuleBase
567 foldl add emptyVarEnv builtinRules
570 = extendRuleBase env name rule