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 )
23 import StringBuffer ( hGetStringBuffer,
24 stringToStringBuffer, freeStringBuffer )
26 import Lex ( PState(..), ParseResult(..) )
27 import SrcLoc ( mkSrcLoc )
28 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
29 import Rules ( emptyRuleBase )
30 import PrelInfo ( wiredInThingEnv, wiredInThings )
31 import PrelNames ( vanillaSyntaxMap, knownKeyNames )
32 import MkIface ( completeIface, mkModDetailsFromIface, mkModDetails,
33 writeIface, pprIface )
35 import InstEnv ( emptyInstEnv )
38 import CoreUtils ( coreBindsSize )
39 import CoreTidy ( tidyCorePgm )
41 import CoreToStg ( coreToStg )
42 import SimplStg ( stg2stg )
43 import CodeGen ( codeGen )
44 import CodeOutput ( codeOutput )
46 import Id ( Id, idName, idFlavour, modifyIdInfo )
47 import IdInfo ( setFlavourInfo, makeConstantFlavour )
48 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(..),
62 HomeSymbolTable, InteractiveContext(..), TyThing(..),
63 NameSupply(..), PackageRuleBase, HomeIfaceTable,
64 typeEnvClasses, typeEnvTyCons, emptyIfaceTable,
67 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
68 import OccName ( OccName )
69 import Name ( Name, nameModule, nameOccName, getName, isGlobalName,
70 emptyNameEnv, extendNameEnvList
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 /tmp)
99 (Maybe String) -- generated stub_c filename (in /tmp)
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, env_tc, local_rules) -> do {
170 -- create a new details from the closed, typechecked, old iface
171 let new_details = mkModDetailsFromIface env_tc local_rules
173 return (HscNoRecomp pcs_tc new_details old_iface)
176 compMsg mod location =
177 mod_str ++ take (12 - length mod_str) (repeat ' ')
178 ++ " (" ++ unJust "hscRecomp" (ml_hs_file location) ++ ")"
179 where mod_str = moduleUserString mod
182 hscRecomp ghci_mode dflags mod location maybe_checked_iface hst hit pcs_ch
184 ; when (verbosity dflags >= 1) $
185 hPutStrLn stderr ("Compiling " ++ compMsg mod location);
187 -- what target are we shooting for?
188 ; let toInterp = dopt_HscLang dflags == HscInterpreted
193 ; maybe_parsed <- myParseModule dflags
194 (unJust "hscRecomp:hspp" (ml_hspp_file location))
195 ; case maybe_parsed of {
196 Nothing -> return (HscFail pcs_ch);
197 Just rdr_module -> do {
198 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
203 ; (pcs_rn, print_unqualified, maybe_rn_result)
205 renameModule dflags hit hst pcs_ch this_mod rdr_module
206 ; case maybe_rn_result of {
207 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
208 Just (is_exported, new_iface, rn_hs_decls) -> do {
210 -- In interactive mode, we don't want to discard any top-level entities at
211 -- all (eg. do not inline them away during simplification), and retain them
212 -- all in the TypeEnv so they are available from the command line.
214 -- isGlobalName separates the user-defined top-level names from those
215 -- introduced by the type checker.
216 ; let dont_discard | ghci_mode == Interactive = isGlobalName
217 | otherwise = is_exported
223 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
224 print_unqualified rn_hs_decls
225 ; case maybe_tc_result of {
226 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
227 Just (pcs_tc, tc_result) -> do {
229 ; let env_tc = tc_env tc_result
234 ; (ds_binds, ds_rules, foreign_stuff)
236 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
239 -- SIMPLIFY, TIDY-CORE
241 -- We grab the the unfoldings at this point.
242 ; (pcs_simpl, tidy_binds, orphan_rules)
243 <- simplThenTidy dflags pcs_tc hst this_mod dont_discard ds_binds ds_rules
246 -- BUILD THE NEW ModDetails AND ModIface
248 ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
249 ; final_iface <- _scc_ "MkFinalIface"
250 mkFinalIface ghci_mode dflags location
251 maybe_checked_iface new_iface new_details
254 -- CONVERT TO STG and COMPLETE CODE GENERATION
256 -- Do saturation and convert to A-normal form
257 ; saturated <- coreSatPgm dflags tidy_binds
259 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
260 <- restOfCodeGeneration dflags toInterp this_mod
261 (map ideclName (hsModuleImports rdr_module))
262 foreign_stuff env_tc saturated
263 hit (pcs_PIT pcs_simpl)
265 -- and the answer is ...
266 ; return (HscRecomp pcs_simpl new_details final_iface
267 maybe_stub_h_filename maybe_stub_c_filename
273 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
274 = case completeIface maybe_old_iface new_iface new_details of
275 (new_iface, Nothing) -- no change in the interfacfe
276 -> do when (dopt Opt_D_dump_hi_diffs dflags)
277 (printDump (text "INTERFACE UNCHANGED"))
278 dumpIfSet_dyn dflags Opt_D_dump_hi
279 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
281 (new_iface, Just sdoc_diffs)
282 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
284 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
286 -- Write the interface file
287 when (ghci_mode /= Interactive)
288 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
293 myParseModule dflags src_filename
294 = do -------------------------- Parser ----------------
295 showPass dflags "Parser"
298 buf <- hGetStringBuffer True{-expand tabs-} src_filename
300 let glaexts | dopt Opt_GlasgowExts dflags = 1#
303 case parseModule buf PState{ bol = 0#, atbol = 1#,
304 context = [], glasgow_exts = glaexts,
305 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
307 PFailed err -> do { hPutStrLn stderr (showSDoc err);
308 freeStringBuffer buf;
311 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
313 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
315 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
316 (ppSourceStats False rdr_module) ;
318 return (Just rdr_module)
319 -- ToDo: free the string buffer later.
323 simplThenTidy dflags pcs hst this_mod dont_discard binds rules
324 = do -- Do main Core-language transformations ---------
326 (simplified, orphan_rules)
327 <- core2core dflags pcs hst dont_discard binds rules
329 -- Do the final tidy-up
330 (pcs', tidy_binds, tidy_orphan_rules)
331 <- tidyCorePgm dflags this_mod pcs simplified orphan_rules
333 return (pcs', tidy_binds, tidy_orphan_rules)
336 restOfCodeGeneration dflags toInterp this_mod imported_module_names
337 foreign_stuff env_tc tidy_binds
338 hit pit -- these last two for mapping ModNames to Modules
341 <- byteCodeGen dflags tidy_binds local_tycons local_classes
342 return (Nothing, Nothing, Just (bcos,itbl_env))
346 -------------------------- Convert to STG -------------------------------
347 (stg_binds, cost_centre_info)
349 myCoreToStg dflags this_mod tidy_binds env_tc
351 -------------------------- Code generation ------------------------------
352 abstractC <- _scc_ "CodeGen"
353 codeGen dflags this_mod imported_modules
354 cost_centre_info fe_binders
355 local_tycons stg_binds
357 -------------------------- Code output -------------------------------
358 (maybe_stub_h_name, maybe_stub_c_name)
359 <- codeOutput dflags this_mod local_tycons
361 c_code h_code abstractC
363 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
365 local_tycons = typeEnvTyCons env_tc
366 local_classes = typeEnvClasses env_tc
367 imported_modules = map mod_name_to_Module imported_module_names
368 (h_code,c_code,fe_binders) = foreign_stuff
370 mod_name_to_Module :: ModuleName -> Module
371 mod_name_to_Module nm
372 = let str_mi = case lookupModuleEnvByName hit nm of
374 Nothing -> case lookupModuleEnvByName pit nm of
378 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
382 myCoreToStg dflags this_mod tidy_binds env_tc
384 () <- coreBindsSize tidy_binds `seq` return ()
385 -- TEMP: the above call zaps some space usage allocated by the
386 -- simplifier, which for reasons I don't understand, persists
387 -- thoroughout code generation
389 --let bcos = byteCodeGen dflags tidy_binds local_tycons local_classes
392 stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
394 (stg_binds2, cost_centre_info)
395 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
397 return (stg_binds2, cost_centre_info)
399 local_tycons = typeEnvTyCons env_tc
400 local_classes = typeEnvClasses env_tc
404 %************************************************************************
406 \subsection{Compiling a do-statement}
408 %************************************************************************
416 -> PersistentCompilerState -- IN: persistent compiler state
417 -> InteractiveContext -- Context for compiling
418 -> String -- The statement
419 -> IO ( PersistentCompilerState,
420 Maybe (InteractiveContext,
425 When the UnlinkedBCOExpr is linked you get an HValue of type
427 When you run it you get a list of HValues that should be
428 the same length as the list of names; add them to the ClosureEnv.
430 A naked expression returns a singleton Name [it].
432 What you type The IO [HValue] that hscStmt returns
433 ------------- ------------------------------------
434 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
437 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
440 expr (of IO type) ==> expr >>= \ v -> return [v]
441 [NB: result not printed] bindings: [it]
444 expr (of non-IO type,
445 result showable) ==> let v = expr in print v >> return [v]
448 expr (of non-IO type,
449 result not showable) ==> error
452 hscStmt dflags hst hit pcs0 icontext stmt
456 ic_type_env = type_env,
457 ic_module = this_mod } = icontext
459 do { maybe_stmt <- hscParseStmt dflags stmt
461 Nothing -> return (pcs0, Nothing)
462 Just parsed_stmt -> do {
465 (pcs1, print_unqual, maybe_renamed_stmt)
466 <- renameStmt dflags hit hst pcs0 this_mod rn_env parsed_stmt
467 ; case maybe_renamed_stmt of
468 Nothing -> return (pcs0, Nothing)
469 Just (bound_names, rn_stmt) -> do {
472 maybe_tc_return <- typecheckStmt dflags pcs1 hst type_env
473 print_unqual this_mod bound_names rn_stmt
474 ; case maybe_tc_return of {
475 Nothing -> return (pcs0, Nothing) ;
476 Just (pcs2, tc_expr, bound_ids) -> do {
479 ds_expr <- deSugarExpr dflags pcs2 hst this_mod print_unqual tc_expr
482 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
485 ; sat_expr <- coreSatExpr dflags simpl_expr
488 ; bcos <- coreExprToBCOs dflags sat_expr
491 -- make all the bound ids "constant" ids, now that
492 -- they're notionally top-level bindings. This is
493 -- important: otherwise when we come to compile an expression
494 -- using these ids later, the byte code generator will consider
495 -- the occurrences to be free rather than global.
496 constant_bound_ids = map constantizeId bound_ids
498 = modifyIdInfo (`setFlavourInfo` makeConstantFlavour
501 new_rn_env = extendLocalRdrEnv rn_env
502 (map idName constant_bound_ids)
503 -- Extend the renamer-env from bound_ids, not bound_names,
504 -- because the latter may contain [it] when the former is empty
506 new_type_env = extendNameEnvList type_env
507 [(getName id, AnId id) | id <- constant_bound_ids]
509 new_icontext = icontext { ic_rn_env = new_rn_env,
510 ic_type_env = new_type_env }
511 ; return (pcs2, Just (new_icontext, bound_ids, bcos))
514 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
515 hscParseStmt dflags str
516 = do -------------------------- Parser ----------------
517 showPass dflags "Parser"
520 buf <- stringToStringBuffer str
522 let glaexts | dopt Opt_GlasgowExts dflags = 1#
525 case parseStmt buf PState{ bol = 0#, atbol = 1#,
526 context = [], glasgow_exts = glaexts,
527 loc = mkSrcLoc SLIT("<no file>") 0 } of {
529 PFailed err -> do { hPutStrLn stderr (showSDoc err);
530 -- Not yet implemented in <4.11 freeStringBuffer buf;
533 -- no stmt: the line consisted of just space or comments
534 POk _ Nothing -> return Nothing;
536 POk _ (Just rdr_stmt) -> do {
538 --ToDo: can't free the string buffer until we've finished this
539 -- compilation sweep and all the identifiers have gone away.
540 --freeStringBuffer buf;
541 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
542 return (Just rdr_stmt)
547 %************************************************************************
549 \subsection{Initial persistent state}
551 %************************************************************************
554 initPersistentCompilerState :: IO PersistentCompilerState
555 initPersistentCompilerState
556 = do prs <- initPersistentRenamerState
558 PCS { pcs_PIT = emptyIfaceTable,
559 pcs_PTE = wiredInThingEnv,
560 pcs_insts = emptyInstEnv,
561 pcs_rules = emptyRuleBase,
566 initPersistentRenamerState :: IO PersistentRenamerState
567 = do us <- mkSplitUniqSupply 'r'
569 PRS { prsOrig = NameSupply { nsUniqs = us,
570 nsNames = initOrigNames,
572 prsDecls = (emptyNameEnv, 0),
573 prsInsts = (emptyBag, 0),
574 prsRules = (emptyBag, 0),
579 initOrigNames :: FiniteMap (ModuleName,OccName) Name
581 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
583 grab names = foldl add emptyFM names
585 = addToFM env (moduleName (nameModule name), nameOccName name) name
588 initRules :: PackageRuleBase
589 initRules = emptyRuleBase
591 foldl add emptyVarEnv builtinRules
594 = extendRuleBase env name rule