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 Rename ( renameExpr )
18 import Unique ( Uniquable(..) )
19 import Type ( Type, splitTyConApp_maybe )
20 import PrelNames ( ioTyConKey )
21 import ByteCodeGen ( byteCodeGen )
26 import StringBuffer ( hGetStringBuffer,
27 stringToStringBuffer, freeStringBuffer )
29 import Lex ( PState(..), ParseResult(..) )
30 import SrcLoc ( mkSrcLoc )
31 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
32 import Rules ( emptyRuleBase )
33 import PrelInfo ( wiredInThingEnv, wiredInThings )
34 import PrelNames ( knownKeyNames )
35 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
36 writeIface, pprIface )
38 import InstEnv ( emptyInstEnv )
41 import CoreUtils ( coreBindsSize )
42 import CoreTidy ( tidyCorePgm )
44 import CoreToStg ( coreToStg )
45 import SimplStg ( stg2stg )
46 import CodeGen ( codeGen )
47 import CodeOutput ( codeOutput )
49 import Module ( ModuleName, moduleName, mkHomeModule )
51 import ErrUtils ( dumpIfSet_dyn, showPass )
52 import Util ( unJust )
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 NameSupply(..), PackageRuleBase, HomeIfaceTable,
64 typeEnvClasses, typeEnvTyCons, emptyIfaceTable )
65 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
66 import OccName ( OccName )
67 import Name ( Name, nameModule, nameOccName, getName, isGlobalName,
69 import Module ( Module, lookupModuleEnvByName )
72 import Maybe ( isJust )
77 %************************************************************************
79 \subsection{The main compiler pipeline}
81 %************************************************************************
86 = HscFail PersistentCompilerState -- updated PCS
87 -- concluded that it wasn't necessary
88 | HscNoRecomp PersistentCompilerState -- updated PCS
89 ModDetails -- new details (HomeSymbolTable additions)
90 ModIface -- new iface (if any compilation was done)
92 | HscRecomp PersistentCompilerState -- updated PCS
93 ModDetails -- new details (HomeSymbolTable additions)
94 ModIface -- new iface (if any compilation was done)
95 (Maybe String) -- generated stub_h filename (in /tmp)
96 (Maybe String) -- generated stub_c filename (in /tmp)
97 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
100 -- no errors or warnings; the individual passes
101 -- (parse/rename/typecheck) print messages themselves
106 -> Bool -- source unchanged?
107 -> ModuleLocation -- location info
108 -> Maybe ModIface -- old interface, if available
109 -> HomeSymbolTable -- for home module ModDetails
111 -> PersistentCompilerState -- IN: persistent compiler state
114 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
116 showPass dflags ("Checking old interface for hs = "
117 ++ show (ml_hs_file location)
118 ++ ", hspp = " ++ show (ml_hspp_file location));
120 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
121 <- checkOldIface ghci_mode dflags hit hst pcs
122 (unJust "hscMain" (ml_hi_file location))
123 source_unchanged maybe_old_iface;
126 return (HscFail pcs_ch)
129 let no_old_iface = not (isJust maybe_checked_iface)
130 what_next | recomp_reqd || no_old_iface = hscRecomp
131 | otherwise = hscNoRecomp
133 what_next ghci_mode dflags location maybe_checked_iface
138 -- we definitely expect to have the old interface available
139 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
140 | ghci_mode == OneShot
142 hPutStrLn stderr "compilation IS NOT required";
143 let { bomb = panic "hscNoRecomp:OneShot" };
144 return (HscNoRecomp pcs_ch bomb bomb)
148 hPutStrLn stderr "compilation IS NOT required";
151 (pcs_cl, closure_errs, cl_hs_decls)
152 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
154 return (HscFail pcs_cl)
158 maybe_tc_result <- typecheckModule dflags pcs_cl hst
159 old_iface alwaysQualify cl_hs_decls
160 False{-don't check for Main.main-};
161 case maybe_tc_result of {
162 Nothing -> return (HscFail pcs_cl);
163 Just (pcs_tc, tc_result) -> do {
165 let env_tc = tc_env tc_result
166 local_rules = tc_rules tc_result
168 -- create a new details from the closed, typechecked, old iface
169 let new_details = mkModDetailsFromIface env_tc local_rules
171 return (HscNoRecomp pcs_tc new_details old_iface)
175 hscRecomp ghci_mode dflags location maybe_checked_iface hst hit pcs_ch
177 ; when (verbosity dflags >= 1) $
178 hPutStrLn stderr "compilation IS required";
180 -- what target are we shooting for?
181 ; let toInterp = dopt_HscLang dflags == HscInterpreted
186 ; maybe_parsed <- myParseModule dflags
187 (unJust "hscRecomp:hspp" (ml_hspp_file location))
188 ; case maybe_parsed of {
189 Nothing -> return (HscFail pcs_ch);
190 Just rdr_module -> do {
191 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
196 ; (pcs_rn, maybe_rn_result)
198 renameModule dflags hit hst pcs_ch this_mod rdr_module
199 ; case maybe_rn_result of {
200 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
201 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
203 -- In interactive mode, we don't want to discard any top-level entities at
204 -- all (eg. do not inline them away during simplification), and retain them
205 -- all in the TypeEnv so they are available from the command line.
207 -- isGlobalName separates the user-defined top-level names from those
208 -- introduced by the type checker.
209 ; let dont_discard | ghci_mode == Interactive = isGlobalName
210 | otherwise = is_exported
216 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
217 print_unqualified rn_hs_decls
218 True{-check for Main.main if necessary-}
219 ; case maybe_tc_result of {
220 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
221 Just (pcs_tc, tc_result) -> do {
223 ; let env_tc = tc_env tc_result
228 ; (ds_binds, ds_rules, foreign_stuff)
230 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
233 -- SIMPLIFY, TIDY-CORE
235 -- We grab the the unfoldings at this point.
236 ; (pcs_simpl, tidy_binds, orphan_rules)
237 <- simplThenTidy dflags pcs_tc hst this_mod dont_discard ds_binds ds_rules
240 -- BUILD THE NEW ModDetails AND ModIface
242 ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
243 ; final_iface <- _scc_ "MkFinalIface"
244 mkFinalIface ghci_mode dflags location
245 maybe_checked_iface new_iface new_details
248 -- CONVERT TO STG and COMPLETE CODE GENERATION
250 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
251 <- restOfCodeGeneration dflags toInterp this_mod
252 (map ideclName (hsModuleImports rdr_module))
253 foreign_stuff env_tc tidy_binds
254 hit (pcs_PIT pcs_simpl)
256 -- and the answer is ...
257 ; return (HscRecomp pcs_simpl new_details final_iface
258 maybe_stub_h_filename maybe_stub_c_filename
264 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
265 = case completeIface maybe_old_iface new_iface new_details of
266 (new_iface, Nothing) -- no change in the interfacfe
267 -> do when (dopt Opt_D_dump_hi_diffs dflags)
268 (printDump (text "INTERFACE UNCHANGED"))
269 dumpIfSet_dyn dflags Opt_D_dump_hi
270 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
272 (new_iface, Just sdoc_diffs)
273 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
275 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
277 -- Write the interface file
278 when (ghci_mode /= Interactive)
279 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
284 myParseModule dflags src_filename
285 = do -------------------------- Parser ----------------
286 showPass dflags "Parser"
289 buf <- hGetStringBuffer True{-expand tabs-} src_filename
291 let glaexts | dopt Opt_GlasgowExts dflags = 1#
294 case parseModule buf PState{ bol = 0#, atbol = 1#,
295 context = [], glasgow_exts = glaexts,
296 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
298 PFailed err -> do { hPutStrLn stderr (showSDoc err);
299 freeStringBuffer buf;
302 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
304 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
306 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
307 (ppSourceStats False rdr_module) ;
309 return (Just rdr_module)
310 -- ToDo: free the string buffer later.
314 simplThenTidy dflags pcs hst this_mod dont_discard binds rules
315 = do -- Do main Core-language transformations ---------
317 (simplified, orphan_rules)
318 <- core2core dflags pcs hst dont_discard binds rules
320 -- Do saturation and convert to A-normal form
321 -- NOTE: subsequent passes may not transform the syntax, only annotate it
322 saturated <- coreSatPgm dflags simplified
324 -- Do the final tidy-up
325 (pcs', tidy_binds, tidy_orphan_rules)
326 <- tidyCorePgm dflags this_mod pcs saturated orphan_rules
328 return (pcs', tidy_binds, tidy_orphan_rules)
331 restOfCodeGeneration dflags toInterp this_mod imported_module_names
332 foreign_stuff env_tc tidy_binds
333 hit pit -- these last two for mapping ModNames to Modules
336 <- byteCodeGen dflags tidy_binds local_tycons local_classes
337 return (Nothing, Nothing, Just (bcos,itbl_env))
341 -------------------------- Convert to STG -------------------------------
342 (stg_binds, cost_centre_info)
344 myCoreToStg dflags this_mod tidy_binds env_tc
346 -------------------------- Code generation ------------------------------
347 abstractC <- _scc_ "CodeGen"
348 codeGen dflags this_mod imported_modules
349 cost_centre_info fe_binders
350 local_tycons stg_binds
352 -------------------------- Code output -------------------------------
353 (maybe_stub_h_name, maybe_stub_c_name)
354 <- codeOutput dflags this_mod local_tycons
356 c_code h_code abstractC
358 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
360 local_tycons = typeEnvTyCons env_tc
361 local_classes = typeEnvClasses env_tc
362 imported_modules = map mod_name_to_Module imported_module_names
363 (h_code,c_code,fe_binders) = foreign_stuff
365 mod_name_to_Module :: ModuleName -> Module
366 mod_name_to_Module nm
367 = let str_mi = case lookupModuleEnvByName hit nm of
369 Nothing -> case lookupModuleEnvByName pit nm of
373 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
377 myCoreToStg dflags this_mod tidy_binds env_tc
379 () <- coreBindsSize tidy_binds `seq` return ()
380 -- TEMP: the above call zaps some space usage allocated by the
381 -- simplifier, which for reasons I don't understand, persists
382 -- thoroughout code generation
384 --let bcos = byteCodeGen dflags tidy_binds local_tycons local_classes
387 stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
389 (stg_binds2, cost_centre_info)
390 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
392 return (stg_binds2, cost_centre_info)
394 local_tycons = typeEnvTyCons env_tc
395 local_classes = typeEnvClasses env_tc
399 %************************************************************************
401 \subsection{Compiling an expression}
403 %************************************************************************
409 -> Bool -- True <=> wrap in 'print' to get a result of IO type
412 -> PersistentCompilerState -- IN: persistent compiler state
413 -> Module -- Context for compiling
414 -> String -- The expression
415 -> IO ( PersistentCompilerState,
416 Maybe (UnlinkedBCOExpr, PrintUnqualified, Type) )
418 hscExpr dflags wrap_io hst hit pcs0 this_module expr
420 maybe_parsed <- hscParseExpr dflags expr;
422 Nothing -> return (pcs0, Nothing)
423 Just parsed_expr -> do {
426 (pcs1, maybe_renamed_expr) <-
427 renameExpr dflags hit hst pcs0 this_module parsed_expr;
428 case maybe_renamed_expr of
429 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing)
430 Just (print_unqual, rn_expr) -> do {
434 <- typecheckExpr dflags wrap_io pcs1 hst print_unqual this_module rn_expr;
435 case maybe_tc_return of {
436 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing);
437 Just (pcs2, tc_expr, ty) -> do
440 ds_expr <- deSugarExpr dflags pcs2 hst this_module
441 print_unqual tc_expr;
444 simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
447 sat_expr <- coreSatExpr dflags simpl_expr;
449 -- ToDo: need to do SRTs?
452 bcos <- coreExprToBCOs dflags sat_expr
454 return (pcs2, Just (bcos, print_unqual, ty));
457 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
458 hscParseExpr dflags str
459 = do -------------------------- Parser ----------------
460 showPass dflags "Parser"
463 buf <- stringToStringBuffer str
465 let glaexts | dopt Opt_GlasgowExts dflags = 1#
468 case parseExpr buf PState{ bol = 0#, atbol = 1#,
469 context = [], glasgow_exts = glaexts,
470 loc = mkSrcLoc SLIT("<no file>") 0 } of {
472 PFailed err -> do { hPutStrLn stderr (showSDoc err);
473 -- Not yet implemented in <4.11 freeStringBuffer buf;
476 POk _ rdr_expr -> do {
478 --ToDo: can't free the string buffer until we've finished this
479 -- compilation sweep and all the identifiers have gone away.
480 --freeStringBuffer buf;
481 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
482 return (Just rdr_expr)
487 %************************************************************************
489 \subsection{Initial persistent state}
491 %************************************************************************
494 initPersistentCompilerState :: IO PersistentCompilerState
495 initPersistentCompilerState
496 = do prs <- initPersistentRenamerState
498 PCS { pcs_PIT = emptyIfaceTable,
499 pcs_PTE = wiredInThingEnv,
500 pcs_insts = emptyInstEnv,
501 pcs_rules = emptyRuleBase,
506 initPersistentRenamerState :: IO PersistentRenamerState
507 = do us <- mkSplitUniqSupply 'r'
509 PRS { prsOrig = NameSupply { nsUniqs = us,
510 nsNames = initOrigNames,
512 prsDecls = (emptyNameEnv, 0),
513 prsInsts = (emptyBag, 0),
514 prsRules = (emptyBag, 0),
519 initOrigNames :: FiniteMap (ModuleName,OccName) Name
521 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
523 grab names = foldl add emptyFM names
525 = addToFM env (moduleName (nameModule name), nameOccName name) name
528 initRules :: PackageRuleBase
529 initRules = emptyRuleBase
531 foldl add emptyVarEnv builtinRules
534 = extendRuleBase env name rule