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 )
50 import ErrUtils ( dumpIfSet_dyn, showPass )
51 import Util ( unJust )
52 import UniqSupply ( mkSplitUniqSupply )
54 import Bag ( emptyBag )
57 import CmStaticInfo ( GhciMode(..) )
58 import HscStats ( ppSourceStats )
59 import HscTypes ( ModDetails, ModIface(..), PersistentCompilerState(..),
60 PersistentRenamerState(..), ModuleLocation(..),
61 HomeSymbolTable, InteractiveContext(..), TyThing(..),
62 NameSupply(..), PackageRuleBase, HomeIfaceTable,
63 typeEnvClasses, typeEnvTyCons, emptyIfaceTable,
66 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
67 import OccName ( OccName )
68 import Name ( Name, nameModule, nameOccName, getName, isGlobalName,
69 emptyNameEnv, extendNameEnvList
71 import Module ( Module, lookupModuleEnvByName )
74 import Maybe ( isJust )
79 %************************************************************************
81 \subsection{The main compiler pipeline}
83 %************************************************************************
88 = HscFail PersistentCompilerState -- updated PCS
89 -- concluded that it wasn't necessary
90 | HscNoRecomp PersistentCompilerState -- updated PCS
91 ModDetails -- new details (HomeSymbolTable additions)
92 ModIface -- new iface (if any compilation was done)
94 | HscRecomp PersistentCompilerState -- updated PCS
95 ModDetails -- new details (HomeSymbolTable additions)
96 ModIface -- new iface (if any compilation was done)
97 (Maybe String) -- generated stub_h filename (in /tmp)
98 (Maybe String) -- generated stub_c filename (in /tmp)
99 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
102 -- no errors or warnings; the individual passes
103 -- (parse/rename/typecheck) print messages themselves
108 -> Bool -- source unchanged?
109 -> ModuleLocation -- location info
110 -> Maybe ModIface -- old interface, if available
111 -> HomeSymbolTable -- for home module ModDetails
113 -> PersistentCompilerState -- IN: persistent compiler state
116 hscMain ghci_mode dflags source_unchanged location maybe_old_iface hst hit pcs
118 showPass dflags ("Checking old interface for hs = "
119 ++ show (ml_hs_file location)
120 ++ ", hspp = " ++ show (ml_hspp_file location));
122 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
123 <- checkOldIface ghci_mode dflags hit hst pcs
124 (unJust "hscMain" (ml_hi_file location))
125 source_unchanged maybe_old_iface;
128 return (HscFail pcs_ch)
131 let no_old_iface = not (isJust maybe_checked_iface)
132 what_next | recomp_reqd || no_old_iface = hscRecomp
133 | otherwise = hscNoRecomp
135 what_next ghci_mode dflags location maybe_checked_iface
140 -- we definitely expect to have the old interface available
141 hscNoRecomp ghci_mode dflags location (Just old_iface) hst hit pcs_ch
142 | ghci_mode == OneShot
144 hPutStrLn stderr "compilation IS NOT required";
145 let { bomb = panic "hscNoRecomp:OneShot" };
146 return (HscNoRecomp pcs_ch bomb bomb)
150 when (verbosity dflags >= 1) $
151 hPutStrLn stderr ("Skipping " ++
152 (unJust "hscNoRecomp" (ml_hs_file location)));
155 (pcs_cl, closure_errs, cl_hs_decls)
156 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
158 return (HscFail pcs_cl)
163 <- typecheckIface dflags pcs_cl hst old_iface (vanillaSyntaxMap, cl_hs_decls);
165 case maybe_tc_result of {
166 Nothing -> return (HscFail pcs_cl);
167 Just (pcs_tc, env_tc, local_rules) -> do {
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 hPutStrLn stderr ("Compiling " ++
180 (unJust "hscRecomp" (ml_hs_file location)))
182 -- what target are we shooting for?
183 ; let toInterp = dopt_HscLang dflags == HscInterpreted
188 ; maybe_parsed <- myParseModule dflags
189 (unJust "hscRecomp:hspp" (ml_hspp_file location))
190 ; case maybe_parsed of {
191 Nothing -> return (HscFail pcs_ch);
192 Just rdr_module -> do {
193 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
198 ; (pcs_rn, print_unqualified, maybe_rn_result)
200 renameModule dflags hit hst pcs_ch this_mod rdr_module
201 ; case maybe_rn_result of {
202 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
203 Just (is_exported, new_iface, rn_hs_decls) -> do {
205 -- In interactive mode, we don't want to discard any top-level entities at
206 -- all (eg. do not inline them away during simplification), and retain them
207 -- all in the TypeEnv so they are available from the command line.
209 -- isGlobalName separates the user-defined top-level names from those
210 -- introduced by the type checker.
211 ; let dont_discard | ghci_mode == Interactive = isGlobalName
212 | otherwise = is_exported
218 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
219 print_unqualified rn_hs_decls
220 ; case maybe_tc_result of {
221 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
222 Just (pcs_tc, tc_result) -> do {
224 ; let env_tc = tc_env tc_result
229 ; (ds_binds, ds_rules, foreign_stuff)
231 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
234 -- SIMPLIFY, TIDY-CORE
236 -- We grab the the unfoldings at this point.
237 ; (pcs_simpl, tidy_binds, orphan_rules)
238 <- simplThenTidy dflags pcs_tc hst this_mod dont_discard ds_binds ds_rules
241 -- BUILD THE NEW ModDetails AND ModIface
243 ; let new_details = mkModDetails env_tc tidy_binds orphan_rules
244 ; final_iface <- _scc_ "MkFinalIface"
245 mkFinalIface ghci_mode dflags location
246 maybe_checked_iface new_iface new_details
249 -- CONVERT TO STG and COMPLETE CODE GENERATION
251 -- Do saturation and convert to A-normal form
252 ; saturated <- coreSatPgm dflags tidy_binds
254 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
255 <- restOfCodeGeneration dflags toInterp this_mod
256 (map ideclName (hsModuleImports rdr_module))
257 foreign_stuff env_tc saturated
258 hit (pcs_PIT pcs_simpl)
260 -- and the answer is ...
261 ; return (HscRecomp pcs_simpl new_details final_iface
262 maybe_stub_h_filename maybe_stub_c_filename
268 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
269 = case completeIface maybe_old_iface new_iface new_details of
270 (new_iface, Nothing) -- no change in the interfacfe
271 -> do when (dopt Opt_D_dump_hi_diffs dflags)
272 (printDump (text "INTERFACE UNCHANGED"))
273 dumpIfSet_dyn dflags Opt_D_dump_hi
274 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
276 (new_iface, Just sdoc_diffs)
277 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
279 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
281 -- Write the interface file
282 when (ghci_mode /= Interactive)
283 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
288 myParseModule dflags src_filename
289 = do -------------------------- Parser ----------------
290 showPass dflags "Parser"
293 buf <- hGetStringBuffer True{-expand tabs-} src_filename
295 let glaexts | dopt Opt_GlasgowExts dflags = 1#
298 case parseModule buf PState{ bol = 0#, atbol = 1#,
299 context = [], glasgow_exts = glaexts,
300 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
302 PFailed err -> do { hPutStrLn stderr (showSDoc err);
303 freeStringBuffer buf;
306 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
308 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
310 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
311 (ppSourceStats False rdr_module) ;
313 return (Just rdr_module)
314 -- ToDo: free the string buffer later.
318 simplThenTidy dflags pcs hst this_mod dont_discard binds rules
319 = do -- Do main Core-language transformations ---------
321 (simplified, orphan_rules)
322 <- core2core dflags pcs hst dont_discard binds rules
324 -- Do the final tidy-up
325 (pcs', tidy_binds, tidy_orphan_rules)
326 <- tidyCorePgm dflags this_mod pcs simplified 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 a do-statement}
403 %************************************************************************
411 -> PersistentCompilerState -- IN: persistent compiler state
412 -> InteractiveContext -- Context for compiling
413 -> String -- The statement
414 -> IO ( PersistentCompilerState,
415 Maybe (InteractiveContext,
420 When the UnlinkedBCOExpr is linked you get an HValue of type
422 When you run it you get a list of HValues that should be
423 the same length as the list of names; add them to the ClosureEnv.
425 A naked expression returns a singleton Name [it].
427 What you type The IO [HValue] that hscStmt returns
428 ------------- ------------------------------------
429 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
432 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
435 expr (of IO type) ==> expr >>= \ v -> return [v]
436 [NB: result not printed] bindings: [it]
439 expr (of non-IO type,
440 result showable) ==> let v = expr in print v >> return [v]
443 expr (of non-IO type,
444 result not showable) ==> error
447 hscStmt dflags hst hit pcs0 icontext stmt
451 ic_type_env = type_env,
452 ic_module = this_mod } = icontext
454 do { maybe_stmt <- hscParseStmt dflags stmt
456 Nothing -> return (pcs0, Nothing)
457 Just parsed_stmt -> do {
460 (pcs1, print_unqual, maybe_renamed_stmt)
461 <- renameStmt dflags hit hst pcs0 this_mod rn_env parsed_stmt
462 ; case maybe_renamed_stmt of
463 Nothing -> return (pcs0, Nothing)
464 Just (bound_names, rn_stmt) -> do {
467 maybe_tc_return <- typecheckStmt dflags pcs1 hst type_env
468 print_unqual this_mod bound_names rn_stmt
469 ; case maybe_tc_return of {
470 Nothing -> return (pcs0, Nothing) ;
471 Just (pcs2, tc_expr, bound_ids) -> do {
474 ds_expr <- deSugarExpr dflags pcs2 hst this_mod print_unqual tc_expr
477 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
480 ; sat_expr <- coreSatExpr dflags simpl_expr
483 ; bcos <- coreExprToBCOs dflags sat_expr
486 -- make all the bound ids "constant" ids, now that
487 -- they're notionally top-level bindings. This is
488 -- important: otherwise when we come to compile an expression
489 -- using these ids later, the byte code generator will consider
490 -- the occurrences to be free rather than global.
491 constant_bound_ids = map constantizeId bound_ids
493 = modifyIdInfo (`setFlavourInfo` makeConstantFlavour
496 new_rn_env = extendLocalRdrEnv rn_env
497 (map idName constant_bound_ids)
498 -- Extend the renamer-env from bound_ids, not bound_names,
499 -- because the latter may contain [it] when the former is empty
501 new_type_env = extendNameEnvList type_env
502 [(getName id, AnId id) | id <- constant_bound_ids]
504 new_icontext = icontext { ic_rn_env = new_rn_env,
505 ic_type_env = new_type_env }
506 ; return (pcs2, Just (new_icontext, bound_ids, bcos))
509 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
510 hscParseStmt dflags str
511 = do -------------------------- Parser ----------------
512 showPass dflags "Parser"
515 buf <- stringToStringBuffer str
517 let glaexts | dopt Opt_GlasgowExts dflags = 1#
520 case parseStmt buf PState{ bol = 0#, atbol = 1#,
521 context = [], glasgow_exts = glaexts,
522 loc = mkSrcLoc SLIT("<no file>") 0 } of {
524 PFailed err -> do { hPutStrLn stderr (showSDoc err);
525 -- Not yet implemented in <4.11 freeStringBuffer buf;
528 -- no stmt: the line consisted of just space or comments
529 POk _ Nothing -> return Nothing;
531 POk _ (Just rdr_stmt) -> do {
533 --ToDo: can't free the string buffer until we've finished this
534 -- compilation sweep and all the identifiers have gone away.
535 --freeStringBuffer buf;
536 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
537 return (Just rdr_stmt)
542 %************************************************************************
544 \subsection{Initial persistent state}
546 %************************************************************************
549 initPersistentCompilerState :: IO PersistentCompilerState
550 initPersistentCompilerState
551 = do prs <- initPersistentRenamerState
553 PCS { pcs_PIT = emptyIfaceTable,
554 pcs_PTE = wiredInThingEnv,
555 pcs_insts = emptyInstEnv,
556 pcs_rules = emptyRuleBase,
561 initPersistentRenamerState :: IO PersistentRenamerState
562 = do us <- mkSplitUniqSupply 'r'
564 PRS { prsOrig = NameSupply { nsUniqs = us,
565 nsNames = initOrigNames,
567 prsDecls = (emptyNameEnv, 0),
568 prsInsts = (emptyBag, 0),
569 prsRules = (emptyBag, 0),
574 initOrigNames :: FiniteMap (ModuleName,OccName) Name
576 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
578 grab names = foldl add emptyFM names
580 = addToFM env (moduleName (nameModule name), nameOccName name) name
583 initRules :: PackageRuleBase
584 initRules = emptyRuleBase
586 foldl add emptyVarEnv builtinRules
589 = extendRuleBase env name rule