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,
10 hscStmt, hscThing, hscModuleContents,
12 initPersistentCompilerState ) where
14 #include "HsVersions.h"
18 import ByteCodeGen ( byteCodeGen )
19 import CoreTidy ( tidyCoreExpr )
20 import CorePrep ( corePrepExpr )
21 import Rename ( renameStmt, renameRdrName, slurpIface )
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 Module ( lookupModuleEnv )
32 import RdrName ( rdrEnvElts )
33 import PrelNames ( iNTERACTIVE )
34 import StringBuffer ( stringToStringBuffer )
35 import FastString ( mkFastString )
36 import Maybes ( catMaybes )
43 import RdrName ( mkRdrOrig )
45 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
46 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
48 import Lex ( ParseResult(..), ExtFlags(..), mkPState )
49 import SrcLoc ( mkSrcLoc )
50 import Finder ( findModule )
51 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
52 import Rules ( emptyRuleBase )
53 import PrelInfo ( wiredInThingEnv, wiredInThings )
54 import PrelRules ( builtinRules )
55 import PrelNames ( knownKeyNames )
56 import MkIface ( mkFinalIface )
58 import InstEnv ( emptyInstEnv )
60 import Flattening ( flatten, flattenExpr )
62 import CoreUtils ( coreBindsSize )
63 import CoreTidy ( tidyCorePgm )
64 import CorePrep ( corePrepPgm )
66 import CoreToStg ( coreToStg )
67 import SimplStg ( stg2stg )
68 import CodeGen ( codeGen )
69 import CodeOutput ( codeOutput )
71 import Module ( ModuleName, moduleName, mkHomeModule )
73 import DriverState ( v_HCHeader )
74 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
75 import Util ( unJust )
76 import UniqSupply ( mkSplitUniqSupply )
78 import Bag ( consBag, emptyBag )
80 import HscStats ( ppSourceStats )
82 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
83 import OccName ( OccName )
84 import Name ( Name, nameModule, nameOccName, getName )
85 import NameEnv ( emptyNameEnv, mkNameEnv )
86 import Module ( Module )
88 import IOExts ( newIORef, readIORef, writeIORef,
92 import Maybe ( isJust, fromJust )
95 import MkExternalCore ( emitExternalCore )
99 %************************************************************************
101 \subsection{The main compiler pipeline}
103 %************************************************************************
107 -- compilation failed
108 = HscFail PersistentCompilerState -- updated PCS
109 -- concluded that it wasn't necessary
110 | HscNoRecomp PersistentCompilerState -- updated PCS
111 ModDetails -- new details (HomeSymbolTable additions)
112 ModIface -- new iface (if any compilation was done)
114 | HscRecomp PersistentCompilerState -- updated PCS
115 ModDetails -- new details (HomeSymbolTable additions)
116 ModIface -- new iface (if any compilation was done)
117 Bool -- stub_h exists
118 Bool -- stub_c exists
120 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
122 (Maybe ()) -- no interpreted code whatsoever
125 -- no errors or warnings; the individual passes
126 -- (parse/rename/typecheck) print messages themselves
132 -> ModuleLocation -- location info
133 -> Bool -- True <=> source unchanged
134 -> Bool -- True <=> have an object file (for msgs only)
135 -> Maybe ModIface -- old interface, if available
136 -> HomeSymbolTable -- for home module ModDetails
138 -> PersistentCompilerState -- IN: persistent compiler state
141 hscMain ghci_mode dflags mod location source_unchanged have_object
142 maybe_old_iface hst hit pcs
143 = {-# SCC "hscMain" #-}
145 showPass dflags ("Checking old interface for hs = "
146 ++ show (ml_hs_file location)
147 ++ ", hspp = " ++ show (ml_hspp_file location));
149 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
150 <- _scc_ "checkOldIface"
151 checkOldIface ghci_mode dflags hit hst pcs mod (ml_hi_file location)
152 source_unchanged maybe_old_iface;
155 return (HscFail pcs_ch)
158 let no_old_iface = not (isJust maybe_checked_iface)
159 what_next | recomp_reqd || no_old_iface = hscRecomp
160 | otherwise = hscNoRecomp
162 what_next ghci_mode dflags have_object mod location
163 maybe_checked_iface hst hit pcs_ch
167 -- we definitely expect to have the old interface available
168 hscNoRecomp ghci_mode dflags have_object
169 mod location (Just old_iface) hst hit pcs_ch
170 | ghci_mode == OneShot
172 when (verbosity dflags > 0) $
173 hPutStrLn stderr "compilation IS NOT required";
174 let { bomb = panic "hscNoRecomp:OneShot" };
175 return (HscNoRecomp pcs_ch bomb bomb)
179 when (verbosity dflags >= 1) $
180 hPutStrLn stderr ("Skipping " ++
181 showModMsg have_object mod location);
184 (pcs_cl, closure_errs, cl_hs_decls)
185 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
187 return (HscFail pcs_cl)
192 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
194 case maybe_tc_result of {
195 Nothing -> return (HscFail pcs_cl);
196 Just (pcs_tc, new_details) ->
198 return (HscNoRecomp pcs_tc new_details old_iface)
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 (ghci_mode /= OneShot && verbosity dflags >= 1) $
209 hPutStrLn stderr ("Compiling " ++
210 showModMsg (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_unqual, maybe_rn_result)
227 renameModule dflags ghci_mode hit hst pcs_ch this_mod rdr_module
228 ; case maybe_rn_result of {
229 Nothing -> return (HscFail pcs_ch);
230 Just (dont_discard, new_iface, rn_result) -> do {
237 typecheckModule dflags pcs_rn hst print_unqual rn_result
238 ; case maybe_tc_result of {
239 Nothing -> return (HscFail pcs_ch);
240 Just (pcs_tc, tc_result) -> do {
245 ; (ds_details, foreign_stuff)
247 deSugar dflags pcs_tc hst this_mod print_unqual tc_result
253 <- _scc_ "Flattening"
254 flatten dflags pcs_tc hst ds_details
257 <- _scc_ "pcs_middle"
258 if ghci_mode == OneShot
259 then do init_pcs <- initPersistentCompilerState
260 init_prs <- initPersistentRenamerState
262 rules = pcs_rules pcs_tc
263 orig_tc = prsOrig (pcs_PRS pcs_tc)
264 new_prs = init_prs{ prsOrig=orig_tc }
266 orig_tc `seq` rules `seq` new_prs `seq`
267 return init_pcs{ pcs_PRS = new_prs,
271 -- alive at this point:
282 core2core dflags pcs_middle hst dont_discard flat_details
287 ; cg_info_ref <- newIORef Nothing ;
288 ; let cg_info :: CgInfoEnv
289 cg_info = unsafePerformIO $ do {
290 maybe_cg_env <- readIORef cg_info_ref ;
292 Just env -> return env
293 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
294 return emptyNameEnv } }
295 -- cg_info_ref will be filled in just after restOfCodeGeneration
296 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
298 ; (pcs_simpl, tidy_details)
300 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
302 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
303 else return pcs_simpl
305 -- alive at this point:
309 ; emitExternalCore dflags new_iface tidy_details
311 ; let final_details = tidy_details {md_binds = []}
312 ; final_details `seq` return ()
315 -- PREPARE FOR CODE GENERATION
317 -- Do saturation and convert to A-normal form
318 ; prepd_details <- _scc_ "CorePrep"
319 corePrepPgm dflags tidy_details
322 -- CONVERT TO STG and COMPLETE CODE GENERATION
325 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
327 local_tycons = typeEnvTyCons env_tc
328 local_classes = typeEnvClasses env_tc
330 imported_module_names = map ideclName (hsModuleImports rdr_module)
332 mod_name_to_Module nm
333 = do m <- findModule nm ; return (fst (fromJust m))
335 (h_code, c_code, headers, fe_binders) = foreign_stuff
337 -- turn the list of headers requested in foreign import
338 -- declarations into a string suitable for emission into generated
343 . map (\fname -> "#include \"" ++ _UNPK_ fname ++ "\"")
347 -- ...and add the string to the headers requested via command line
350 ; fhdrs <- readIORef v_HCHeader
351 ; writeIORef v_HCHeader (fhdrs ++ foreign_headers)
353 ; imported_modules <- mapM mod_name_to_Module imported_module_names
355 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
359 ----------------- Generate byte code ------------------
360 (bcos,itbl_env) <- byteCodeGen dflags binds
361 local_tycons local_classes
363 -- Fill in the code-gen info
364 writeIORef cg_info_ref (Just emptyNameEnv)
366 ------------------ BUILD THE NEW ModIface ------------
367 final_iface <- _scc_ "MkFinalIface"
368 mkFinalIface ghci_mode dflags location
369 maybe_checked_iface new_iface tidy_details
371 return ( False, False, Just (bcos,itbl_env), final_iface )
373 then error "GHC not compiled with interpreter"
377 ----------------- Convert to STG ------------------
378 (stg_binds, cost_centre_info, stg_back_end_info)
380 myCoreToStg dflags this_mod binds
382 -- Fill in the code-gen info for the earlier tidyCorePgm
383 writeIORef cg_info_ref (Just stg_back_end_info)
385 ------------------ BUILD THE NEW ModIface ------------
386 final_iface <- _scc_ "MkFinalIface"
387 mkFinalIface ghci_mode dflags location
388 maybe_checked_iface new_iface tidy_details
391 return (False, False, Nothing, final_iface)
393 ------------------ Code generation ------------------
394 abstractC <- _scc_ "CodeGen"
395 codeGen dflags this_mod imported_modules
396 cost_centre_info fe_binders
397 local_tycons stg_binds
399 ------------------ Code output -----------------------
400 (stub_h_exists, stub_c_exists)
401 <- codeOutput dflags this_mod [] --local_tycons
403 c_code h_code abstractC
405 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
407 -- and the answer is ...
408 ; return (HscRecomp pcs_final
411 stub_h_exists stub_c_exists
415 myParseModule dflags src_filename
416 = do -------------------------- Parser ----------------
417 showPass dflags "Parser"
420 buf <- hGetStringBuffer True{-expand tabs-} src_filename
422 let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
423 parrEF = dopt Opt_PArr dflags}
424 loc = mkSrcLoc (_PK_ src_filename) 1
426 case parseModule buf (mkPState loc exts) of {
428 PFailed err -> do { hPutStrLn stderr (showSDoc err);
429 freeStringBuffer buf;
432 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
434 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
436 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
437 (ppSourceStats False rdr_module) ;
439 return (Just rdr_module)
440 -- ToDo: free the string buffer later.
444 myCoreToStg dflags this_mod tidy_binds
446 () <- coreBindsSize tidy_binds `seq` return ()
447 -- TEMP: the above call zaps some space usage allocated by the
448 -- simplifier, which for reasons I don't understand, persists
449 -- thoroughout code generation -- JRS
451 -- This is still necessary. -- SDM (10 Dec 2001)
453 stg_binds <- _scc_ "Core2Stg"
454 coreToStg dflags tidy_binds
456 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
457 stg2stg dflags this_mod stg_binds
459 let env_rhs :: CgInfoEnv
460 env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
461 | (bind,_) <- stg_binds2,
463 | stgBindHasCafRefs bind = MayHaveCafRefs
464 | otherwise = NoCafRefs,
465 bndr <- stgBinders bind ]
467 return (stg_binds2, cost_centre_info, env_rhs)
471 %************************************************************************
473 \subsection{Compiling a do-statement}
475 %************************************************************************
483 -> PersistentCompilerState -- IN: persistent compiler state
484 -> InteractiveContext -- Context for compiling
485 -> String -- The statement
486 -> Bool -- just treat it as an expression
487 -> IO ( PersistentCompilerState,
493 When the UnlinkedBCOExpr is linked you get an HValue of type
495 When you run it you get a list of HValues that should be
496 the same length as the list of names; add them to the ClosureEnv.
498 A naked expression returns a singleton Name [it].
500 What you type The IO [HValue] that hscStmt returns
501 ------------- ------------------------------------
502 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
505 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
508 expr (of IO type) ==> expr >>= \ v -> return [v]
509 [NB: result not printed] bindings: [it]
512 expr (of non-IO type,
513 result showable) ==> let v = expr in print v >> return [v]
516 expr (of non-IO type,
517 result not showable) ==> error
520 hscStmt dflags hst hit pcs0 icontext stmt just_expr
521 = do { maybe_stmt <- hscParseStmt dflags stmt
523 Nothing -> return (pcs0, Nothing)
524 Just parsed_stmt -> do {
526 let { notExprStmt (ExprStmt _ _ _) = False;
530 if (just_expr && notExprStmt parsed_stmt)
531 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
532 return (pcs0, Nothing)
536 (pcs1, print_unqual, maybe_renamed_stmt)
537 <- renameStmt dflags hit hst pcs0 icontext parsed_stmt
539 ; case maybe_renamed_stmt of
540 Nothing -> return (pcs0, Nothing)
541 Just (bound_names, rn_stmt) -> do {
546 then case rn_stmt of { (ExprStmt e _ _, decls) ->
547 typecheckExpr dflags pcs1 hst (ic_type_env icontext)
548 print_unqual iNTERACTIVE (e,decls) }
549 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
550 print_unqual iNTERACTIVE bound_names rn_stmt
552 ; case maybe_tc_return of
553 Nothing -> return (pcs0, Nothing)
554 Just (pcs2, tc_expr, bound_ids, ty) -> do {
557 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
560 ; flat_expr <- flattenExpr dflags pcs2 hst ds_expr
563 ; simpl_expr <- simplifyExpr dflags pcs2 hst flat_expr
565 -- Tidy it (temporary, until coreSat does cloning)
566 ; tidy_expr <- tidyCoreExpr simpl_expr
568 -- Prepare for codegen
569 ; prepd_expr <- corePrepExpr dflags tidy_expr
572 ; bcos <- coreExprToBCOs dflags prepd_expr
575 -- Make all the bound ids "global" ids, now that
576 -- they're notionally top-level bindings. This is
577 -- important: otherwise when we come to compile an expression
578 -- using these ids later, the byte code generator will consider
579 -- the occurrences to be free rather than global.
580 global_bound_ids = map globaliseId bound_ids;
581 globaliseId id = setGlobalIdDetails id VanillaGlobal
583 ; return (pcs2, Just (global_bound_ids, ty, bcos))
587 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
588 hscParseStmt dflags str
589 = do -------------------------- Parser ----------------
590 showPass dflags "Parser"
593 buf <- stringToStringBuffer str
595 let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
596 parrEF = dopt Opt_PArr dflags}
597 loc = mkSrcLoc SLIT("<interactive>") 1
599 case parseStmt buf (mkPState loc exts) of {
601 PFailed err -> do { hPutStrLn stderr (showSDoc err);
602 -- Not yet implemented in <4.11 freeStringBuffer buf;
605 -- no stmt: the line consisted of just space or comments
606 POk _ Nothing -> return Nothing;
608 POk _ (Just rdr_stmt) -> do {
610 --ToDo: can't free the string buffer until we've finished this
611 -- compilation sweep and all the identifiers have gone away.
612 --freeStringBuffer buf;
613 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
614 return (Just rdr_stmt)
619 %************************************************************************
621 \subsection{Getting information about an identifer}
623 %************************************************************************
627 hscThing -- like hscStmt, but deals with a single identifier
631 -> PersistentCompilerState -- IN: persistent compiler state
632 -> InteractiveContext -- Context for compiling
633 -> String -- The identifier
634 -> IO ( PersistentCompilerState,
637 hscThing dflags hst hit pcs0 ic str
638 = do maybe_rdr_name <- myParseIdentifier dflags str
639 case maybe_rdr_name of {
640 Nothing -> return (pcs0, []);
643 -- if the identifier is a constructor (begins with an
644 -- upper-case letter), then we need to consider both
645 -- constructor and type class identifiers.
647 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
648 | otherwise = [ rdr_name ]
650 occ = rdrNameOcc rdr_name
651 tccls_occ = setOccNameSpace occ tcClsName
652 tccls_name = setRdrNameOcc rdr_name tccls_occ
654 (pcs, unqual, maybe_rn_result) <-
655 renameRdrName dflags hit hst pcs0 ic rdr_names
657 case maybe_rn_result of {
658 Nothing -> return (pcs, []);
659 Just (names, decls) -> do {
661 maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
665 Nothing -> return (pcs, []);
668 | isLocalName n = lookupNameEnv (ic_type_env ic) n
669 | otherwise = lookupType hst (pcs_PTE pcs) n
671 maybe_ty_things = map do_lookup names
673 return (pcs, catMaybes maybe_ty_things) }
676 myParseIdentifier dflags str
677 = do buf <- stringToStringBuffer str
679 let exts = ExtFlags {glasgowExtsEF = dopt Opt_GlasgowExts dflags,
680 parrEF = dopt Opt_PArr dflags}
681 loc = mkSrcLoc SLIT("<interactive>") 1
683 case parseIdentifier buf (mkPState loc exts) of
685 PFailed err -> do { hPutStrLn stderr (showSDoc err);
686 freeStringBuffer buf;
689 POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
690 return (Just rdr_name) }
694 %************************************************************************
696 \subsection{Find all the things defined in a module}
698 %************************************************************************
706 -> PersistentCompilerState -- IN: persistent compiler state
707 -> Module -- module to inspect
708 -> Bool -- grab just the exports, or the whole toplev
709 -> IO (PersistentCompilerState, Maybe [TyThing])
711 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
713 -- slurp the interface if necessary
714 (pcs1, print_unqual, maybe_rn_stuff)
715 <- slurpIface dflags hit hst pcs0 mod;
717 case maybe_rn_stuff of {
718 Nothing -> return (pcs0, Nothing);
719 Just (names, rn_decls) -> do {
721 -- Typecheck the declarations
723 typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
726 Nothing -> return (pcs1, Nothing);
730 | exports_only = names
732 let { iface = fromJust (lookupModuleEnv hit mod);
733 env = fromJust (mi_globals iface);
734 range = rdrEnvElts env;
736 -- grab all the things from the global env that are locally def'd
737 nub [ n | elts <- range, GRE n LocalDef _ <- elts ];
741 ty_things = map (fromJust . lookupType hst pte) all_names;
745 return (pcs2, Just ty_things)
750 %************************************************************************
752 \subsection{Initial persistent state}
754 %************************************************************************
757 initPersistentCompilerState :: IO PersistentCompilerState
758 initPersistentCompilerState
759 = do prs <- initPersistentRenamerState
761 PCS { pcs_PIT = emptyIfaceTable,
762 pcs_PTE = wiredInThingEnv,
763 pcs_insts = emptyInstEnv,
764 pcs_rules = emptyRuleBase,
769 initPersistentRenamerState :: IO PersistentRenamerState
770 = do us <- mkSplitUniqSupply 'r'
772 PRS { prsOrig = NameSupply { nsUniqs = us,
773 nsNames = initOrigNames,
775 prsDecls = (emptyNameEnv, 0),
776 prsInsts = (emptyBag, 0),
777 prsRules = foldr add_rule (emptyBag, 0) builtinRules,
782 add_rule (name,rule) (rules, n_rules)
783 = (gated_decl `consBag` rules, n_rules+1)
785 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
786 mod = nameModule name
787 rdr_name = mkRdrOrig (moduleName mod) (nameOccName name)
788 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
790 initOrigNames :: FiniteMap (ModuleName,OccName) Name
792 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
794 grab names = foldl add emptyFM names
796 = addToFM env (moduleName (nameModule name), nameOccName name) name