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,
11 initPersistentCompilerState ) where
13 #include "HsVersions.h"
16 import RdrHsSyn ( RdrNameHsExpr )
17 import CoreToStg ( coreToStgExpr )
18 import StringBuffer ( stringToStringBuffer, freeStringBuffer )
23 import StringBuffer ( hGetStringBuffer )
25 import Lex ( PState(..), ParseResult(..) )
26 import SrcLoc ( mkSrcLoc )
28 import Rules ( emptyRuleBase )
29 import PrelInfo ( wiredInThingEnv, wiredInThings )
30 import PrelNames ( knownKeyNames )
31 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
32 writeIface, pprIface )
36 import InstEnv ( emptyInstEnv )
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, moduleName, mkHomeModule )
49 import ErrUtils ( dumpIfSet_dyn, showPass )
50 import Util ( unJust )
51 import Unique ( Uniquable(..) )
52 import PrelNames ( ioTyConKey )
53 import UniqSupply ( mkSplitUniqSupply )
55 import Bag ( emptyBag )
58 import CmStaticInfo ( GhciMode(..) )
59 import HscStats ( ppSourceStats )
60 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
61 PersistentRenamerState(..), ModuleLocation(..),
63 OrigNameEnv(..), PackageRuleBase, HomeIfaceTable,
64 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
65 import Type ( splitTyConApp_maybe )
66 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
67 import OccName ( OccName )
68 import Name ( Name, nameModule, nameOccName, getName )
69 import Name ( emptyNameEnv )
70 import Module ( Module, lookupModuleEnvByName )
73 import Maybe ( isJust )
74 import IO ( hPutStrLn, stderr )
78 %************************************************************************
80 \subsection{The main compiler pipeline}
82 %************************************************************************
87 = HscFail PersistentCompilerState -- updated PCS
88 -- concluded that it wasn't necessary
89 | HscNoRecomp PersistentCompilerState -- updated PCS
90 ModDetails -- new details (HomeSymbolTable additions)
91 ModIface -- new iface (if any compilation was done)
93 | HscRecomp PersistentCompilerState -- updated PCS
94 ModDetails -- new details (HomeSymbolTable additions)
95 ModIface -- new iface (if any compilation was done)
96 (Maybe String) -- generated stub_h filename (in /tmp)
97 (Maybe String) -- generated stub_c filename (in /tmp)
98 (Maybe ([UnlinkedIBind],ItblEnv)) -- interpreted code, if any
101 -- no errors or warnings; the individual passes
102 -- (parse/rename/typecheck) print messages themselves
107 -> Bool -- source unchanged?
108 -> ModuleLocation -- location info
109 -> Maybe ModIface -- old interface, if available
110 -> HomeSymbolTable -- for home module ModDetails
112 -> PersistentCompilerState -- IN: persistent compiler state
115 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
117 showPass dflags ("Checking old interface for hs = "
118 ++ show (ml_hs_file location)
119 ++ ", hspp = " ++ show (ml_hspp_file location));
121 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
122 <- checkOldIface dflags hit hst pcs
123 (unJust "hscMain" (ml_hi_file location))
124 source_unchanged maybe_old_iface;
127 return (HscFail pcs_ch)
130 let no_old_iface = not (isJust maybe_checked_iface)
131 what_next | recomp_reqd || no_old_iface = hscRecomp
132 | otherwise = hscNoRecomp
134 what_next ghci_mode dflags location maybe_checked_iface
139 -- we definitely expect to have the old interface available
140 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
141 | ghci_mode == OneShot
142 = let bomb = panic "hscNoRecomp:OneShot"
143 in return (HscNoRecomp pcs_ch bomb bomb)
146 hPutStrLn stderr "compilation IS NOT required";
149 (pcs_cl, closure_errs, cl_hs_decls)
150 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
152 return (HscFail pcs_cl)
156 maybe_tc_result <- typecheckModule dflags pcs_cl hst
157 old_iface alwaysQualify cl_hs_decls;
158 case maybe_tc_result of {
159 Nothing -> return (HscFail pcs_cl);
160 Just (pcs_tc, tc_result) -> do {
162 let env_tc = tc_env tc_result
163 local_insts = tc_insts tc_result
164 local_rules = tc_rules tc_result
166 -- create a new details from the closed, typechecked, old iface
167 let new_details = mkModDetailsFromIface env_tc local_insts local_rules
169 return (HscNoRecomp pcs_tc new_details old_iface)
173 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
175 ; when (verbosity dflags >= 1) $
176 hPutStrLn stderr "compilation IS required";
178 -- what target are we shooting for?
179 ; let toInterp = dopt_HscLang dflags == HscInterpreted
184 ; maybe_parsed <- myParseModule dflags
185 (unJust "hscRecomp:hspp" (ml_hspp_file location))
186 ; case maybe_parsed of {
187 Nothing -> return (HscFail pcs_ch);
188 Just rdr_module -> do {
189 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
194 ; (pcs_rn, maybe_rn_result)
195 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
196 ; case maybe_rn_result of {
197 Nothing -> return (HscFail pcs_rn);
198 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
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 (pcs_simpl, tidy_binds, orphan_rules, foreign_stuff) = simpl_result
223 ; (stg_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 tidy_binds
242 hit (pcs_PIT pcs_simpl)
244 -- and the answer is ...
245 ; return (HscRecomp pcs_simpl 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 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
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 ----------------
345 (desugared, rules, h_code, c_code, fe_binders)
346 <- deSugar dflags pcs hst this_mod print_unqual tc_result
348 -------------------------- Main Core-language transformations ----------------
350 (simplified, orphan_rules)
351 <- core2core dflags pcs hst is_exported desugared rules
353 -- Do the final tidy-up
354 (pcs', tidy_binds, tidy_orphan_rules)
355 <- tidyCorePgm dflags this_mod pcs simplified orphan_rules
357 return (pcs', tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
360 myCoreToStg dflags this_mod tidy_binds
362 () <- coreBindsSize occ_anal_tidy_binds `seq` return ()
363 -- TEMP: the above call zaps some space usage allocated by the
364 -- simplifier, which for reasons I don't understand, persists
365 -- thoroughout code generation
368 stg_binds <- topCoreBindsToStg dflags occ_anal_tidy_binds
371 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod st_uniqs stg_binds
372 let final_ids = collectFinalStgBinders (map fst stg_binds2)
374 return (stg_binds2, cost_centre_info, final_ids)
378 %************************************************************************
380 \subsection{Compiling an expression}
382 %************************************************************************
386 hscExpr dflags hst hit pcs this_module expr
387 = panic "hscExpr: non-interactive build"
388 hscTypeExpr dflags hst hit pcs0 this_module expr
389 = panic "hscTypeExpr: non-interactive build"
396 -> PersistentCompilerState -- IN: persistent compiler state
397 -> Module -- Context for compiling
398 -> String -- The expression
399 -> IO ( PersistentCompilerState, Maybe UnlinkedIExpr )
401 hscExpr dflags hst hit pcs0 this_module expr
403 -- parse, rename & typecheck the expression
404 (pcs1, maybe_tc_result)
405 <- hscExprFrontEnd dflags hst hit pcs0 this_module expr;
407 case maybe_tc_result of {
408 Nothing -> return (pcs1, Nothing);
409 Just (print_unqual, tc_expr, ty) -> do {
411 -- if it isn't an IO-typed expression,
412 -- wrap "print" around it & recompile...
413 let { is_IO_type = case splitTyConApp_maybe ty of {
414 Just (tycon, _) -> getUnique tycon == ioTyConKey;
419 then hscExpr dflags hst hit pcs1 this_module
420 ("print (" ++ expr ++ ")")
424 ds_expr <- deSugarExpr dflags pcs1 hst this_module
425 print_unqual tc_expr;
428 simpl_expr <- simplifyExpr dflags pcs1 hst ds_expr;
431 stg_expr <- coreToStgExpr dflags simpl_expr;
433 -- ToDo: need to do StgVarInfo? or SRTs?
435 -- Convert to InterpSyn
436 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
438 return (pcs1, Just unlinked_iexpr);
445 -> PersistentCompilerState -- IN: persistent compiler state
446 -> Module -- Context for compiling
447 -> String -- The expression
448 -> IO ( PersistentCompilerState,
449 Maybe (PrintUnqualified,TypecheckedHsExpr,Type)
451 hscExprFrontEnd dflags hst hit pcs0 this_module expr
453 maybe_parsed <- hscParseExpr dflags expr;
455 Nothing -> return (pcs0, Nothing)
456 Just parsed_expr -> do {
459 (pcs1, maybe_renamed_expr) <-
460 renameExpr dflags hit hst pcs0 this_module parsed_expr;
461 case maybe_renamed_expr of
462 Nothing -> return (pcs1, Nothing)
463 Just (print_unqual, rn_expr) -> do {
467 <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
468 case maybe_tc_return of
469 Nothing -> return (pcs1, Nothing)
470 Just (pcs2, tc_expr, ty) ->
471 return (pcs2, Just (print_unqual, tc_expr, ty))
478 -> PersistentCompilerState -- IN: persistent compiler state
479 -> Module -- Context for compiling
480 -> String -- The expression
481 -> IO (PersistentCompilerState, Maybe (PrintUnqualified, Type))
482 hscTypeExpr dflags hst hit pcs0 this_module expr
483 = do (pcs1, maybe_tc_result)
484 <- hscExprFrontEnd dflags hst hit pcs0 this_module expr
485 case maybe_tc_result of
486 Nothing -> return (pcs1, Nothing)
487 Just (print_unqual,_,ty) -> return (pcs1, Just (print_unqual,ty))
489 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
490 hscParseExpr dflags str
491 = do -------------------------- Parser ----------------
492 showPass dflags "Parser"
495 buf <- stringToStringBuffer ("__expr " ++ str)
497 -- glaexts is True for now (because of the daft __expr at the front
500 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
503 case parse buf PState{ bol = 0#, atbol = 1#,
504 context = [], glasgow_exts = glaexts,
505 loc = mkSrcLoc SLIT("<no file>") 0 } of {
507 PFailed err -> do { freeStringBuffer buf;
508 hPutStrLn stderr (showSDoc err);
511 POk _ (PExpr rdr_expr) -> do {
513 --ToDo: can't free the string buffer until we've finished this
514 -- compilation sweep and all the identifiers have gone away.
515 --freeStringBuffer buf;
516 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
517 return (Just rdr_expr)
522 %************************************************************************
524 \subsection{Initial persistent state}
526 %************************************************************************
529 initPersistentCompilerState :: IO PersistentCompilerState
530 initPersistentCompilerState
531 = do prs <- initPersistentRenamerState
533 PCS { pcs_PIT = emptyIfaceTable,
534 pcs_PTE = wiredInThingEnv,
535 pcs_insts = emptyInstEnv,
536 pcs_rules = emptyRuleBase,
541 initPersistentRenamerState :: IO PersistentRenamerState
542 = do ns <- mkSplitUniqSupply 'r'
544 PRS { prsOrig = Orig { origNames = initOrigNames,
545 origIParam = emptyFM },
546 prsDecls = (emptyNameEnv, 0),
547 prsInsts = (emptyBag, 0),
548 prsRules = (emptyBag, 0),
553 initOrigNames :: FiniteMap (ModuleName,OccName) Name
555 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
557 grab names = foldl add emptyFM names
559 = addToFM env (moduleName (nameModule name), nameOccName name) name
562 initRules :: PackageRuleBase
563 initRules = emptyRuleBase
565 foldl add emptyVarEnv builtinRules
568 = extendRuleBase env name rule