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 ( RdrNameStmt )
17 import Rename ( renameStmt )
18 import ByteCodeGen ( byteCodeGen )
19 import Id ( Id, idName )
20 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
21 import HscTypes ( InteractiveContext(..), TyThing(..) )
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 ( vanillaSyntaxMap, knownKeyNames, iNTERACTIVE )
35 import MkIface ( completeIface, writeIface, pprIface )
38 import InstEnv ( emptyInstEnv )
41 import CoreUtils ( coreBindsSize )
42 import CoreTidy ( tidyCorePgm )
44 import CoreTidy ( tidyCoreExpr )
45 import CoreToStg ( coreToStg )
46 import SimplStg ( stg2stg )
47 import CodeGen ( codeGen )
48 import CodeOutput ( codeOutput )
50 import Module ( ModuleName, moduleName, mkHomeModule,
53 import ErrUtils ( dumpIfSet_dyn, showPass )
54 import Util ( unJust )
55 import UniqSupply ( mkSplitUniqSupply )
57 import Bag ( emptyBag )
60 import CmStaticInfo ( GhciMode(..) )
61 import HscStats ( ppSourceStats )
62 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
63 PersistentRenamerState(..), ModuleLocation(..),
65 NameSupply(..), PackageRuleBase, HomeIfaceTable,
66 typeEnvClasses, typeEnvTyCons, emptyIfaceTable
68 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
69 import OccName ( OccName )
70 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
71 import NameEnv ( emptyNameEnv )
72 import Module ( Module, lookupModuleEnvByName )
75 import Maybe ( isJust )
80 %************************************************************************
82 \subsection{The main compiler pipeline}
84 %************************************************************************
89 = HscFail PersistentCompilerState -- updated PCS
90 -- concluded that it wasn't necessary
91 | HscNoRecomp PersistentCompilerState -- updated PCS
92 ModDetails -- new details (HomeSymbolTable additions)
93 ModIface -- new iface (if any compilation was done)
95 | HscRecomp PersistentCompilerState -- updated PCS
96 ModDetails -- new details (HomeSymbolTable additions)
97 ModIface -- new iface (if any compilation was done)
98 (Maybe String) -- generated stub_h filename (in TMPDIR)
99 (Maybe String) -- generated stub_c filename (in TMPDIR)
100 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
103 -- no errors or warnings; the individual passes
104 -- (parse/rename/typecheck) print messages themselves
110 -> ModuleLocation -- location info
111 -> Bool -- source unchanged?
112 -> Maybe ModIface -- old interface, if available
113 -> HomeSymbolTable -- for home module ModDetails
115 -> PersistentCompilerState -- IN: persistent compiler state
118 hscMain ghci_mode dflags mod location source_unchanged maybe_old_iface hst hit pcs
120 showPass dflags ("Checking old interface for hs = "
121 ++ show (ml_hs_file location)
122 ++ ", hspp = " ++ show (ml_hspp_file location));
124 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
125 <- checkOldIface ghci_mode dflags hit hst pcs
126 (unJust "hscMain" (ml_hi_file location))
127 source_unchanged maybe_old_iface;
130 return (HscFail pcs_ch)
133 let no_old_iface = not (isJust maybe_checked_iface)
134 what_next | recomp_reqd || no_old_iface = hscRecomp
135 | otherwise = hscNoRecomp
137 what_next ghci_mode dflags mod location maybe_checked_iface
142 -- we definitely expect to have the old interface available
143 hscNoRecomp ghci_mode dflags mod location (Just old_iface) hst hit pcs_ch
144 | ghci_mode == OneShot
146 hPutStrLn stderr "compilation IS NOT required";
147 let { bomb = panic "hscNoRecomp:OneShot" };
148 return (HscNoRecomp pcs_ch bomb bomb)
152 when (verbosity dflags >= 1) $
153 hPutStrLn stderr ("Skipping " ++ compMsg mod location);
156 (pcs_cl, closure_errs, cl_hs_decls)
157 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
159 return (HscFail pcs_cl)
164 <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
166 case maybe_tc_result of {
167 Nothing -> return (HscFail pcs_cl);
168 Just (pcs_tc, new_details) ->
170 return (HscNoRecomp pcs_tc new_details old_iface)
173 compMsg mod location =
174 mod_str ++ take (12 - length mod_str) (repeat ' ')
175 ++ " (" ++ unJust "hscRecomp" (ml_hs_file location) ++ ")"
176 where mod_str = moduleUserString mod
179 hscRecomp ghci_mode dflags mod location maybe_checked_iface hst hit pcs_ch
181 ; when (verbosity dflags >= 1) $
182 hPutStrLn stderr ("Compiling " ++ compMsg mod location);
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, print_unqualified, maybe_rn_result)
202 renameModule dflags hit hst pcs_ch this_mod rdr_module
203 ; case maybe_rn_result of {
204 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
205 Just (is_exported, new_iface, rn_hs_decls) -> do {
207 -- In interactive mode, we don't want to discard any top-level entities at
208 -- all (eg. do not inline them away during simplification), and retain them
209 -- all in the TypeEnv so they are available from the command line.
211 -- isGlobalName separates the user-defined top-level names from those
212 -- introduced by the type checker.
213 ; let dont_discard | ghci_mode == Interactive = isGlobalName
214 | otherwise = is_exported
220 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
221 print_unqualified rn_hs_decls
222 ; case maybe_tc_result of {
223 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
224 Just (pcs_tc, tc_result) -> do {
226 ; let env_tc = tc_env tc_result
227 insts_tc = tc_insts tc_result
232 ; (ds_binds, ds_rules, foreign_stuff)
234 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
239 ; (simplified, orphan_rules)
241 core2core dflags pcs_tc hst dont_discard ds_binds ds_rules
246 ; (pcs_simpl, tidy_binds, new_details)
247 <- tidyCorePgm dflags this_mod pcs_tc env_tc insts_tc
248 simplified orphan_rules
251 -- BUILD THE NEW ModDetails AND ModIface
253 ; final_iface <- _scc_ "MkFinalIface"
254 mkFinalIface ghci_mode dflags location
255 maybe_checked_iface new_iface new_details
258 -- CONVERT TO STG and COMPLETE CODE GENERATION
260 -- Do saturation and convert to A-normal form
261 ; saturated <- coreSatPgm dflags tidy_binds
263 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
264 <- restOfCodeGeneration dflags toInterp this_mod
265 (map ideclName (hsModuleImports rdr_module))
266 foreign_stuff env_tc saturated
267 hit (pcs_PIT pcs_simpl)
269 -- and the answer is ...
270 ; return (HscRecomp pcs_simpl new_details final_iface
271 maybe_stub_h_filename maybe_stub_c_filename
277 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
278 = case completeIface maybe_old_iface new_iface new_details of
279 (new_iface, Nothing) -- no change in the interfacfe
280 -> do when (dopt Opt_D_dump_hi_diffs dflags)
281 (printDump (text "INTERFACE UNCHANGED"))
282 dumpIfSet_dyn dflags Opt_D_dump_hi
283 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
285 (new_iface, Just sdoc_diffs)
286 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
288 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
290 -- Write the interface file
291 when (ghci_mode /= Interactive)
292 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
297 myParseModule dflags src_filename
298 = do -------------------------- Parser ----------------
299 showPass dflags "Parser"
302 buf <- hGetStringBuffer True{-expand tabs-} src_filename
304 let glaexts | dopt Opt_GlasgowExts dflags = 1#
307 case parseModule buf PState{ bol = 0#, atbol = 1#,
308 context = [], glasgow_exts = glaexts,
309 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
311 PFailed err -> do { hPutStrLn stderr (showSDoc err);
312 freeStringBuffer buf;
315 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
317 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
319 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
320 (ppSourceStats False rdr_module) ;
322 return (Just rdr_module)
323 -- ToDo: free the string buffer later.
327 restOfCodeGeneration dflags toInterp this_mod imported_module_names
328 foreign_stuff env_tc tidy_binds
329 hit pit -- these last two for mapping ModNames to Modules
332 <- byteCodeGen dflags tidy_binds local_tycons local_classes
333 return (Nothing, Nothing, Just (bcos,itbl_env))
337 -------------------------- Convert to STG -------------------------------
338 (stg_binds, cost_centre_info)
340 myCoreToStg dflags this_mod tidy_binds env_tc
342 -------------------------- Code generation ------------------------------
343 abstractC <- _scc_ "CodeGen"
344 codeGen dflags this_mod imported_modules
345 cost_centre_info fe_binders
346 local_tycons stg_binds
348 -------------------------- Code output -------------------------------
349 (maybe_stub_h_name, maybe_stub_c_name)
350 <- codeOutput dflags this_mod local_tycons
352 c_code h_code abstractC
354 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
356 local_tycons = typeEnvTyCons env_tc
357 local_classes = typeEnvClasses env_tc
358 imported_modules = map mod_name_to_Module imported_module_names
359 (h_code,c_code,fe_binders) = foreign_stuff
361 mod_name_to_Module :: ModuleName -> Module
362 mod_name_to_Module nm
363 = let str_mi = case lookupModuleEnvByName hit nm of
365 Nothing -> case lookupModuleEnvByName pit nm of
369 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
373 myCoreToStg dflags this_mod tidy_binds env_tc
375 () <- coreBindsSize tidy_binds `seq` return ()
376 -- TEMP: the above call zaps some space usage allocated by the
377 -- simplifier, which for reasons I don't understand, persists
378 -- thoroughout code generation
380 --let bcos = byteCodeGen dflags tidy_binds local_tycons local_classes
383 stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
385 (stg_binds2, cost_centre_info)
386 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
388 return (stg_binds2, cost_centre_info)
390 local_tycons = typeEnvTyCons env_tc
391 local_classes = typeEnvClasses env_tc
395 %************************************************************************
397 \subsection{Compiling a do-statement}
399 %************************************************************************
407 -> PersistentCompilerState -- IN: persistent compiler state
408 -> InteractiveContext -- Context for compiling
409 -> String -- The statement
410 -> Bool -- just treat it as an expression
411 -> IO ( PersistentCompilerState,
417 When the UnlinkedBCOExpr is linked you get an HValue of type
419 When you run it you get a list of HValues that should be
420 the same length as the list of names; add them to the ClosureEnv.
422 A naked expression returns a singleton Name [it].
424 What you type The IO [HValue] that hscStmt returns
425 ------------- ------------------------------------
426 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
429 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
432 expr (of IO type) ==> expr >>= \ v -> return [v]
433 [NB: result not printed] bindings: [it]
436 expr (of non-IO type,
437 result showable) ==> let v = expr in print v >> return [v]
440 expr (of non-IO type,
441 result not showable) ==> error
444 hscStmt dflags hst hit pcs0 icontext stmt just_expr
448 ic_type_env = type_env,
449 ic_module = scope_mod } = icontext
451 do { maybe_stmt <- hscParseStmt dflags stmt
453 Nothing -> return (pcs0, Nothing)
454 Just parsed_stmt -> do {
456 let { notExprStmt (ExprStmt _ _) = False;
460 if (just_expr && notExprStmt parsed_stmt)
461 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
462 return (pcs0, Nothing)
466 (pcs1, print_unqual, maybe_renamed_stmt)
467 <- renameStmt dflags hit hst pcs0 scope_mod
468 iNTERACTIVE rn_env parsed_stmt
470 ; case maybe_renamed_stmt of
471 Nothing -> return (pcs0, Nothing)
472 Just (bound_names, rn_stmt) -> do {
477 then case rn_stmt of { (syn, ExprStmt e _, decls) ->
478 typecheckExpr dflags pcs1 hst type_env
479 print_unqual iNTERACTIVE (syn,e,decls) }
480 else typecheckStmt dflags pcs1 hst type_env
481 print_unqual iNTERACTIVE bound_names rn_stmt
483 ; case maybe_tc_return of
484 Nothing -> return (pcs0, Nothing)
485 Just (pcs2, tc_expr, bound_ids, ty) -> do {
488 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
491 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
493 -- Tidy it (temporary, until coreSat does cloning)
494 ; tidy_expr <- tidyCoreExpr simpl_expr
497 ; sat_expr <- coreSatExpr dflags tidy_expr
500 ; bcos <- coreExprToBCOs dflags sat_expr
503 -- Make all the bound ids "global" ids, now that
504 -- they're notionally top-level bindings. This is
505 -- important: otherwise when we come to compile an expression
506 -- using these ids later, the byte code generator will consider
507 -- the occurrences to be free rather than global.
508 global_bound_ids = map globaliseId bound_ids;
509 globaliseId id = setIdGlobalDetails id VanillaGlobal
511 ; return (pcs2, Just (global_bound_ids, ty, bcos))
515 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
516 hscParseStmt dflags str
517 = do -------------------------- Parser ----------------
518 showPass dflags "Parser"
521 buf <- stringToStringBuffer str
523 let glaexts | dopt Opt_GlasgowExts dflags = 1#
526 case parseStmt buf PState{ bol = 0#, atbol = 1#,
527 context = [], glasgow_exts = glaexts,
528 loc = mkSrcLoc SLIT("<no file>") 0 } of {
530 PFailed err -> do { hPutStrLn stderr (showSDoc err);
531 -- Not yet implemented in <4.11 freeStringBuffer buf;
534 -- no stmt: the line consisted of just space or comments
535 POk _ Nothing -> return Nothing;
537 POk _ (Just rdr_stmt) -> do {
539 --ToDo: can't free the string buffer until we've finished this
540 -- compilation sweep and all the identifiers have gone away.
541 --freeStringBuffer buf;
542 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
543 return (Just rdr_stmt)
548 %************************************************************************
550 \subsection{Initial persistent state}
552 %************************************************************************
555 initPersistentCompilerState :: IO PersistentCompilerState
556 initPersistentCompilerState
557 = do prs <- initPersistentRenamerState
559 PCS { pcs_PIT = emptyIfaceTable,
560 pcs_PTE = wiredInThingEnv,
561 pcs_insts = emptyInstEnv,
562 pcs_rules = emptyRuleBase,
567 initPersistentRenamerState :: IO PersistentRenamerState
568 = do us <- mkSplitUniqSupply 'r'
570 PRS { prsOrig = NameSupply { nsUniqs = us,
571 nsNames = initOrigNames,
573 prsDecls = (emptyNameEnv, 0),
574 prsInsts = (emptyBag, 0),
575 prsRules = (emptyBag, 0),
580 initOrigNames :: FiniteMap (ModuleName,OccName) Name
582 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
584 grab names = foldl add emptyFM names
586 = addToFM env (moduleName (nameModule name), nameOccName name) name
589 initRules :: PackageRuleBase
590 initRules = emptyRuleBase
592 foldl add emptyVarEnv builtinRules
595 = extendRuleBase env name rule