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 ; showPass dflags "Rename"
193 ; (pcs_rn, maybe_rn_result)
194 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
195 ; case maybe_rn_result of {
196 Nothing -> return (HscFail pcs_rn);
197 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
202 ; showPass dflags "Typecheck"
203 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
204 print_unqualified rn_hs_decls
205 ; case maybe_tc_result of {
206 Nothing -> return (HscFail pcs_rn);
207 Just (pcs_tc, tc_result) -> do {
209 ; let env_tc = tc_env tc_result
210 local_insts = tc_insts tc_result
213 -- DESUGAR, SIMPLIFY, TIDY-CORE
215 -- We grab the the unfoldings at this point.
216 ; simpl_result <- dsThenSimplThenTidy dflags pcs_tc hst this_mod
217 print_unqualified is_exported tc_result
218 ; let (tidy_binds, orphan_rules, foreign_stuff) = simpl_result
223 ; (stg_binds, oa_tidy_binds, cost_centre_info, top_level_ids)
224 <- myCoreToStg dflags this_mod tidy_binds
228 -- BUILD THE NEW ModDetails AND ModIface
230 ; let new_details = mkModDetails env_tc local_insts tidy_binds
231 top_level_ids orphan_rules
232 ; final_iface <- mkFinalIface ghci_mode dflags location
233 maybe_checked_iface new_iface new_details
236 -- COMPLETE CODE GENERATION
238 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
239 <- restOfCodeGeneration dflags toInterp this_mod
240 (map ideclName (hsModuleImports rdr_module))
241 cost_centre_info foreign_stuff env_tc stg_binds oa_tidy_binds
244 -- and the answer is ...
245 ; return (HscRecomp pcs_tc new_details final_iface
246 maybe_stub_h_filename maybe_stub_c_filename
252 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
253 = case completeIface maybe_old_iface new_iface new_details of
254 (new_iface, Nothing) -- no change in the interfacfe
255 -> do when (dopt Opt_D_dump_hi_diffs dflags)
256 (printDump (text "INTERFACE UNCHANGED"))
257 dumpIfSet_dyn dflags Opt_D_dump_hi
258 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
260 (new_iface, Just sdoc_diffs)
261 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
263 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
265 -- Write the interface file
266 when (ghci_mode /= Interactive)
267 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
272 myParseModule dflags src_filename
273 = do -------------------------- Parser ----------------
274 showPass dflags "Parser"
277 buf <- hGetStringBuffer True{-expand tabs-} src_filename
279 let glaexts | dopt Opt_GlasgowExts dflags = 1#
282 case parse buf PState{ bol = 0#, atbol = 1#,
283 context = [], glasgow_exts = glaexts,
284 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
286 PFailed err -> do { hPutStrLn stderr (showSDoc err);
289 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
291 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
293 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
294 (ppSourceStats False rdr_module) ;
296 return (Just rdr_module)
300 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
301 foreign_stuff env_tc stg_binds oa_tidy_binds
302 hit pit -- these last two for mapping ModNames to Modules
304 = do (ibinds,itbl_env)
305 <- stgBindsToInterpSyn dflags (map fst stg_binds)
306 local_tycons local_classes
307 return (Nothing, Nothing, Just (ibinds,itbl_env))
310 = do -------------------------- Code generation -------------------------------
312 abstractC <- codeGen dflags this_mod imported_modules
313 cost_centre_info fe_binders
314 local_tycons stg_binds
316 -------------------------- Code output -------------------------------
317 -- _scc_ "CodeOutput"
318 (maybe_stub_h_name, maybe_stub_c_name)
319 <- codeOutput dflags this_mod local_tycons
320 oa_tidy_binds stg_binds
321 c_code h_code abstractC
323 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
325 local_tycons = typeEnvTyCons env_tc
326 local_classes = typeEnvClasses env_tc
327 imported_modules = map mod_name_to_Module imported_module_names
328 (fe_binders,h_code,c_code) = foreign_stuff
330 mod_name_to_Module :: ModuleName -> Module
331 mod_name_to_Module nm
332 = let str_mi = case lookupModuleEnvByName hit nm of
334 Nothing -> case lookupModuleEnvByName pit nm of
338 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
342 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
343 = do -------------------------- Desugaring ----------------
344 showPass dflags "DeSugar"
346 (desugared, rules, h_code, c_code, fe_binders)
347 <- deSugar dflags pcs hst this_mod print_unqual tc_result
349 -------------------------- Main Core-language transformations ----------------
351 (simplified, orphan_rules)
352 <- core2core dflags pcs hst is_exported desugared rules
354 -- Do the final tidy-up
355 showPass dflags "TidyCore"
356 (tidy_binds, tidy_orphan_rules)
357 <- tidyCorePgm dflags this_mod simplified orphan_rules
359 return (tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
362 myCoreToStg dflags this_mod tidy_binds
364 st_uniqs <- mkSplitUniqSupply 'g'
365 let occ_anal_tidy_binds = occurAnalyseBinds tidy_binds
367 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
368 -- TEMP: the above call zaps some space usage allocated by the
369 -- simplifier, which for reasons I don't understand, persists
370 -- thoroughout code generation
373 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
375 showPass dflags "Stg2Stg"
377 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
378 let final_ids = collectFinalStgBinders (map fst stg_binds2)
380 return (stg_binds2, occ_anal_tidy_binds, cost_centre_info, final_ids)
384 %************************************************************************
386 \subsection{Compiling an expression}
388 %************************************************************************
392 hscExpr dflags hst hit pcs this_module expr
393 = panic "hscExpr: non-interactive build"
394 hscTypeExpr dflags hst hit pcs0 this_module expr
395 = panic "hscTypeExpr: non-interactive build"
402 -> PersistentCompilerState -- IN: persistent compiler state
403 -> Module -- Context for compiling
404 -> String -- The expression
405 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
407 hscExpr dflags hst hit pcs0 this_module expr
409 -- parse, rename & typecheck the expression
410 (pcs1, maybe_tc_result)
411 <- hscExprFrontEnd dflags hst hit pcs0 this_module expr;
413 case maybe_tc_result of {
414 Nothing -> return (pcs1, Nothing);
415 Just (print_unqual, tc_expr, ty) -> do {
417 -- if it isn't an IO-typed expression,
418 -- wrap "print" around it & recompile...
419 let { is_IO_type = case splitTyConApp_maybe ty of {
420 Just (tycon, _) -> getUnique tycon == ioTyConKey;
425 then hscExpr dflags hst hit pcs1 this_module
426 ("print (" ++ expr ++ ")")
430 ds_expr <- deSugarExpr dflags pcs1 hst this_module
431 print_unqual tc_expr;
434 simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
437 stg_expr <- coreToStgExpr dflags simpl_expr;
439 -- ToDo: need to do StgVarInfo? or SRTs?
441 -- Convert to InterpSyn
442 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
444 return (pcs1, Just unlinked_iexpr);
451 -> PersistentCompilerState -- IN: persistent compiler state
452 -> Module -- Context for compiling
453 -> String -- The expression
454 -> IO ( PersistentCompilerState,
455 Maybe (PrintUnqualified,TypecheckedHsExpr,Type)
457 hscExprFrontEnd dflags hst hit pcs0 this_module expr
459 maybe_parsed <- hscParseExpr dflags expr;
461 Nothing -> return (pcs0, Nothing)
462 Just parsed_expr -> do {
465 (pcs1, maybe_renamed_expr) <-
466 renameExpr dflags hit hst pcs0 this_module parsed_expr;
467 case maybe_renamed_expr of
468 Nothing -> return (pcs1, Nothing)
469 Just (print_unqual, rn_expr) -> do {
473 <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
474 case maybe_tc_return of
475 Nothing -> return (pcs1, Nothing)
476 Just (pcs2, tc_expr, ty) ->
477 return (pcs2, Just (print_unqual, tc_expr, ty))
484 -> PersistentCompilerState -- IN: persistent compiler state
485 -> Module -- Context for compiling
486 -> String -- The expression
487 -> IO (PersistentCompilerState, Maybe (PrintUnqualified, Type))
488 hscTypeExpr dflags hst hit pcs0 this_module expr
489 = do (pcs1, maybe_tc_result)
490 <- hscExprFrontEnd dflags hst hit pcs0 this_module expr
491 case maybe_tc_result of
492 Nothing -> return (pcs1, Nothing)
493 Just (print_unqual,_,ty) -> return (pcs1, Just (print_unqual,ty))
495 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
496 hscParseExpr dflags str
497 = do -------------------------- Parser ----------------
498 showPass dflags "Parser"
501 buf <- stringToStringBuffer ("__expr " ++ str)
503 -- glaexts is True for now (because of the daft __expr at the front
506 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
509 case parse buf PState{ bol = 0#, atbol = 1#,
510 context = [], glasgow_exts = glaexts,
511 loc = mkSrcLoc SLIT("<no file>") 0 } of {
513 PFailed err -> do { freeStringBuffer buf;
514 hPutStrLn stderr (showSDoc err);
517 POk _ (PExpr rdr_expr) -> do {
519 --ToDo: can't free the string buffer until we've finished this
520 -- compilation sweep and all the identifiers have gone away.
521 --freeStringBuffer buf;
522 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
523 return (Just rdr_expr)
528 %************************************************************************
530 \subsection{Initial persistent state}
532 %************************************************************************
535 initPersistentCompilerState :: IO PersistentCompilerState
536 initPersistentCompilerState
537 = do prs <- initPersistentRenamerState
539 PCS { pcs_PIT = emptyIfaceTable,
540 pcs_PTE = wiredInThingEnv,
541 pcs_insts = emptyInstEnv,
542 pcs_rules = emptyRuleBase,
547 initPersistentRenamerState :: IO PersistentRenamerState
548 = do ns <- mkSplitUniqSupply 'r'
550 PRS { prsOrig = Orig { origNames = initOrigNames,
551 origIParam = emptyFM },
552 prsDecls = (emptyNameEnv, 0),
553 prsInsts = (emptyBag, 0),
554 prsRules = (emptyBag, 0),
559 initOrigNames :: FiniteMap (ModuleName,OccName) Name
561 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
563 grab names = foldl add emptyFM names
565 = addToFM env (moduleName (nameModule name), nameOccName name) name
568 initRules :: PackageRuleBase
569 initRules = emptyRuleBase
571 foldl add emptyVarEnv builtinRules
574 = extendRuleBase env name rule