2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
8 module HscMain ( HscResult(..), hscMain,
12 initPersistentCompilerState ) where
14 #include "HsVersions.h"
17 import ByteCodeGen ( byteCodeGen )
18 import CoreTidy ( tidyCoreExpr )
19 import CorePrep ( corePrepExpr )
20 import Rename ( renameStmt, renameRdrName )
21 import RdrName ( rdrNameOcc, setRdrNameOcc )
22 import RdrHsSyn ( RdrNameStmt )
23 import OccName ( dataName, tcClsName,
24 occNameSpace, setOccNameSpace )
26 import Id ( Id, idName, setGlobalIdDetails )
27 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
28 import HscTypes ( InteractiveContext(..) )
29 import PrelNames ( iNTERACTIVE )
30 import StringBuffer ( stringToStringBuffer )
31 import FastString ( mkFastString )
32 import Char ( isUpper )
33 import DriverUtil ( split_longest_prefix )
39 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
40 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
42 import Lex ( PState(..), ParseResult(..) )
43 import SrcLoc ( mkSrcLoc )
44 import Finder ( findModule )
45 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
46 import Rules ( emptyRuleBase )
47 import PrelInfo ( wiredInThingEnv, wiredInThings )
48 import PrelNames ( knownKeyNames )
49 import MkIface ( mkFinalIface )
51 import InstEnv ( emptyInstEnv )
54 import CoreUtils ( coreBindsSize )
55 import CoreTidy ( tidyCorePgm )
56 import CorePrep ( corePrepPgm )
58 import CoreToStg ( coreToStg )
59 import SimplStg ( stg2stg )
60 import CodeGen ( codeGen )
61 import CodeOutput ( codeOutput )
63 import Module ( ModuleName, moduleName, mkHomeModule,
66 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
67 import Util ( unJust )
68 import UniqSupply ( mkSplitUniqSupply )
70 import Bag ( emptyBag )
73 import HscStats ( ppSourceStats )
75 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
76 import OccName ( OccName )
77 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
78 import NameEnv ( emptyNameEnv, mkNameEnv )
79 import Module ( Module )
81 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
84 import Maybe ( isJust, fromJust, catMaybes )
87 import MkExternalCore ( emitExternalCore )
91 %************************************************************************
93 \subsection{The main compiler pipeline}
95 %************************************************************************
100 = HscFail PersistentCompilerState -- updated PCS
101 -- concluded that it wasn't necessary
102 | HscNoRecomp PersistentCompilerState -- updated PCS
103 ModDetails -- new details (HomeSymbolTable additions)
104 ModIface -- new iface (if any compilation was done)
106 | HscRecomp PersistentCompilerState -- updated PCS
107 ModDetails -- new details (HomeSymbolTable additions)
108 ModIface -- new iface (if any compilation was done)
109 Bool -- stub_h exists
110 Bool -- stub_c exists
112 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
114 (Maybe ()) -- no interpreted code whatsoever
117 -- no errors or warnings; the individual passes
118 -- (parse/rename/typecheck) print messages themselves
124 -> ModuleLocation -- location info
125 -> Bool -- True <=> source unchanged
126 -> Bool -- True <=> have an object file (for msgs only)
127 -> Maybe ModIface -- old interface, if available
128 -> HomeSymbolTable -- for home module ModDetails
130 -> PersistentCompilerState -- IN: persistent compiler state
133 hscMain ghci_mode dflags mod location source_unchanged have_object
134 maybe_old_iface hst hit pcs
136 showPass dflags ("Checking old interface for hs = "
137 ++ show (ml_hs_file location)
138 ++ ", hspp = " ++ show (ml_hspp_file location));
140 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
141 <- _scc_ "checkOldIface"
142 checkOldIface ghci_mode dflags hit hst pcs (ml_hi_file location)
143 source_unchanged maybe_old_iface;
146 return (HscFail pcs_ch)
149 let no_old_iface = not (isJust maybe_checked_iface)
150 what_next | recomp_reqd || no_old_iface = hscRecomp
151 | otherwise = hscNoRecomp
153 what_next ghci_mode dflags have_object mod location
154 maybe_checked_iface hst hit pcs_ch
158 -- we definitely expect to have the old interface available
159 hscNoRecomp ghci_mode dflags have_object
160 mod location (Just old_iface) hst hit pcs_ch
161 | ghci_mode == OneShot
163 hPutStrLn stderr "compilation IS NOT required";
164 let { bomb = panic "hscNoRecomp:OneShot" };
165 return (HscNoRecomp pcs_ch bomb bomb)
169 when (verbosity dflags >= 1) $
170 hPutStrLn stderr ("Skipping " ++
171 compMsg have_object mod location);
174 (pcs_cl, closure_errs, cl_hs_decls)
175 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
177 return (HscFail pcs_cl)
182 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
184 case maybe_tc_result of {
185 Nothing -> return (HscFail pcs_cl);
186 Just (pcs_tc, new_details) ->
188 return (HscNoRecomp pcs_tc new_details old_iface)
191 compMsg use_object mod location =
192 mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
193 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
195 then unJust "hscRecomp" (ml_obj_file location)
198 where mod_str = moduleUserString mod
201 hscRecomp ghci_mode dflags have_object
202 mod location maybe_checked_iface hst hit pcs_ch
204 -- what target are we shooting for?
205 ; let toInterp = dopt_HscLang dflags == HscInterpreted
206 ; let toNothing = dopt_HscLang dflags == HscNothing
208 ; when (verbosity dflags >= 1) $
209 hPutStrLn stderr ("Compiling " ++
210 compMsg (not toInterp) mod location);
215 ; maybe_parsed <- myParseModule dflags
216 (unJust "hscRecomp:hspp" (ml_hspp_file location))
217 ; case maybe_parsed of {
218 Nothing -> return (HscFail pcs_ch);
219 Just rdr_module -> do {
220 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
225 ; (pcs_rn, print_unqualified, maybe_rn_result)
227 renameModule dflags hit hst pcs_ch this_mod rdr_module
228 ; case maybe_rn_result of {
229 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
230 Just (is_exported, new_iface, rn_hs_decls) -> do {
232 -- In interactive mode, we don't want to discard any top-level entities at
233 -- all (eg. do not inline them away during simplification), and retain them
234 -- all in the TypeEnv so they are available from the command line.
236 -- isGlobalName separates the user-defined top-level names from those
237 -- introduced by the type checker.
238 ; let dont_discard | ghci_mode == Interactive = isGlobalName
239 | otherwise = is_exported
245 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
246 print_unqualified rn_hs_decls
247 ; case maybe_tc_result of {
248 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
249 Just (pcs_tc, tc_result) -> do {
254 ; (ds_details, foreign_stuff)
256 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
259 <- if ghci_mode == OneShot
260 then do init_pcs <- initPersistentCompilerState
261 init_prs <- initPersistentRenamerState
263 rules = pcs_rules pcs_tc
264 orig_tc = prsOrig (pcs_PRS pcs_tc)
265 new_prs = init_prs{ prsOrig=orig_tc }
267 orig_tc `seq` rules `seq` new_prs `seq`
268 return init_pcs{ pcs_PRS = new_prs,
277 core2core dflags pcs_middle hst dont_discard ds_details
282 ; cg_info_ref <- newIORef Nothing ;
283 ; let cg_info :: CgInfoEnv
284 cg_info = unsafePerformIO $ do {
285 maybe_cg_env <- readIORef cg_info_ref ;
287 Just env -> return env
288 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
289 return emptyNameEnv } }
290 -- cg_info_ref will be filled in just after restOfCodeGeneration
291 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
293 ; (pcs_simpl, tidy_details)
295 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
297 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
298 else return pcs_simpl
300 -- alive at this point:
304 ; emitExternalCore dflags new_iface tidy_details
306 -- PREPARE FOR CODE GENERATION
308 -- Do saturation and convert to A-normal form
309 ; prepd_details <- _scc_ "CorePrep" corePrepPgm dflags tidy_details
312 -- CONVERT TO STG and COMPLETE CODE GENERATION
315 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
317 local_tycons = typeEnvTyCons env_tc
318 local_classes = typeEnvClasses env_tc
320 imported_module_names = map ideclName (hsModuleImports rdr_module)
322 mod_name_to_Module nm
323 = do m <- findModule nm ; return (fst (fromJust m))
325 (h_code,c_code,fe_binders) = foreign_stuff
327 ; imported_modules <- mapM mod_name_to_Module imported_module_names
329 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
333 ----------------- Generate byte code ------------------
334 (bcos,itbl_env) <- byteCodeGen dflags binds
335 local_tycons local_classes
337 -- Fill in the code-gen info
338 writeIORef cg_info_ref (Just emptyNameEnv)
340 ------------------ BUILD THE NEW ModIface ------------
341 final_iface <- _scc_ "MkFinalIface"
342 mkFinalIface ghci_mode dflags location
343 maybe_checked_iface new_iface tidy_details
345 return ( False, False, Just (bcos,itbl_env), final_iface )
347 then error "GHC not compiled with interpreter"
351 ----------------- Convert to STG ------------------
352 (stg_binds, cost_centre_info, stg_back_end_info)
354 myCoreToStg dflags this_mod binds
356 -- Fill in the code-gen info for the earlier tidyCorePgm
357 writeIORef cg_info_ref (Just stg_back_end_info)
359 ------------------ BUILD THE NEW ModIface ------------
360 final_iface <- _scc_ "MkFinalIface"
361 mkFinalIface ghci_mode dflags location
362 maybe_checked_iface new_iface tidy_details
366 return (False, False, Nothing, final_iface)
368 ------------------ Code generation ------------------
369 abstractC <- _scc_ "CodeGen"
370 codeGen dflags this_mod imported_modules
371 cost_centre_info fe_binders
372 local_tycons stg_binds
374 ------------------ Code output -----------------------
375 (stub_h_exists, stub_c_exists)
376 <- codeOutput dflags this_mod local_tycons
378 c_code h_code abstractC
380 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
382 ; let final_details = tidy_details {md_binds = []}
385 -- and the answer is ...
386 ; return (HscRecomp pcs_final
389 stub_h_exists stub_c_exists
393 myParseModule dflags src_filename
394 = do -------------------------- Parser ----------------
395 showPass dflags "Parser"
398 buf <- hGetStringBuffer True{-expand tabs-} src_filename
400 let glaexts | dopt Opt_GlasgowExts dflags = 1#
403 case parseModule buf PState{ bol = 0#, atbol = 1#,
404 context = [], glasgow_exts = glaexts,
405 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
407 PFailed err -> do { hPutStrLn stderr (showSDoc err);
408 freeStringBuffer buf;
411 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
413 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
415 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
416 (ppSourceStats False rdr_module) ;
418 return (Just rdr_module)
419 -- ToDo: free the string buffer later.
423 myCoreToStg dflags this_mod tidy_binds
425 () <- coreBindsSize tidy_binds `seq` return ()
426 -- TEMP: the above call zaps some space usage allocated by the
427 -- simplifier, which for reasons I don't understand, persists
428 -- thoroughout code generation
430 stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
432 (stg_binds2, cost_centre_info)
433 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
435 let env_rhs :: CgInfoEnv
436 env_rhs = mkNameEnv [ (idName bndr, CgInfo (stgRhsArity rhs) caf_info)
437 | (bind,_) <- stg_binds2,
439 | stgBindHasCafRefs bind = MayHaveCafRefs
440 | otherwise = NoCafRefs,
441 (bndr,rhs) <- stgBindPairs bind ]
443 return (stg_binds2, cost_centre_info, env_rhs)
445 stgBindPairs (StgNonRec _ b r) = [(b,r)]
446 stgBindPairs (StgRec _ prs) = prs
452 %************************************************************************
454 \subsection{Compiling a do-statement}
456 %************************************************************************
464 -> PersistentCompilerState -- IN: persistent compiler state
465 -> InteractiveContext -- Context for compiling
466 -> String -- The statement
467 -> Bool -- just treat it as an expression
468 -> IO ( PersistentCompilerState,
474 When the UnlinkedBCOExpr is linked you get an HValue of type
476 When you run it you get a list of HValues that should be
477 the same length as the list of names; add them to the ClosureEnv.
479 A naked expression returns a singleton Name [it].
481 What you type The IO [HValue] that hscStmt returns
482 ------------- ------------------------------------
483 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
486 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
489 expr (of IO type) ==> expr >>= \ v -> return [v]
490 [NB: result not printed] bindings: [it]
493 expr (of non-IO type,
494 result showable) ==> let v = expr in print v >> return [v]
497 expr (of non-IO type,
498 result not showable) ==> error
501 hscStmt dflags hst hit pcs0 icontext stmt just_expr
505 ic_type_env = type_env,
506 ic_module = scope_mod } = icontext
508 do { maybe_stmt <- hscParseStmt dflags stmt
510 Nothing -> return (pcs0, Nothing)
511 Just parsed_stmt -> do {
513 let { notExprStmt (ExprStmt _ _ _) = False;
517 if (just_expr && notExprStmt parsed_stmt)
518 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
519 return (pcs0, Nothing)
523 (pcs1, print_unqual, maybe_renamed_stmt)
524 <- renameStmt dflags hit hst pcs0 scope_mod
525 iNTERACTIVE rn_env parsed_stmt
527 ; case maybe_renamed_stmt of
528 Nothing -> return (pcs0, Nothing)
529 Just (bound_names, rn_stmt) -> do {
534 then case rn_stmt of { (ExprStmt e _ _, decls) ->
535 typecheckExpr dflags pcs1 hst type_env
536 print_unqual iNTERACTIVE (e,decls) }
537 else typecheckStmt dflags pcs1 hst type_env
538 print_unqual iNTERACTIVE bound_names rn_stmt
540 ; case maybe_tc_return of
541 Nothing -> return (pcs0, Nothing)
542 Just (pcs2, tc_expr, bound_ids, ty) -> do {
545 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
548 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
550 -- Tidy it (temporary, until coreSat does cloning)
551 ; tidy_expr <- tidyCoreExpr simpl_expr
553 -- Prepare for codegen
554 ; prepd_expr <- corePrepExpr dflags tidy_expr
557 ; bcos <- coreExprToBCOs dflags prepd_expr
560 -- Make all the bound ids "global" ids, now that
561 -- they're notionally top-level bindings. This is
562 -- important: otherwise when we come to compile an expression
563 -- using these ids later, the byte code generator will consider
564 -- the occurrences to be free rather than global.
565 global_bound_ids = map globaliseId bound_ids;
566 globaliseId id = setGlobalIdDetails id VanillaGlobal
568 ; return (pcs2, Just (global_bound_ids, ty, bcos))
572 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
573 hscParseStmt dflags str
574 = do -------------------------- Parser ----------------
575 showPass dflags "Parser"
578 buf <- stringToStringBuffer str
580 let glaexts | dopt Opt_GlasgowExts dflags = 1#
583 case parseStmt buf PState{ bol = 0#, atbol = 1#,
584 context = [], glasgow_exts = glaexts,
585 loc = mkSrcLoc SLIT("<interactive>") 1 } of {
587 PFailed err -> do { hPutStrLn stderr (showSDoc err);
588 -- Not yet implemented in <4.11 freeStringBuffer buf;
591 -- no stmt: the line consisted of just space or comments
592 POk _ Nothing -> return Nothing;
594 POk _ (Just rdr_stmt) -> do {
596 --ToDo: can't free the string buffer until we've finished this
597 -- compilation sweep and all the identifiers have gone away.
598 --freeStringBuffer buf;
599 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
600 return (Just rdr_stmt)
605 %************************************************************************
607 \subsection{Getting information about an identifer}
609 %************************************************************************
613 hscThing -- like hscStmt, but deals with a single identifier
617 -> PersistentCompilerState -- IN: persistent compiler state
618 -> InteractiveContext -- Context for compiling
619 -> String -- The identifier
620 -> IO ( PersistentCompilerState,
623 hscThing dflags hst hit pcs0 icontext str
627 ic_module = scope_mod } = icontext
629 maybe_rdr_name <- myParseIdentifier dflags str
630 case maybe_rdr_name of {
631 Nothing -> return (pcs0, []);
634 -- if the identifier is a constructor (begins with an
635 -- upper-case letter), then we need to consider both
636 -- constructor and type class identifiers.
638 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
639 | otherwise = [ rdr_name ]
641 occ = rdrNameOcc rdr_name
642 tccls_occ = setOccNameSpace occ tcClsName
643 tccls_name = setRdrNameOcc rdr_name tccls_occ
645 (pcs, unqual, maybe_rn_result) <-
646 renameRdrName dflags hit hst pcs0 scope_mod scope_mod
649 case maybe_rn_result of {
650 Nothing -> return (pcs, []);
651 Just (names, decls) -> do {
653 maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
657 Nothing -> return (pcs, []);
659 let maybe_ty_things = map (lookupType hst (pcs_PTE pcs)) names
661 return (pcs, catMaybes maybe_ty_things) }
664 myParseIdentifier dflags str
665 = do buf <- stringToStringBuffer str
667 let glaexts | dopt Opt_GlasgowExts dflags = 1#
670 case parseIdentifier buf
671 PState{ bol = 0#, atbol = 1#,
672 context = [], glasgow_exts = glaexts,
673 loc = mkSrcLoc SLIT("<interactive>") 1 } of
675 PFailed err -> do { hPutStrLn stderr (showSDoc err);
676 freeStringBuffer buf;
679 POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
680 return (Just rdr_name) }
684 %************************************************************************
686 \subsection{Initial persistent state}
688 %************************************************************************
691 initPersistentCompilerState :: IO PersistentCompilerState
692 initPersistentCompilerState
693 = do prs <- initPersistentRenamerState
695 PCS { pcs_PIT = emptyIfaceTable,
696 pcs_PTE = wiredInThingEnv,
697 pcs_insts = emptyInstEnv,
698 pcs_rules = emptyRuleBase,
703 initPersistentRenamerState :: IO PersistentRenamerState
704 = do us <- mkSplitUniqSupply 'r'
706 PRS { prsOrig = NameSupply { nsUniqs = us,
707 nsNames = initOrigNames,
709 prsDecls = (emptyNameEnv, 0),
710 prsInsts = (emptyBag, 0),
711 prsRules = (emptyBag, 0),
716 initOrigNames :: FiniteMap (ModuleName,OccName) Name
718 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
720 grab names = foldl add emptyFM names
722 = addToFM env (moduleName (nameModule name), nameOccName name) name