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"
18 import ByteCodeGen ( byteCodeGen )
19 import CoreTidy ( tidyCoreExpr )
20 import CorePrep ( corePrepExpr )
21 import Rename ( renameStmt, renameRdrName )
22 import RdrName ( rdrNameOcc, setRdrNameOcc )
23 import RdrHsSyn ( RdrNameStmt )
24 import OccName ( dataName, tcClsName,
25 occNameSpace, setOccNameSpace )
27 import Id ( Id, idName, setGlobalIdDetails )
28 import IdInfo ( GlobalIdDetails(VanillaGlobal) )
29 import Name ( isLocalName )
30 import NameEnv ( lookupNameEnv )
31 import PrelNames ( iNTERACTIVE )
32 import StringBuffer ( stringToStringBuffer )
33 import FastString ( mkFastString )
34 import Maybes ( catMaybes )
39 import RdrName ( mkRdrOrig )
41 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
42 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
44 import Lex ( PState(..), ParseResult(..) )
45 import SrcLoc ( mkSrcLoc )
46 import Finder ( findModule )
47 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
48 import Rules ( emptyRuleBase )
49 import PrelInfo ( wiredInThingEnv, wiredInThings )
50 import PrelRules ( builtinRules )
51 import PrelNames ( knownKeyNames )
52 import MkIface ( mkFinalIface )
54 import InstEnv ( emptyInstEnv )
57 import CoreUtils ( coreBindsSize )
58 import CoreTidy ( tidyCorePgm )
59 import CorePrep ( corePrepPgm )
61 import CoreToStg ( coreToStg )
62 import SimplStg ( stg2stg )
63 import CodeGen ( codeGen )
64 import CodeOutput ( codeOutput )
66 import Module ( ModuleName, moduleName, mkHomeModule,
69 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
70 import Util ( unJust )
71 import UniqSupply ( mkSplitUniqSupply )
73 import Bag ( consBag, emptyBag )
75 import HscStats ( ppSourceStats )
77 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
78 import OccName ( OccName )
79 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
80 import NameEnv ( emptyNameEnv, mkNameEnv )
81 import Module ( Module )
83 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
86 import Maybe ( isJust, fromJust )
89 import MkExternalCore ( emitExternalCore )
93 %************************************************************************
95 \subsection{The main compiler pipeline}
97 %************************************************************************
101 -- compilation failed
102 = HscFail PersistentCompilerState -- updated PCS
103 -- concluded that it wasn't necessary
104 | HscNoRecomp PersistentCompilerState -- updated PCS
105 ModDetails -- new details (HomeSymbolTable additions)
106 ModIface -- new iface (if any compilation was done)
108 | HscRecomp PersistentCompilerState -- updated PCS
109 ModDetails -- new details (HomeSymbolTable additions)
110 ModIface -- new iface (if any compilation was done)
111 Bool -- stub_h exists
112 Bool -- stub_c exists
114 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
116 (Maybe ()) -- no interpreted code whatsoever
119 -- no errors or warnings; the individual passes
120 -- (parse/rename/typecheck) print messages themselves
126 -> ModuleLocation -- location info
127 -> Bool -- True <=> source unchanged
128 -> Bool -- True <=> have an object file (for msgs only)
129 -> Maybe ModIface -- old interface, if available
130 -> HomeSymbolTable -- for home module ModDetails
132 -> PersistentCompilerState -- IN: persistent compiler state
135 hscMain ghci_mode dflags mod location source_unchanged have_object
136 maybe_old_iface hst hit pcs
137 = {-# SCC "hscMain" #-}
139 showPass dflags ("Checking old interface for hs = "
140 ++ show (ml_hs_file location)
141 ++ ", hspp = " ++ show (ml_hspp_file location));
143 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
144 <- _scc_ "checkOldIface"
145 checkOldIface ghci_mode dflags hit hst pcs (ml_hi_file location)
146 source_unchanged maybe_old_iface;
149 return (HscFail pcs_ch)
152 let no_old_iface = not (isJust maybe_checked_iface)
153 what_next | recomp_reqd || no_old_iface = hscRecomp
154 | otherwise = hscNoRecomp
156 what_next ghci_mode dflags have_object mod location
157 maybe_checked_iface hst hit pcs_ch
161 -- we definitely expect to have the old interface available
162 hscNoRecomp ghci_mode dflags have_object
163 mod location (Just old_iface) hst hit pcs_ch
164 | ghci_mode == OneShot
166 when (verbosity dflags > 0) $
167 hPutStrLn stderr "compilation IS NOT required";
168 let { bomb = panic "hscNoRecomp:OneShot" };
169 return (HscNoRecomp pcs_ch bomb bomb)
173 when (verbosity dflags >= 1) $
174 hPutStrLn stderr ("Skipping " ++
175 showModMsg have_object mod location);
178 (pcs_cl, closure_errs, cl_hs_decls)
179 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
181 return (HscFail pcs_cl)
186 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
188 case maybe_tc_result of {
189 Nothing -> return (HscFail pcs_cl);
190 Just (pcs_tc, new_details) ->
192 return (HscNoRecomp pcs_tc new_details old_iface)
195 hscRecomp ghci_mode dflags have_object
196 mod location maybe_checked_iface hst hit pcs_ch
198 -- what target are we shooting for?
199 ; let toInterp = dopt_HscLang dflags == HscInterpreted
200 ; let toNothing = dopt_HscLang dflags == HscNothing
202 ; when (ghci_mode /= OneShot && verbosity dflags >= 1) $
203 hPutStrLn stderr ("Compiling " ++
204 showModMsg (not toInterp) mod location);
209 ; maybe_parsed <- myParseModule dflags
210 (unJust "hscRecomp:hspp" (ml_hspp_file location))
211 ; case maybe_parsed of {
212 Nothing -> return (HscFail pcs_ch);
213 Just rdr_module -> do {
214 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
219 ; (pcs_rn, print_unqualified, maybe_rn_result)
221 renameModule dflags hit hst pcs_ch this_mod rdr_module
222 ; case maybe_rn_result of {
223 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
224 Just (is_exported, new_iface, rn_hs_decls) -> do {
226 -- In interactive mode, we don't want to discard any top-level
227 -- entities at all (eg. do not inline them away during
228 -- simplification), and retain them all in the TypeEnv so they are
229 -- available from the command line.
231 -- isGlobalName separates the user-defined top-level names from those
232 -- introduced by the type checker.
234 ; let dont_discard | ghci_mode == Interactive = isGlobalName
235 | otherwise = is_exported
242 typecheckModule dflags pcs_rn hst new_iface
243 print_unqualified rn_hs_decls
244 ; case maybe_tc_result of {
245 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
246 Just (pcs_tc, tc_result) -> do {
251 ; (ds_details, foreign_stuff)
253 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
256 <- _scc_ "pcs_middle"
257 if ghci_mode == OneShot
258 then do init_pcs <- initPersistentCompilerState
259 init_prs <- initPersistentRenamerState
261 rules = pcs_rules pcs_tc
262 orig_tc = prsOrig (pcs_PRS pcs_tc)
263 new_prs = init_prs{ prsOrig=orig_tc }
265 orig_tc `seq` rules `seq` new_prs `seq`
266 return init_pcs{ pcs_PRS = new_prs,
270 -- alive at this point:
281 core2core dflags pcs_middle hst dont_discard ds_details
286 ; cg_info_ref <- newIORef Nothing ;
287 ; let cg_info :: CgInfoEnv
288 cg_info = unsafePerformIO $ do {
289 maybe_cg_env <- readIORef cg_info_ref ;
291 Just env -> return env
292 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
293 return emptyNameEnv } }
294 -- cg_info_ref will be filled in just after restOfCodeGeneration
295 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
297 ; (pcs_simpl, tidy_details)
299 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
301 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
302 else return pcs_simpl
304 -- alive at this point:
308 ; emitExternalCore dflags new_iface tidy_details
310 ; let final_details = tidy_details {md_binds = []}
311 ; final_details `seq` return ()
314 -- PREPARE FOR CODE GENERATION
316 -- Do saturation and convert to A-normal form
317 ; prepd_details <- _scc_ "CorePrep"
318 corePrepPgm dflags tidy_details
321 -- CONVERT TO STG and COMPLETE CODE GENERATION
324 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
326 local_tycons = typeEnvTyCons env_tc
327 local_classes = typeEnvClasses env_tc
329 imported_module_names = map ideclName (hsModuleImports rdr_module)
331 mod_name_to_Module nm
332 = do m <- findModule nm ; return (fst (fromJust m))
334 (h_code,c_code,fe_binders) = foreign_stuff
336 ; imported_modules <- mapM mod_name_to_Module imported_module_names
338 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
342 ----------------- Generate byte code ------------------
343 (bcos,itbl_env) <- byteCodeGen dflags binds
344 local_tycons local_classes
346 -- Fill in the code-gen info
347 writeIORef cg_info_ref (Just emptyNameEnv)
349 ------------------ BUILD THE NEW ModIface ------------
350 final_iface <- _scc_ "MkFinalIface"
351 mkFinalIface ghci_mode dflags location
352 maybe_checked_iface new_iface tidy_details
354 return ( False, False, Just (bcos,itbl_env), final_iface )
356 then error "GHC not compiled with interpreter"
360 ----------------- Convert to STG ------------------
361 (stg_binds, cost_centre_info, stg_back_end_info)
363 myCoreToStg dflags this_mod binds
365 -- Fill in the code-gen info for the earlier tidyCorePgm
366 writeIORef cg_info_ref (Just stg_back_end_info)
368 ------------------ BUILD THE NEW ModIface ------------
369 final_iface <- _scc_ "MkFinalIface"
370 mkFinalIface ghci_mode dflags location
371 maybe_checked_iface new_iface tidy_details
374 return (False, False, Nothing, final_iface)
376 ------------------ Code generation ------------------
377 abstractC <- _scc_ "CodeGen"
378 codeGen dflags this_mod imported_modules
379 cost_centre_info fe_binders
380 local_tycons stg_binds
382 ------------------ Code output -----------------------
383 (stub_h_exists, stub_c_exists)
384 <- codeOutput dflags this_mod [] --local_tycons
386 c_code h_code abstractC
388 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
390 -- and the answer is ...
391 ; return (HscRecomp pcs_final
394 stub_h_exists stub_c_exists
398 myParseModule dflags src_filename
399 = do -------------------------- Parser ----------------
400 showPass dflags "Parser"
403 buf <- hGetStringBuffer True{-expand tabs-} src_filename
405 let glaexts | dopt Opt_GlasgowExts dflags = 1#
408 case parseModule buf PState{ bol = 0#, atbol = 1#,
409 context = [], glasgow_exts = glaexts,
410 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
412 PFailed err -> do { hPutStrLn stderr (showSDoc err);
413 freeStringBuffer buf;
416 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
418 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
420 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
421 (ppSourceStats False rdr_module) ;
423 return (Just rdr_module)
424 -- ToDo: free the string buffer later.
428 myCoreToStg dflags this_mod tidy_binds
430 () <- coreBindsSize tidy_binds `seq` return ()
431 -- TEMP: the above call zaps some space usage allocated by the
432 -- simplifier, which for reasons I don't understand, persists
433 -- thoroughout code generation -- JRS
435 -- This is still necessary. -- SDM (10 Dec 2001)
437 stg_binds <- _scc_ "Core2Stg"
438 coreToStg dflags tidy_binds
440 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
441 stg2stg dflags this_mod stg_binds
443 let env_rhs :: CgInfoEnv
444 env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
445 | (bind,_) <- stg_binds2,
447 | stgBindHasCafRefs bind = MayHaveCafRefs
448 | otherwise = NoCafRefs,
449 bndr <- stgBinders bind ]
451 return (stg_binds2, cost_centre_info, env_rhs)
455 %************************************************************************
457 \subsection{Compiling a do-statement}
459 %************************************************************************
467 -> PersistentCompilerState -- IN: persistent compiler state
468 -> InteractiveContext -- Context for compiling
469 -> String -- The statement
470 -> Bool -- just treat it as an expression
471 -> IO ( PersistentCompilerState,
477 When the UnlinkedBCOExpr is linked you get an HValue of type
479 When you run it you get a list of HValues that should be
480 the same length as the list of names; add them to the ClosureEnv.
482 A naked expression returns a singleton Name [it].
484 What you type The IO [HValue] that hscStmt returns
485 ------------- ------------------------------------
486 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
489 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
492 expr (of IO type) ==> expr >>= \ v -> return [v]
493 [NB: result not printed] bindings: [it]
496 expr (of non-IO type,
497 result showable) ==> let v = expr in print v >> return [v]
500 expr (of non-IO type,
501 result not showable) ==> error
504 hscStmt dflags hst hit pcs0 icontext stmt just_expr
505 = do { maybe_stmt <- hscParseStmt dflags stmt
507 Nothing -> return (pcs0, Nothing)
508 Just parsed_stmt -> do {
510 let { notExprStmt (ExprStmt _ _ _) = False;
514 if (just_expr && notExprStmt parsed_stmt)
515 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
516 return (pcs0, Nothing)
520 (pcs1, print_unqual, maybe_renamed_stmt)
521 <- renameStmt dflags hit hst pcs0 icontext parsed_stmt
523 ; case maybe_renamed_stmt of
524 Nothing -> return (pcs0, Nothing)
525 Just (bound_names, rn_stmt) -> do {
530 then case rn_stmt of { (ExprStmt e _ _, decls) ->
531 typecheckExpr dflags pcs1 hst (ic_type_env icontext)
532 print_unqual iNTERACTIVE (e,decls) }
533 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
534 print_unqual iNTERACTIVE bound_names rn_stmt
536 ; case maybe_tc_return of
537 Nothing -> return (pcs0, Nothing)
538 Just (pcs2, tc_expr, bound_ids, ty) -> do {
541 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
544 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
546 -- Tidy it (temporary, until coreSat does cloning)
547 ; tidy_expr <- tidyCoreExpr simpl_expr
549 -- Prepare for codegen
550 ; prepd_expr <- corePrepExpr dflags tidy_expr
553 ; bcos <- coreExprToBCOs dflags prepd_expr
556 -- Make all the bound ids "global" ids, now that
557 -- they're notionally top-level bindings. This is
558 -- important: otherwise when we come to compile an expression
559 -- using these ids later, the byte code generator will consider
560 -- the occurrences to be free rather than global.
561 global_bound_ids = map globaliseId bound_ids;
562 globaliseId id = setGlobalIdDetails id VanillaGlobal
564 ; return (pcs2, Just (global_bound_ids, ty, bcos))
568 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
569 hscParseStmt dflags str
570 = do -------------------------- Parser ----------------
571 showPass dflags "Parser"
574 buf <- stringToStringBuffer str
576 let glaexts | dopt Opt_GlasgowExts dflags = 1#
579 case parseStmt buf PState{ bol = 0#, atbol = 1#,
580 context = [], glasgow_exts = glaexts,
581 loc = mkSrcLoc SLIT("<interactive>") 1 } of {
583 PFailed err -> do { hPutStrLn stderr (showSDoc err);
584 -- Not yet implemented in <4.11 freeStringBuffer buf;
587 -- no stmt: the line consisted of just space or comments
588 POk _ Nothing -> return Nothing;
590 POk _ (Just rdr_stmt) -> do {
592 --ToDo: can't free the string buffer until we've finished this
593 -- compilation sweep and all the identifiers have gone away.
594 --freeStringBuffer buf;
595 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
596 return (Just rdr_stmt)
601 %************************************************************************
603 \subsection{Getting information about an identifer}
605 %************************************************************************
609 hscThing -- like hscStmt, but deals with a single identifier
613 -> PersistentCompilerState -- IN: persistent compiler state
614 -> InteractiveContext -- Context for compiling
615 -> String -- The identifier
616 -> IO ( PersistentCompilerState,
619 hscThing dflags hst hit pcs0 ic str
620 = do maybe_rdr_name <- myParseIdentifier dflags str
621 case maybe_rdr_name of {
622 Nothing -> return (pcs0, []);
625 -- if the identifier is a constructor (begins with an
626 -- upper-case letter), then we need to consider both
627 -- constructor and type class identifiers.
629 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
630 | otherwise = [ rdr_name ]
632 occ = rdrNameOcc rdr_name
633 tccls_occ = setOccNameSpace occ tcClsName
634 tccls_name = setRdrNameOcc rdr_name tccls_occ
636 (pcs, unqual, maybe_rn_result) <-
637 renameRdrName dflags hit hst pcs0 ic rdr_names
639 case maybe_rn_result of {
640 Nothing -> return (pcs, []);
641 Just (names, decls) -> do {
643 maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
647 Nothing -> return (pcs, []);
650 | isLocalName n = lookupNameEnv (ic_type_env ic) n
651 | otherwise = lookupType hst (pcs_PTE pcs) n
653 maybe_ty_things = map do_lookup names
655 return (pcs, catMaybes maybe_ty_things) }
658 myParseIdentifier dflags str
659 = do buf <- stringToStringBuffer str
661 let glaexts | dopt Opt_GlasgowExts dflags = 1#
664 case parseIdentifier buf
665 PState{ bol = 0#, atbol = 1#,
666 context = [], glasgow_exts = glaexts,
667 loc = mkSrcLoc SLIT("<interactive>") 1 } of
669 PFailed err -> do { hPutStrLn stderr (showSDoc err);
670 freeStringBuffer buf;
673 POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
674 return (Just rdr_name) }
678 %************************************************************************
680 \subsection{Initial persistent state}
682 %************************************************************************
685 initPersistentCompilerState :: IO PersistentCompilerState
686 initPersistentCompilerState
687 = do prs <- initPersistentRenamerState
689 PCS { pcs_PIT = emptyIfaceTable,
690 pcs_PTE = wiredInThingEnv,
691 pcs_insts = emptyInstEnv,
692 pcs_rules = emptyRuleBase,
697 initPersistentRenamerState :: IO PersistentRenamerState
698 = do us <- mkSplitUniqSupply 'r'
700 PRS { prsOrig = NameSupply { nsUniqs = us,
701 nsNames = initOrigNames,
703 prsDecls = (emptyNameEnv, 0),
704 prsInsts = (emptyBag, 0),
705 prsRules = foldr add_rule (emptyBag, 0) builtinRules,
710 add_rule (name,rule) (rules, n_rules)
711 = (gated_decl `consBag` rules, n_rules+1)
713 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
714 mod = nameModule name
715 rdr_name = mkRdrOrig (moduleName mod) (nameOccName name)
716 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
718 initOrigNames :: FiniteMap (ModuleName,OccName) Name
720 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
722 grab names = foldl add emptyFM names
724 = addToFM env (moduleName (nameModule name), nameOccName name) name