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 StringBuffer ( stringToStringBuffer, freeStringBuffer )
18 import Unique ( Uniquable(..) )
19 import Type ( splitTyConApp_maybe )
20 import PrelNames ( ioTyConKey )
21 import ByteCodeGen ( byteCodeGen )
26 import StringBuffer ( hGetStringBuffer )
28 import Lex ( PState(..), ParseResult(..) )
29 import SrcLoc ( mkSrcLoc )
30 import Rename ( checkOldIface, renameModule, renameExpr, closeIfaceDecls )
31 import Rules ( emptyRuleBase )
32 import PrelInfo ( wiredInThingEnv, wiredInThings )
33 import PrelNames ( knownKeyNames )
34 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
35 writeIface, pprIface )
38 import InstEnv ( emptyInstEnv )
41 import CoreSyn ( bindersOfBinds )
42 import CoreUtils ( coreBindsSize )
43 import CoreTidy ( tidyCorePgm )
45 import CoreToStg ( coreToStg, coreExprToStg )
46 import SimplStg ( stg2stg )
47 import CodeGen ( codeGen )
48 import CodeOutput ( codeOutput )
50 import Module ( ModuleName, moduleName, mkHomeModule )
52 import ErrUtils ( dumpIfSet_dyn, showPass )
53 import Util ( unJust )
54 import UniqSupply ( mkSplitUniqSupply )
56 import Bag ( emptyBag )
59 import CmStaticInfo ( GhciMode(..) )
60 import HscStats ( ppSourceStats )
61 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
62 PersistentRenamerState(..), ModuleLocation(..),
64 OrigNameEnv(..), PackageRuleBase, HomeIfaceTable,
65 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
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 )
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 ghci_mode 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
143 hPutStrLn stderr "compilation IS NOT required";
144 let { bomb = panic "hscNoRecomp:OneShot" };
145 return (HscNoRecomp pcs_ch bomb bomb)
149 hPutStr stderr "compilation IS NOT required";
150 when (verbosity dflags /= 1) $ hPutStrLn stderr "";
153 (pcs_cl, closure_errs, cl_hs_decls)
154 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
156 return (HscFail pcs_cl)
160 maybe_tc_result <- typecheckModule dflags pcs_cl hst
161 old_iface alwaysQualify cl_hs_decls;
162 case maybe_tc_result of {
163 Nothing -> return (HscFail pcs_cl);
164 Just (pcs_tc, tc_result) -> do {
166 let env_tc = tc_env tc_result
167 local_rules = tc_rules tc_result
169 -- create a new details from the closed, typechecked, old iface
170 let new_details = mkModDetailsFromIface env_tc local_rules
172 return (HscNoRecomp pcs_tc new_details old_iface)
176 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
178 ; when (verbosity dflags >= 1) $
179 hPutStr stderr "compilation IS required";
180 -- mode -v1 tries to keep everything on one line
181 when (verbosity dflags > 1) $
184 -- what target are we shooting for?
185 ; let toInterp = dopt_HscLang dflags == HscInterpreted
190 ; maybe_parsed <- myParseModule dflags
191 (unJust "hscRecomp:hspp" (ml_hspp_file location))
192 ; case maybe_parsed of {
193 Nothing -> return (HscFail pcs_ch);
194 Just rdr_module -> do {
195 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
200 ; (pcs_rn, maybe_rn_result)
201 <- renameModule dflags hit hst pcs_ch this_mod rdr_module
202 ; case maybe_rn_result of {
203 Nothing -> return (HscFail pcs_rn);
204 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
209 ; maybe_tc_result <- typecheckModule dflags pcs_rn hst new_iface
210 print_unqualified rn_hs_decls
211 ; case maybe_tc_result of {
212 Nothing -> return (HscFail pcs_rn);
213 Just (pcs_tc, tc_result) -> do {
215 ; let env_tc = tc_env tc_result
218 -- DESUGAR, SIMPLIFY, TIDY-CORE
220 -- We grab the the unfoldings at this point.
221 ; (pcs_simpl, tidy_binds, orphan_rules, foreign_stuff)
222 <- dsThenSimplThenTidy dflags pcs_tc hst this_mod
223 print_unqualified is_exported tc_result
226 -- BUILD THE NEW ModDetails AND ModIface
228 ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
229 ; final_iface <- mkFinalIface ghci_mode dflags location
230 maybe_checked_iface new_iface new_details
235 ; (stg_binds, cost_centre_info)
236 <- myCoreToStg dflags this_mod tidy_binds
240 -- COMPLETE CODE GENERATION
242 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_ibinds)
243 <- restOfCodeGeneration dflags toInterp this_mod
244 (map ideclName (hsModuleImports rdr_module))
245 cost_centre_info foreign_stuff env_tc stg_binds tidy_binds
246 hit (pcs_PIT pcs_simpl)
248 -- and the answer is ...
249 ; return (HscRecomp pcs_simpl new_details final_iface
250 maybe_stub_h_filename maybe_stub_c_filename
256 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
257 = case completeIface maybe_old_iface new_iface new_details of
258 (new_iface, Nothing) -- no change in the interfacfe
259 -> do when (dopt Opt_D_dump_hi_diffs dflags)
260 (printDump (text "INTERFACE UNCHANGED"))
261 dumpIfSet_dyn dflags Opt_D_dump_hi
262 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
264 (new_iface, Just sdoc_diffs)
265 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
267 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
269 -- Write the interface file
270 when (ghci_mode /= Interactive)
271 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
276 myParseModule dflags src_filename
277 = do -------------------------- Parser ----------------
278 showPass dflags "Parser"
281 buf <- hGetStringBuffer True{-expand tabs-} src_filename
283 let glaexts | dopt Opt_GlasgowExts dflags = 1#
286 case parse buf PState{ bol = 0#, atbol = 1#,
287 context = [], glasgow_exts = glaexts,
288 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
290 PFailed err -> do { hPutStrLn stderr (showSDoc err);
293 POk _ (PModule rdr_module@(HsModule mod_name _ _ _ _ _ _)) -> do {
295 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
297 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
298 (ppSourceStats False rdr_module) ;
300 return (Just rdr_module)
304 restOfCodeGeneration dflags toInterp this_mod imported_module_names cost_centre_info
305 foreign_stuff env_tc stg_binds tidy_binds
306 hit pit -- these last two for mapping ModNames to Modules
308 = do (ibinds,itbl_env)
309 <- stgBindsToInterpSyn dflags (map fst stg_binds)
310 local_tycons local_classes
311 return (Nothing, Nothing, Just (ibinds,itbl_env))
314 = do -------------------------- Code generation -------------------------------
316 abstractC <- codeGen dflags this_mod imported_modules
317 cost_centre_info fe_binders
318 local_tycons stg_binds
320 -------------------------- Code output -------------------------------
321 -- _scc_ "CodeOutput"
322 (maybe_stub_h_name, maybe_stub_c_name)
323 <- codeOutput dflags this_mod local_tycons
325 c_code h_code abstractC
327 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
329 local_tycons = typeEnvTyCons env_tc
330 local_classes = typeEnvClasses env_tc
331 imported_modules = map mod_name_to_Module imported_module_names
332 (fe_binders,h_code,c_code) = foreign_stuff
334 mod_name_to_Module :: ModuleName -> Module
335 mod_name_to_Module nm
336 = let str_mi = case lookupModuleEnvByName hit nm of
338 Nothing -> case lookupModuleEnvByName pit nm of
342 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
346 dsThenSimplThenTidy dflags pcs hst this_mod print_unqual is_exported tc_result
347 = do ------------------ Desugaring ---------------------------------
349 (desugared, rules, h_code, c_code, fe_binders)
350 <- deSugar dflags pcs hst this_mod print_unqual tc_result
352 ------------------ Main Core-language transformations ---------
354 (simplified, orphan_rules)
355 <- core2core dflags pcs hst is_exported desugared rules
357 -- Do saturation and convert to A-normal form
358 -- NOTE: future passes cannot transform the syntax, only annotate it
359 saturated <- coreSatPgm dflags simplified
361 -- Do the final tidy-up
362 (pcs', tidy_binds, tidy_orphan_rules)
363 <- tidyCorePgm dflags this_mod pcs saturated orphan_rules
365 return (pcs', tidy_binds, tidy_orphan_rules, (fe_binders,h_code,c_code))
368 myCoreToStg dflags this_mod tidy_binds
370 () <- coreBindsSize tidy_binds `seq` return ()
371 -- TEMP: the above call zaps some space usage allocated by the
372 -- simplifier, which for reasons I don't understand, persists
373 -- thoroughout code generation
375 --let bcos = byteCodeGen tidy_binds
376 --putStrLn (showSDoc (vcat (map ppr bcos)))
379 stg_binds <- coreToStg dflags this_mod tidy_binds
382 (stg_binds2, cost_centre_info) <- stg2stg dflags this_mod stg_binds
384 return (stg_binds2, cost_centre_info)
388 %************************************************************************
390 \subsection{Compiling an expression}
392 %************************************************************************
396 hscExpr dflags hst hit pcs this_module expr
397 = panic "hscExpr: non-interactive build"
398 hscTypeExpr dflags hst hit pcs0 this_module expr
399 = panic "hscTypeExpr: non-interactive build"
406 -> PersistentCompilerState -- IN: persistent compiler state
407 -> Module -- Context for compiling
408 -> String -- The expression
409 -> IO ( PersistentCompilerState,
410 Maybe (UnlinkedIExpr, PrintUnqualified, Type) )
412 hscExpr dflags hst hit pcs0 this_module expr
414 maybe_parsed <- hscParseExpr dflags expr;
416 Nothing -> return (pcs0, Nothing)
417 Just parsed_expr -> do {
420 (pcs1, maybe_renamed_expr) <-
421 renameExpr dflags hit hst pcs0 this_module parsed_expr;
422 case maybe_renamed_expr of
423 Nothing -> return (pcs1, Nothing)
424 Just (print_unqual, rn_expr) -> do {
428 <- typecheckExpr dflags pcs1 hst print_unqual this_module rn_expr;
429 case maybe_tc_return of {
430 Nothing -> return (pcs1, Nothing);
431 Just (pcs2, tc_expr, ty) -> do
433 -- if it isn't an IO-typed expression,
434 -- wrap "print" around it & recompile...
435 let { is_IO_type = case splitTyConApp_maybe ty of {
436 Just (tycon, _) -> getUnique tycon == ioTyConKey;
441 then do (new_pcs, maybe_stuff)
442 <- hscExpr dflags hst hit pcs2 this_module
443 ("print (" ++ expr ++ ")")
445 Nothing -> return (new_pcs, maybe_stuff)
447 return (new_pcs, Just (expr, print_unqual, ty))
451 ds_expr <- deSugarExpr dflags pcs2 hst this_module
452 print_unqual tc_expr;
455 simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
458 sat_expr <- coreSatExpr dflags simpl_expr;
461 let stg_expr = coreExprToStg sat_expr;
463 -- ToDo: need to do SRTs?
465 -- Convert to InterpSyn
466 unlinked_iexpr <- stgExprToInterpSyn dflags stg_expr;
468 return (pcs2, Just (unlinked_iexpr, print_unqual, ty));
471 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
472 hscParseExpr dflags str
473 = do -------------------------- Parser ----------------
474 showPass dflags "Parser"
477 buf <- stringToStringBuffer ("__expr " ++ str)
479 -- glaexts is True for now (because of the daft __expr at the front
482 --let glaexts | dopt Opt_GlasgowExts dflags = 1#
485 case parse buf PState{ bol = 0#, atbol = 1#,
486 context = [], glasgow_exts = glaexts,
487 loc = mkSrcLoc SLIT("<no file>") 0 } of {
489 PFailed err -> do { freeStringBuffer buf;
490 hPutStrLn stderr (showSDoc err);
493 POk _ (PExpr rdr_expr) -> do {
495 --ToDo: can't free the string buffer until we've finished this
496 -- compilation sweep and all the identifiers have gone away.
497 --freeStringBuffer buf;
498 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
499 return (Just rdr_expr)
504 %************************************************************************
506 \subsection{Initial persistent state}
508 %************************************************************************
511 initPersistentCompilerState :: IO PersistentCompilerState
512 initPersistentCompilerState
513 = do prs <- initPersistentRenamerState
515 PCS { pcs_PIT = emptyIfaceTable,
516 pcs_PTE = wiredInThingEnv,
517 pcs_insts = emptyInstEnv,
518 pcs_rules = emptyRuleBase,
523 initPersistentRenamerState :: IO PersistentRenamerState
524 = do ns <- mkSplitUniqSupply 'r'
526 PRS { prsOrig = Orig { origNS = ns,
527 origNames = initOrigNames,
528 origIParam = emptyFM },
529 prsDecls = (emptyNameEnv, 0),
530 prsInsts = (emptyBag, 0),
531 prsRules = (emptyBag, 0)
535 initOrigNames :: FiniteMap (ModuleName,OccName) Name
537 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
539 grab names = foldl add emptyFM names
541 = addToFM env (moduleName (nameModule name), nameOccName name) name
544 initRules :: PackageRuleBase
545 initRules = emptyRuleBase
547 foldl add emptyVarEnv builtinRules
550 = extendRuleBase env name rule