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 HscTypes ( InteractiveContext(..) )
30 import PrelNames ( iNTERACTIVE )
31 import StringBuffer ( stringToStringBuffer )
32 import FastString ( mkFastString )
33 import Maybes ( catMaybes )
38 import RdrName ( mkRdrOrig )
40 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
41 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
43 import Lex ( PState(..), ParseResult(..) )
44 import SrcLoc ( mkSrcLoc )
45 import Finder ( findModule )
46 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
47 import Rules ( emptyRuleBase )
48 import PrelInfo ( wiredInThingEnv, wiredInThings )
49 import PrelRules ( builtinRules )
50 import PrelNames ( knownKeyNames )
51 import MkIface ( mkFinalIface )
53 import InstEnv ( emptyInstEnv )
56 import CoreUtils ( coreBindsSize )
57 import CoreTidy ( tidyCorePgm )
58 import CorePrep ( corePrepPgm )
60 import CoreToStg ( coreToStg )
61 import SimplStg ( stg2stg )
62 import CodeGen ( codeGen )
63 import CodeOutput ( codeOutput )
65 import Module ( ModuleName, moduleName, mkHomeModule,
68 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
69 import Util ( unJust )
70 import UniqSupply ( mkSplitUniqSupply )
72 import Bag ( consBag, emptyBag )
74 import HscStats ( ppSourceStats )
76 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
77 import OccName ( OccName )
78 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
79 import NameEnv ( emptyNameEnv, mkNameEnv )
80 import Module ( Module )
82 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
85 import Maybe ( isJust, fromJust )
88 import MkExternalCore ( emitExternalCore )
92 %************************************************************************
94 \subsection{The main compiler pipeline}
96 %************************************************************************
100 -- compilation failed
101 = HscFail PersistentCompilerState -- updated PCS
102 -- concluded that it wasn't necessary
103 | HscNoRecomp PersistentCompilerState -- updated PCS
104 ModDetails -- new details (HomeSymbolTable additions)
105 ModIface -- new iface (if any compilation was done)
107 | HscRecomp PersistentCompilerState -- updated PCS
108 ModDetails -- new details (HomeSymbolTable additions)
109 ModIface -- new iface (if any compilation was done)
110 Bool -- stub_h exists
111 Bool -- stub_c exists
113 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
115 (Maybe ()) -- no interpreted code whatsoever
118 -- no errors or warnings; the individual passes
119 -- (parse/rename/typecheck) print messages themselves
125 -> ModuleLocation -- location info
126 -> Bool -- True <=> source unchanged
127 -> Bool -- True <=> have an object file (for msgs only)
128 -> Maybe ModIface -- old interface, if available
129 -> HomeSymbolTable -- for home module ModDetails
131 -> PersistentCompilerState -- IN: persistent compiler state
134 hscMain ghci_mode dflags mod location source_unchanged have_object
135 maybe_old_iface hst hit pcs
136 = {-# SCC "hscMain" #-}
138 showPass dflags ("Checking old interface for hs = "
139 ++ show (ml_hs_file location)
140 ++ ", hspp = " ++ show (ml_hspp_file location));
142 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
143 <- _scc_ "checkOldIface"
144 checkOldIface ghci_mode dflags hit hst pcs (ml_hi_file location)
145 source_unchanged maybe_old_iface;
148 return (HscFail pcs_ch)
151 let no_old_iface = not (isJust maybe_checked_iface)
152 what_next | recomp_reqd || no_old_iface = hscRecomp
153 | otherwise = hscNoRecomp
155 what_next ghci_mode dflags have_object mod location
156 maybe_checked_iface hst hit pcs_ch
160 -- we definitely expect to have the old interface available
161 hscNoRecomp ghci_mode dflags have_object
162 mod location (Just old_iface) hst hit pcs_ch
163 | ghci_mode == OneShot
165 when (verbosity dflags > 0) $
166 hPutStrLn stderr "compilation IS NOT required";
167 let { bomb = panic "hscNoRecomp:OneShot" };
168 return (HscNoRecomp pcs_ch bomb bomb)
172 when (verbosity dflags >= 1) $
173 hPutStrLn stderr ("Skipping " ++
174 compMsg have_object mod location);
177 (pcs_cl, closure_errs, cl_hs_decls)
178 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
180 return (HscFail pcs_cl)
185 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
187 case maybe_tc_result of {
188 Nothing -> return (HscFail pcs_cl);
189 Just (pcs_tc, new_details) ->
191 return (HscNoRecomp pcs_tc new_details old_iface)
194 compMsg use_object mod location =
195 mod_str ++ replicate (max 0 (16 - length mod_str)) ' '
196 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
198 then unJust "hscRecomp" (ml_obj_file location)
201 where mod_str = moduleUserString mod
204 hscRecomp ghci_mode dflags have_object
205 mod location maybe_checked_iface hst hit pcs_ch
207 -- what target are we shooting for?
208 ; let toInterp = dopt_HscLang dflags == HscInterpreted
209 ; let toNothing = dopt_HscLang dflags == HscNothing
211 ; when (ghci_mode /= OneShot && verbosity dflags >= 1) $
212 hPutStrLn stderr ("Compiling " ++
213 compMsg (not toInterp) mod location);
218 ; maybe_parsed <- myParseModule dflags
219 (unJust "hscRecomp:hspp" (ml_hspp_file location))
220 ; case maybe_parsed of {
221 Nothing -> return (HscFail pcs_ch);
222 Just rdr_module -> do {
223 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
228 ; (pcs_rn, print_unqualified, maybe_rn_result)
230 renameModule dflags hit hst pcs_ch this_mod rdr_module
231 ; case maybe_rn_result of {
232 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
233 Just (is_exported, new_iface, rn_hs_decls) -> do {
235 -- In interactive mode, we don't want to discard any top-level
236 -- entities at all (eg. do not inline them away during
237 -- simplification), and retain them all in the TypeEnv so they are
238 -- available from the command line.
240 -- isGlobalName separates the user-defined top-level names from those
241 -- introduced by the type checker.
243 ; let dont_discard | ghci_mode == Interactive = isGlobalName
244 | otherwise = is_exported
251 typecheckModule dflags pcs_rn hst new_iface
252 print_unqualified rn_hs_decls
253 ; case maybe_tc_result of {
254 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
255 Just (pcs_tc, tc_result) -> do {
260 ; (ds_details, foreign_stuff)
262 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
265 <- _scc_ "pcs_middle"
266 if ghci_mode == OneShot
267 then do init_pcs <- initPersistentCompilerState
268 init_prs <- initPersistentRenamerState
270 rules = pcs_rules pcs_tc
271 orig_tc = prsOrig (pcs_PRS pcs_tc)
272 new_prs = init_prs{ prsOrig=orig_tc }
274 orig_tc `seq` rules `seq` new_prs `seq`
275 return init_pcs{ pcs_PRS = new_prs,
279 -- alive at this point:
290 core2core dflags pcs_middle hst dont_discard ds_details
295 ; cg_info_ref <- newIORef Nothing ;
296 ; let cg_info :: CgInfoEnv
297 cg_info = unsafePerformIO $ do {
298 maybe_cg_env <- readIORef cg_info_ref ;
300 Just env -> return env
301 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
302 return emptyNameEnv } }
303 -- cg_info_ref will be filled in just after restOfCodeGeneration
304 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
306 ; (pcs_simpl, tidy_details)
308 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
310 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
311 else return pcs_simpl
313 -- alive at this point:
317 ; emitExternalCore dflags new_iface tidy_details
319 ; let final_details = tidy_details {md_binds = []}
320 ; final_details `seq` return ()
323 -- PREPARE FOR CODE GENERATION
325 -- Do saturation and convert to A-normal form
326 ; prepd_details <- _scc_ "CorePrep"
327 corePrepPgm dflags tidy_details
330 -- CONVERT TO STG and COMPLETE CODE GENERATION
333 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
335 local_tycons = typeEnvTyCons env_tc
336 local_classes = typeEnvClasses env_tc
338 imported_module_names = map ideclName (hsModuleImports rdr_module)
340 mod_name_to_Module nm
341 = do m <- findModule nm ; return (fst (fromJust m))
343 (h_code,c_code,fe_binders) = foreign_stuff
345 ; imported_modules <- mapM mod_name_to_Module imported_module_names
347 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
351 ----------------- Generate byte code ------------------
352 (bcos,itbl_env) <- byteCodeGen dflags binds
353 local_tycons local_classes
355 -- Fill in the code-gen info
356 writeIORef cg_info_ref (Just emptyNameEnv)
358 ------------------ BUILD THE NEW ModIface ------------
359 final_iface <- _scc_ "MkFinalIface"
360 mkFinalIface ghci_mode dflags location
361 maybe_checked_iface new_iface tidy_details
363 return ( False, False, Just (bcos,itbl_env), final_iface )
365 then error "GHC not compiled with interpreter"
369 ----------------- Convert to STG ------------------
370 (stg_binds, cost_centre_info, stg_back_end_info)
372 myCoreToStg dflags this_mod binds
374 -- Fill in the code-gen info for the earlier tidyCorePgm
375 writeIORef cg_info_ref (Just stg_back_end_info)
377 ------------------ BUILD THE NEW ModIface ------------
378 final_iface <- _scc_ "MkFinalIface"
379 mkFinalIface ghci_mode dflags location
380 maybe_checked_iface new_iface tidy_details
383 return (False, False, Nothing, final_iface)
385 ------------------ Code generation ------------------
386 abstractC <- _scc_ "CodeGen"
387 codeGen dflags this_mod imported_modules
388 cost_centre_info fe_binders
389 local_tycons stg_binds
391 ------------------ Code output -----------------------
392 (stub_h_exists, stub_c_exists)
393 <- codeOutput dflags this_mod [] --local_tycons
395 c_code h_code abstractC
397 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
399 -- and the answer is ...
400 ; return (HscRecomp pcs_final
403 stub_h_exists stub_c_exists
407 myParseModule dflags src_filename
408 = do -------------------------- Parser ----------------
409 showPass dflags "Parser"
412 buf <- hGetStringBuffer True{-expand tabs-} src_filename
414 let glaexts | dopt Opt_GlasgowExts dflags = 1#
417 case parseModule buf PState{ bol = 0#, atbol = 1#,
418 context = [], glasgow_exts = glaexts,
419 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
421 PFailed err -> do { hPutStrLn stderr (showSDoc err);
422 freeStringBuffer buf;
425 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
427 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
429 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
430 (ppSourceStats False rdr_module) ;
432 return (Just rdr_module)
433 -- ToDo: free the string buffer later.
437 myCoreToStg dflags this_mod tidy_binds
439 () <- coreBindsSize tidy_binds `seq` return ()
440 -- TEMP: the above call zaps some space usage allocated by the
441 -- simplifier, which for reasons I don't understand, persists
442 -- thoroughout code generation -- JRS
444 -- This is still necessary. -- SDM (10 Dec 2001)
446 stg_binds <- _scc_ "Core2Stg"
447 coreToStg dflags tidy_binds
449 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
450 stg2stg dflags this_mod stg_binds
452 let env_rhs :: CgInfoEnv
453 env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
454 | (bind,_) <- stg_binds2,
456 | stgBindHasCafRefs bind = MayHaveCafRefs
457 | otherwise = NoCafRefs,
458 bndr <- stgBinders bind ]
460 return (stg_binds2, cost_centre_info, env_rhs)
464 %************************************************************************
466 \subsection{Compiling a do-statement}
468 %************************************************************************
476 -> PersistentCompilerState -- IN: persistent compiler state
477 -> InteractiveContext -- Context for compiling
478 -> String -- The statement
479 -> Bool -- just treat it as an expression
480 -> IO ( PersistentCompilerState,
486 When the UnlinkedBCOExpr is linked you get an HValue of type
488 When you run it you get a list of HValues that should be
489 the same length as the list of names; add them to the ClosureEnv.
491 A naked expression returns a singleton Name [it].
493 What you type The IO [HValue] that hscStmt returns
494 ------------- ------------------------------------
495 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
498 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
501 expr (of IO type) ==> expr >>= \ v -> return [v]
502 [NB: result not printed] bindings: [it]
505 expr (of non-IO type,
506 result showable) ==> let v = expr in print v >> return [v]
509 expr (of non-IO type,
510 result not showable) ==> error
513 hscStmt dflags hst hit pcs0 icontext stmt just_expr
514 = do { maybe_stmt <- hscParseStmt dflags stmt
516 Nothing -> return (pcs0, Nothing)
517 Just parsed_stmt -> do {
519 let { notExprStmt (ExprStmt _ _ _) = False;
523 if (just_expr && notExprStmt parsed_stmt)
524 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
525 return (pcs0, Nothing)
529 (pcs1, print_unqual, maybe_renamed_stmt)
530 <- renameStmt dflags hit hst pcs0
531 iNTERACTIVE icontext parsed_stmt
533 ; case maybe_renamed_stmt of
534 Nothing -> return (pcs0, Nothing)
535 Just (bound_names, rn_stmt) -> do {
540 then case rn_stmt of { (ExprStmt e _ _, decls) ->
541 typecheckExpr dflags pcs1 hst (ic_type_env icontext)
542 print_unqual iNTERACTIVE (e,decls) }
543 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
544 print_unqual iNTERACTIVE bound_names rn_stmt
546 ; case maybe_tc_return of
547 Nothing -> return (pcs0, Nothing)
548 Just (pcs2, tc_expr, bound_ids, ty) -> do {
551 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
554 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
556 -- Tidy it (temporary, until coreSat does cloning)
557 ; tidy_expr <- tidyCoreExpr simpl_expr
559 -- Prepare for codegen
560 ; prepd_expr <- corePrepExpr dflags tidy_expr
563 ; bcos <- coreExprToBCOs dflags prepd_expr
566 -- Make all the bound ids "global" ids, now that
567 -- they're notionally top-level bindings. This is
568 -- important: otherwise when we come to compile an expression
569 -- using these ids later, the byte code generator will consider
570 -- the occurrences to be free rather than global.
571 global_bound_ids = map globaliseId bound_ids;
572 globaliseId id = setGlobalIdDetails id VanillaGlobal
574 ; return (pcs2, Just (global_bound_ids, ty, bcos))
578 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
579 hscParseStmt dflags str
580 = do -------------------------- Parser ----------------
581 showPass dflags "Parser"
584 buf <- stringToStringBuffer str
586 let glaexts | dopt Opt_GlasgowExts dflags = 1#
589 case parseStmt buf PState{ bol = 0#, atbol = 1#,
590 context = [], glasgow_exts = glaexts,
591 loc = mkSrcLoc SLIT("<interactive>") 1 } of {
593 PFailed err -> do { hPutStrLn stderr (showSDoc err);
594 -- Not yet implemented in <4.11 freeStringBuffer buf;
597 -- no stmt: the line consisted of just space or comments
598 POk _ Nothing -> return Nothing;
600 POk _ (Just rdr_stmt) -> do {
602 --ToDo: can't free the string buffer until we've finished this
603 -- compilation sweep and all the identifiers have gone away.
604 --freeStringBuffer buf;
605 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
606 return (Just rdr_stmt)
611 %************************************************************************
613 \subsection{Getting information about an identifer}
615 %************************************************************************
619 hscThing -- like hscStmt, but deals with a single identifier
623 -> PersistentCompilerState -- IN: persistent compiler state
624 -> InteractiveContext -- Context for compiling
625 -> String -- The identifier
626 -> IO ( PersistentCompilerState,
629 hscThing dflags hst hit pcs0 icontext str
630 = do maybe_rdr_name <- myParseIdentifier dflags str
631 case maybe_rdr_name of {
632 Nothing -> return (pcs0, []);
635 -- if the identifier is a constructor (begins with an
636 -- upper-case letter), then we need to consider both
637 -- constructor and type class identifiers.
639 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
640 | otherwise = [ rdr_name ]
642 occ = rdrNameOcc rdr_name
643 tccls_occ = setOccNameSpace occ tcClsName
644 tccls_name = setRdrNameOcc rdr_name tccls_occ
646 (pcs, unqual, maybe_rn_result) <-
647 renameRdrName dflags hit hst pcs0 iNTERACTIVE icontext rdr_names
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 = foldr add_rule (emptyBag, 0) builtinRules,
716 add_rule (name,rule) (rules, n_rules)
717 = (gated_decl `consBag` rules, n_rules+1)
719 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
720 mod = nameModule name
721 rdr_name = mkRdrOrig (moduleName mod) (nameOccName name)
722 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
724 initOrigNames :: FiniteMap (ModuleName,OccName) Name
726 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
728 grab names = foldl add emptyFM names
730 = addToFM env (moduleName (nameModule name), nameOccName name) name