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 ( PState(..), ParseResult(..) )
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 )
61 import CoreUtils ( coreBindsSize )
62 import CoreTidy ( tidyCorePgm )
63 import CorePrep ( corePrepPgm )
65 import CoreToStg ( coreToStg )
66 import SimplStg ( stg2stg )
67 import CodeGen ( codeGen )
68 import CodeOutput ( codeOutput )
70 import Module ( ModuleName, moduleName, mkHomeModule )
72 import DriverState ( v_HCHeader )
73 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
74 import Util ( unJust )
75 import UniqSupply ( mkSplitUniqSupply )
77 import Bag ( consBag, emptyBag )
79 import HscStats ( ppSourceStats )
81 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
82 import OccName ( OccName )
83 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
84 import NameEnv ( emptyNameEnv, mkNameEnv )
85 import Module ( Module )
87 import IOExts ( newIORef, readIORef, writeIORef,
91 import Maybe ( isJust, fromJust )
94 import MkExternalCore ( emitExternalCore )
98 %************************************************************************
100 \subsection{The main compiler pipeline}
102 %************************************************************************
106 -- compilation failed
107 = HscFail PersistentCompilerState -- updated PCS
108 -- concluded that it wasn't necessary
109 | HscNoRecomp PersistentCompilerState -- updated PCS
110 ModDetails -- new details (HomeSymbolTable additions)
111 ModIface -- new iface (if any compilation was done)
113 | HscRecomp PersistentCompilerState -- updated PCS
114 ModDetails -- new details (HomeSymbolTable additions)
115 ModIface -- new iface (if any compilation was done)
116 Bool -- stub_h exists
117 Bool -- stub_c exists
119 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
121 (Maybe ()) -- no interpreted code whatsoever
124 -- no errors or warnings; the individual passes
125 -- (parse/rename/typecheck) print messages themselves
131 -> ModuleLocation -- location info
132 -> Bool -- True <=> source unchanged
133 -> Bool -- True <=> have an object file (for msgs only)
134 -> Maybe ModIface -- old interface, if available
135 -> HomeSymbolTable -- for home module ModDetails
137 -> PersistentCompilerState -- IN: persistent compiler state
140 hscMain ghci_mode dflags mod location source_unchanged have_object
141 maybe_old_iface hst hit pcs
142 = {-# SCC "hscMain" #-}
144 showPass dflags ("Checking old interface for hs = "
145 ++ show (ml_hs_file location)
146 ++ ", hspp = " ++ show (ml_hspp_file location));
148 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
149 <- _scc_ "checkOldIface"
150 checkOldIface ghci_mode dflags hit hst pcs mod (ml_hi_file location)
151 source_unchanged maybe_old_iface;
154 return (HscFail pcs_ch)
157 let no_old_iface = not (isJust maybe_checked_iface)
158 what_next | recomp_reqd || no_old_iface = hscRecomp
159 | otherwise = hscNoRecomp
161 what_next ghci_mode dflags have_object mod location
162 maybe_checked_iface hst hit pcs_ch
166 -- we definitely expect to have the old interface available
167 hscNoRecomp ghci_mode dflags have_object
168 mod location (Just old_iface) hst hit pcs_ch
169 | ghci_mode == OneShot
171 when (verbosity dflags > 0) $
172 hPutStrLn stderr "compilation IS NOT required";
173 let { bomb = panic "hscNoRecomp:OneShot" };
174 return (HscNoRecomp pcs_ch bomb bomb)
178 when (verbosity dflags >= 1) $
179 hPutStrLn stderr ("Skipping " ++
180 showModMsg have_object mod location);
183 (pcs_cl, closure_errs, cl_hs_decls)
184 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
186 return (HscFail pcs_cl)
191 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
193 case maybe_tc_result of {
194 Nothing -> return (HscFail pcs_cl);
195 Just (pcs_tc, new_details) ->
197 return (HscNoRecomp pcs_tc new_details old_iface)
200 hscRecomp ghci_mode dflags have_object
201 mod location maybe_checked_iface hst hit pcs_ch
203 -- what target are we shooting for?
204 ; let toInterp = dopt_HscLang dflags == HscInterpreted
205 ; let toNothing = dopt_HscLang dflags == HscNothing
207 ; when (ghci_mode /= OneShot && verbosity dflags >= 1) $
208 hPutStrLn stderr ("Compiling " ++
209 showModMsg (not toInterp) mod location);
214 ; maybe_parsed <- myParseModule dflags
215 (unJust "hscRecomp:hspp" (ml_hspp_file location))
216 ; case maybe_parsed of {
217 Nothing -> return (HscFail pcs_ch);
218 Just rdr_module -> do {
219 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
224 ; (pcs_rn, print_unqual, maybe_rn_result)
226 renameModule dflags ghci_mode hit hst pcs_ch this_mod rdr_module
227 ; case maybe_rn_result of {
228 Nothing -> return (HscFail pcs_ch);
229 Just (dont_discard, new_iface, rn_result) -> do {
236 typecheckModule dflags pcs_rn hst print_unqual rn_result
237 ; case maybe_tc_result of {
238 Nothing -> return (HscFail pcs_ch);
239 Just (pcs_tc, tc_result) -> do {
244 ; (ds_details, foreign_stuff)
246 deSugar dflags pcs_tc hst this_mod print_unqual tc_result
249 <- _scc_ "pcs_middle"
250 if ghci_mode == OneShot
251 then do init_pcs <- initPersistentCompilerState
252 init_prs <- initPersistentRenamerState
254 rules = pcs_rules pcs_tc
255 orig_tc = prsOrig (pcs_PRS pcs_tc)
256 new_prs = init_prs{ prsOrig=orig_tc }
258 orig_tc `seq` rules `seq` new_prs `seq`
259 return init_pcs{ pcs_PRS = new_prs,
263 -- alive at this point:
274 core2core dflags pcs_middle hst dont_discard ds_details
279 ; cg_info_ref <- newIORef Nothing ;
280 ; let cg_info :: CgInfoEnv
281 cg_info = unsafePerformIO $ do {
282 maybe_cg_env <- readIORef cg_info_ref ;
284 Just env -> return env
285 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
286 return emptyNameEnv } }
287 -- cg_info_ref will be filled in just after restOfCodeGeneration
288 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
290 ; (pcs_simpl, tidy_details)
292 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
294 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
295 else return pcs_simpl
297 -- alive at this point:
301 ; emitExternalCore dflags new_iface tidy_details
303 ; let final_details = tidy_details {md_binds = []}
304 ; final_details `seq` return ()
307 -- PREPARE FOR CODE GENERATION
309 -- Do saturation and convert to A-normal form
310 ; prepd_details <- _scc_ "CorePrep"
311 corePrepPgm dflags tidy_details
314 -- CONVERT TO STG and COMPLETE CODE GENERATION
317 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
319 local_tycons = typeEnvTyCons env_tc
320 local_classes = typeEnvClasses env_tc
322 imported_module_names = map ideclName (hsModuleImports rdr_module)
324 mod_name_to_Module nm
325 = do m <- findModule nm ; return (fst (fromJust m))
327 (h_code, c_code, headers, fe_binders) = foreign_stuff
329 -- turn the list of headers requested in foreign import
330 -- declarations into a string suitable for emission into generated
335 . map (\fname -> "#include \"" ++ _UNPK_ fname ++ "\"")
339 -- ...and add the string to the headers requested via command line
342 ; fhdrs <- readIORef v_HCHeader
343 ; writeIORef v_HCHeader (fhdrs ++ foreign_headers)
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 icontext parsed_stmt
532 ; case maybe_renamed_stmt of
533 Nothing -> return (pcs0, Nothing)
534 Just (bound_names, rn_stmt) -> do {
539 then case rn_stmt of { (ExprStmt e _ _, decls) ->
540 typecheckExpr dflags pcs1 hst (ic_type_env icontext)
541 print_unqual iNTERACTIVE (e,decls) }
542 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
543 print_unqual iNTERACTIVE bound_names rn_stmt
545 ; case maybe_tc_return of
546 Nothing -> return (pcs0, Nothing)
547 Just (pcs2, tc_expr, bound_ids, ty) -> do {
550 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
553 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
555 -- Tidy it (temporary, until coreSat does cloning)
556 ; tidy_expr <- tidyCoreExpr simpl_expr
558 -- Prepare for codegen
559 ; prepd_expr <- corePrepExpr dflags tidy_expr
562 ; bcos <- coreExprToBCOs dflags prepd_expr
565 -- Make all the bound ids "global" ids, now that
566 -- they're notionally top-level bindings. This is
567 -- important: otherwise when we come to compile an expression
568 -- using these ids later, the byte code generator will consider
569 -- the occurrences to be free rather than global.
570 global_bound_ids = map globaliseId bound_ids;
571 globaliseId id = setGlobalIdDetails id VanillaGlobal
573 ; return (pcs2, Just (global_bound_ids, ty, bcos))
577 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
578 hscParseStmt dflags str
579 = do -------------------------- Parser ----------------
580 showPass dflags "Parser"
583 buf <- stringToStringBuffer str
585 let glaexts | dopt Opt_GlasgowExts dflags = 1#
588 case parseStmt buf PState{ bol = 0#, atbol = 1#,
589 context = [], glasgow_exts = glaexts,
590 loc = mkSrcLoc SLIT("<interactive>") 1 } of {
592 PFailed err -> do { hPutStrLn stderr (showSDoc err);
593 -- Not yet implemented in <4.11 freeStringBuffer buf;
596 -- no stmt: the line consisted of just space or comments
597 POk _ Nothing -> return Nothing;
599 POk _ (Just rdr_stmt) -> do {
601 --ToDo: can't free the string buffer until we've finished this
602 -- compilation sweep and all the identifiers have gone away.
603 --freeStringBuffer buf;
604 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
605 return (Just rdr_stmt)
610 %************************************************************************
612 \subsection{Getting information about an identifer}
614 %************************************************************************
618 hscThing -- like hscStmt, but deals with a single identifier
622 -> PersistentCompilerState -- IN: persistent compiler state
623 -> InteractiveContext -- Context for compiling
624 -> String -- The identifier
625 -> IO ( PersistentCompilerState,
628 hscThing dflags hst hit pcs0 ic str
629 = do 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 ic rdr_names
648 case maybe_rn_result of {
649 Nothing -> return (pcs, []);
650 Just (names, decls) -> do {
652 maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
656 Nothing -> return (pcs, []);
659 | isLocalName n = lookupNameEnv (ic_type_env ic) n
660 | otherwise = lookupType hst (pcs_PTE pcs) n
662 maybe_ty_things = map do_lookup names
664 return (pcs, catMaybes maybe_ty_things) }
667 myParseIdentifier dflags str
668 = do buf <- stringToStringBuffer str
670 let glaexts | dopt Opt_GlasgowExts dflags = 1#
673 case parseIdentifier buf
674 PState{ bol = 0#, atbol = 1#,
675 context = [], glasgow_exts = glaexts,
676 loc = mkSrcLoc SLIT("<interactive>") 1 } of
678 PFailed err -> do { hPutStrLn stderr (showSDoc err);
679 freeStringBuffer buf;
682 POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
683 return (Just rdr_name) }
687 %************************************************************************
689 \subsection{Find all the things defined in a module}
691 %************************************************************************
699 -> PersistentCompilerState -- IN: persistent compiler state
700 -> Module -- module to inspect
701 -> Bool -- grab just the exports, or the whole toplev
702 -> IO (PersistentCompilerState, Maybe [TyThing])
704 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
706 -- slurp the interface if necessary
707 (pcs1, print_unqual, maybe_rn_stuff)
708 <- slurpIface dflags hit hst pcs0 mod;
710 case maybe_rn_stuff of {
711 Nothing -> return (pcs0, Nothing);
712 Just (names, rn_decls) -> do {
714 -- Typecheck the declarations
716 typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
719 Nothing -> return (pcs1, Nothing);
723 | exports_only = names
725 let { iface = fromJust (lookupModuleEnv hit mod);
726 env = fromJust (mi_globals iface);
727 range = rdrEnvElts env;
729 -- grab all the things from the global env that are locally def'd
730 nub [ n | elts <- range, GRE n LocalDef _ <- elts ];
734 ty_things = map (fromJust . lookupType hst pte) all_names;
738 return (pcs2, Just ty_things)
743 %************************************************************************
745 \subsection{Initial persistent state}
747 %************************************************************************
750 initPersistentCompilerState :: IO PersistentCompilerState
751 initPersistentCompilerState
752 = do prs <- initPersistentRenamerState
754 PCS { pcs_PIT = emptyIfaceTable,
755 pcs_PTE = wiredInThingEnv,
756 pcs_insts = emptyInstEnv,
757 pcs_rules = emptyRuleBase,
762 initPersistentRenamerState :: IO PersistentRenamerState
763 = do us <- mkSplitUniqSupply 'r'
765 PRS { prsOrig = NameSupply { nsUniqs = us,
766 nsNames = initOrigNames,
768 prsDecls = (emptyNameEnv, 0),
769 prsInsts = (emptyBag, 0),
770 prsRules = foldr add_rule (emptyBag, 0) builtinRules,
775 add_rule (name,rule) (rules, n_rules)
776 = (gated_decl `consBag` rules, n_rules+1)
778 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
779 mod = nameModule name
780 rdr_name = mkRdrOrig (moduleName mod) (nameOccName name)
781 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
783 initOrigNames :: FiniteMap (ModuleName,OccName) Name
785 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
787 grab names = foldl add emptyFM names
789 = addToFM env (moduleName (nameModule name), nameOccName name) name