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, tidyType )
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 VarEnv ( emptyTidyEnv )
68 import Name ( Name, nameModule, nameOccName, getName, isGlobalName,
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 ([UnlinkedBCO],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 hPutStrLn stderr "compilation IS NOT required";
152 (pcs_cl, closure_errs, cl_hs_decls)
153 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
155 return (HscFail pcs_cl)
159 maybe_tc_result <- typecheckModule dflags pcs_cl hst
160 old_iface alwaysQualify cl_hs_decls
161 False{-don't check for Main.main-};
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 hPutStrLn stderr "compilation IS required";
181 -- what target are we shooting for?
182 ; let toInterp = dopt_HscLang dflags == HscInterpreted
187 ; maybe_parsed <- myParseModule dflags
188 (unJust "hscRecomp:hspp" (ml_hspp_file location))
189 ; case maybe_parsed of {
190 Nothing -> return (HscFail pcs_ch);
191 Just rdr_module -> do {
192 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
197 ; (pcs_rn, maybe_rn_result)
199 renameModule dflags hit hst pcs_ch this_mod rdr_module
200 ; case maybe_rn_result of {
201 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
202 Just (print_unqualified, (is_exported, new_iface, rn_hs_decls)) -> do {
204 -- In interactive mode, we don't want to discard any top-level entities at
205 -- all (eg. do not inline them away during simplification), and retain them
206 -- all in the TypeEnv so they are available from the command line.
208 -- isGlobalName separates the user-defined top-level names from those
209 -- introduced by the type checker.
210 ; let dont_discard | ghci_mode == Interactive = isGlobalName
211 | otherwise = is_exported
217 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
218 print_unqualified rn_hs_decls
219 True{-check for Main.main if necessary-}
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 ; (maybe_stub_h_filename, maybe_stub_c_filename, maybe_bcos)
252 <- restOfCodeGeneration dflags toInterp this_mod
253 (map ideclName (hsModuleImports rdr_module))
254 foreign_stuff env_tc tidy_binds
255 hit (pcs_PIT pcs_simpl)
257 -- and the answer is ...
258 ; return (HscRecomp pcs_simpl new_details final_iface
259 maybe_stub_h_filename maybe_stub_c_filename
265 mkFinalIface ghci_mode dflags location maybe_old_iface new_iface new_details
266 = case completeIface maybe_old_iface new_iface new_details of
267 (new_iface, Nothing) -- no change in the interfacfe
268 -> do when (dopt Opt_D_dump_hi_diffs dflags)
269 (printDump (text "INTERFACE UNCHANGED"))
270 dumpIfSet_dyn dflags Opt_D_dump_hi
271 "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
273 (new_iface, Just sdoc_diffs)
274 -> do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED"
276 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE"
278 -- Write the interface file
279 when (ghci_mode /= Interactive)
280 (writeIface (unJust "hscRecomp:hi" (ml_hi_file location))
285 myParseModule dflags src_filename
286 = do -------------------------- Parser ----------------
287 showPass dflags "Parser"
290 buf <- hGetStringBuffer True{-expand tabs-} src_filename
292 let glaexts | dopt Opt_GlasgowExts dflags = 1#
295 case parseModule buf PState{ bol = 0#, atbol = 1#,
296 context = [], glasgow_exts = glaexts,
297 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
299 PFailed err -> do { hPutStrLn stderr (showSDoc err);
300 freeStringBuffer buf;
303 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
305 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
307 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
308 (ppSourceStats False rdr_module) ;
310 return (Just rdr_module)
311 -- ToDo: free the string buffer later.
315 simplThenTidy dflags pcs hst this_mod dont_discard binds rules
316 = do -- Do main Core-language transformations ---------
318 (simplified, orphan_rules)
319 <- core2core dflags pcs hst dont_discard binds rules
321 -- Do saturation and convert to A-normal form
322 -- NOTE: subsequent passes may not transform the syntax, only annotate it
323 saturated <- coreSatPgm dflags simplified
325 -- Do the final tidy-up
326 (pcs', tidy_binds, tidy_orphan_rules)
327 <- tidyCorePgm dflags this_mod pcs saturated orphan_rules
329 return (pcs', tidy_binds, tidy_orphan_rules)
332 restOfCodeGeneration dflags toInterp this_mod imported_module_names
333 foreign_stuff env_tc tidy_binds
334 hit pit -- these last two for mapping ModNames to Modules
337 <- byteCodeGen dflags tidy_binds local_tycons local_classes
338 return (Nothing, Nothing, Just (bcos,itbl_env))
342 -------------------------- Convert to STG -------------------------------
343 (stg_binds, cost_centre_info)
345 myCoreToStg dflags this_mod tidy_binds env_tc
347 -------------------------- Code generation ------------------------------
348 abstractC <- _scc_ "CodeGen"
349 codeGen dflags this_mod imported_modules
350 cost_centre_info fe_binders
351 local_tycons stg_binds
353 -------------------------- Code output -------------------------------
354 (maybe_stub_h_name, maybe_stub_c_name)
355 <- codeOutput dflags this_mod local_tycons
357 c_code h_code abstractC
359 return (maybe_stub_h_name, maybe_stub_c_name, Nothing)
361 local_tycons = typeEnvTyCons env_tc
362 local_classes = typeEnvClasses env_tc
363 imported_modules = map mod_name_to_Module imported_module_names
364 (h_code,c_code,fe_binders) = foreign_stuff
366 mod_name_to_Module :: ModuleName -> Module
367 mod_name_to_Module nm
368 = let str_mi = case lookupModuleEnvByName hit nm of
370 Nothing -> case lookupModuleEnvByName pit nm of
374 barf nm = pprPanic "mod_name_to_Module: no hst or pst mapping for"
378 myCoreToStg dflags this_mod tidy_binds env_tc
380 () <- coreBindsSize tidy_binds `seq` return ()
381 -- TEMP: the above call zaps some space usage allocated by the
382 -- simplifier, which for reasons I don't understand, persists
383 -- thoroughout code generation
385 --let bcos = byteCodeGen dflags tidy_binds local_tycons local_classes
388 stg_binds <- _scc_ "Core2Stg" coreToStg dflags this_mod tidy_binds
390 (stg_binds2, cost_centre_info)
391 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
393 return (stg_binds2, cost_centre_info)
395 local_tycons = typeEnvTyCons env_tc
396 local_classes = typeEnvClasses env_tc
400 %************************************************************************
402 \subsection{Compiling an expression}
404 %************************************************************************
410 -> Bool -- True <=> wrap in 'print' to get a result of IO type
413 -> PersistentCompilerState -- IN: persistent compiler state
414 -> Module -- Context for compiling
415 -> String -- The expression
416 -> IO ( PersistentCompilerState,
417 Maybe (UnlinkedBCOExpr, PrintUnqualified, Type) )
419 hscExpr dflags wrap_io hst hit pcs0 this_module expr
421 maybe_parsed <- hscParseExpr dflags expr;
423 Nothing -> return (pcs0, Nothing)
424 Just parsed_expr -> do {
427 (pcs1, maybe_renamed_expr) <-
428 renameExpr dflags hit hst pcs0 this_module parsed_expr;
429 case maybe_renamed_expr of
430 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing)
431 Just (print_unqual, rn_expr) -> do {
435 <- typecheckExpr dflags wrap_io pcs1 hst print_unqual this_module rn_expr;
436 case maybe_tc_return of {
437 Nothing -> return ({-WAS:pcs1-} pcs0, Nothing);
438 Just (pcs2, tc_expr, ty) -> do
440 let tidy_ty = tidyType emptyTidyEnv ty;
443 ds_expr <- deSugarExpr dflags pcs2 hst this_module
444 print_unqual tc_expr;
447 simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr;
450 sat_expr <- coreSatExpr dflags simpl_expr;
452 -- ToDo: need to do SRTs?
455 bcos <- coreExprToBCOs dflags sat_expr
457 return (pcs2, Just (bcos, print_unqual, tidy_ty));
460 hscParseExpr :: DynFlags -> String -> IO (Maybe RdrNameHsExpr)
461 hscParseExpr dflags str
462 = do -------------------------- Parser ----------------
463 showPass dflags "Parser"
466 buf <- stringToStringBuffer str
468 let glaexts | dopt Opt_GlasgowExts dflags = 1#
471 case parseExpr buf PState{ bol = 0#, atbol = 1#,
472 context = [], glasgow_exts = glaexts,
473 loc = mkSrcLoc SLIT("<no file>") 0 } of {
475 PFailed err -> do { hPutStrLn stderr (showSDoc err);
476 -- Not yet implemented in <4.11 freeStringBuffer buf;
479 POk _ rdr_expr -> do {
481 --ToDo: can't free the string buffer until we've finished this
482 -- compilation sweep and all the identifiers have gone away.
483 --freeStringBuffer buf;
484 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_expr);
485 return (Just rdr_expr)
490 %************************************************************************
492 \subsection{Initial persistent state}
494 %************************************************************************
497 initPersistentCompilerState :: IO PersistentCompilerState
498 initPersistentCompilerState
499 = do prs <- initPersistentRenamerState
501 PCS { pcs_PIT = emptyIfaceTable,
502 pcs_PTE = wiredInThingEnv,
503 pcs_insts = emptyInstEnv,
504 pcs_rules = emptyRuleBase,
509 initPersistentRenamerState :: IO PersistentRenamerState
510 = do us <- mkSplitUniqSupply 'r'
512 PRS { prsOrig = NameSupply { nsUniqs = us,
513 nsNames = initOrigNames,
515 prsDecls = (emptyNameEnv, 0),
516 prsInsts = (emptyBag, 0),
517 prsRules = (emptyBag, 0),
522 initOrigNames :: FiniteMap (ModuleName,OccName) Name
524 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
526 grab names = foldl add emptyFM names
528 = addToFM env (moduleName (nameModule name), nameOccName name) name
531 initRules :: PackageRuleBase
532 initRules = emptyRuleBase
534 foldl add emptyVarEnv builtinRules
537 = extendRuleBase env name rule