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 RdrName ( rdrEnvElts )
32 import PrelNames ( iNTERACTIVE )
33 import StringBuffer ( stringToStringBuffer )
34 import FastString ( mkFastString )
35 import Maybes ( catMaybes )
42 import RdrName ( mkRdrOrig )
44 import IdInfo ( CafInfo(..), CgInfoEnv, CgInfo(..) )
45 import StringBuffer ( hGetStringBuffer, freeStringBuffer )
47 import Lex ( PState(..), ParseResult(..) )
48 import SrcLoc ( mkSrcLoc )
49 import Finder ( findModule )
50 import Rename ( checkOldIface, renameModule, closeIfaceDecls )
51 import Rules ( emptyRuleBase )
52 import PrelInfo ( wiredInThingEnv, wiredInThings )
53 import PrelRules ( builtinRules )
54 import PrelNames ( knownKeyNames )
55 import MkIface ( mkFinalIface )
57 import InstEnv ( emptyInstEnv )
60 import CoreUtils ( coreBindsSize )
61 import CoreTidy ( tidyCorePgm )
62 import CorePrep ( corePrepPgm )
64 import CoreToStg ( coreToStg )
65 import SimplStg ( stg2stg )
66 import CodeGen ( codeGen )
67 import CodeOutput ( codeOutput )
69 import Module ( ModuleName, moduleName, mkHomeModule,
70 moduleUserString, lookupModuleEnv )
72 import ErrUtils ( dumpIfSet_dyn, showPass, printError )
73 import Util ( unJust )
74 import UniqSupply ( mkSplitUniqSupply )
76 import Bag ( consBag, emptyBag )
78 import HscStats ( ppSourceStats )
80 import FiniteMap ( FiniteMap, plusFM, emptyFM, addToFM )
81 import OccName ( OccName )
82 import Name ( Name, nameModule, nameOccName, getName, isGlobalName )
83 import NameEnv ( emptyNameEnv, mkNameEnv )
84 import Module ( Module )
86 import IOExts ( newIORef, readIORef, writeIORef, unsafePerformIO )
89 import Maybe ( isJust, fromJust )
92 import MkExternalCore ( emitExternalCore )
96 %************************************************************************
98 \subsection{The main compiler pipeline}
100 %************************************************************************
104 -- compilation failed
105 = HscFail PersistentCompilerState -- updated PCS
106 -- concluded that it wasn't necessary
107 | HscNoRecomp PersistentCompilerState -- updated PCS
108 ModDetails -- new details (HomeSymbolTable additions)
109 ModIface -- new iface (if any compilation was done)
111 | HscRecomp PersistentCompilerState -- updated PCS
112 ModDetails -- new details (HomeSymbolTable additions)
113 ModIface -- new iface (if any compilation was done)
114 Bool -- stub_h exists
115 Bool -- stub_c exists
117 (Maybe ([UnlinkedBCO],ItblEnv)) -- interpreted code, if any
119 (Maybe ()) -- no interpreted code whatsoever
122 -- no errors or warnings; the individual passes
123 -- (parse/rename/typecheck) print messages themselves
129 -> ModuleLocation -- location info
130 -> Bool -- True <=> source unchanged
131 -> Bool -- True <=> have an object file (for msgs only)
132 -> Maybe ModIface -- old interface, if available
133 -> HomeSymbolTable -- for home module ModDetails
135 -> PersistentCompilerState -- IN: persistent compiler state
138 hscMain ghci_mode dflags mod location source_unchanged have_object
139 maybe_old_iface hst hit pcs
140 = {-# SCC "hscMain" #-}
142 showPass dflags ("Checking old interface for hs = "
143 ++ show (ml_hs_file location)
144 ++ ", hspp = " ++ show (ml_hspp_file location));
146 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
147 <- _scc_ "checkOldIface"
148 checkOldIface ghci_mode dflags hit hst pcs mod (ml_hi_file location)
149 source_unchanged maybe_old_iface;
152 return (HscFail pcs_ch)
155 let no_old_iface = not (isJust maybe_checked_iface)
156 what_next | recomp_reqd || no_old_iface = hscRecomp
157 | otherwise = hscNoRecomp
159 what_next ghci_mode dflags have_object mod location
160 maybe_checked_iface hst hit pcs_ch
164 -- we definitely expect to have the old interface available
165 hscNoRecomp ghci_mode dflags have_object
166 mod location (Just old_iface) hst hit pcs_ch
167 | ghci_mode == OneShot
169 when (verbosity dflags > 0) $
170 hPutStrLn stderr "compilation IS NOT required";
171 let { bomb = panic "hscNoRecomp:OneShot" };
172 return (HscNoRecomp pcs_ch bomb bomb)
176 when (verbosity dflags >= 1) $
177 hPutStrLn stderr ("Skipping " ++
178 showModMsg have_object mod location);
181 (pcs_cl, closure_errs, cl_hs_decls)
182 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
184 return (HscFail pcs_cl)
189 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
191 case maybe_tc_result of {
192 Nothing -> return (HscFail pcs_cl);
193 Just (pcs_tc, new_details) ->
195 return (HscNoRecomp pcs_tc new_details old_iface)
198 hscRecomp ghci_mode dflags have_object
199 mod location maybe_checked_iface hst hit pcs_ch
201 -- what target are we shooting for?
202 ; let toInterp = dopt_HscLang dflags == HscInterpreted
203 ; let toNothing = dopt_HscLang dflags == HscNothing
205 ; when (ghci_mode /= OneShot && verbosity dflags >= 1) $
206 hPutStrLn stderr ("Compiling " ++
207 showModMsg (not toInterp) mod location);
212 ; maybe_parsed <- myParseModule dflags
213 (unJust "hscRecomp:hspp" (ml_hspp_file location))
214 ; case maybe_parsed of {
215 Nothing -> return (HscFail pcs_ch);
216 Just rdr_module -> do {
217 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
222 ; (pcs_rn, print_unqualified, maybe_rn_result)
224 renameModule dflags hit hst pcs_ch this_mod rdr_module
225 ; case maybe_rn_result of {
226 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
227 Just (is_exported, new_iface, rn_hs_decls) -> do {
229 -- In interactive mode, we don't want to discard any top-level
230 -- entities at all (eg. do not inline them away during
231 -- simplification), and retain them all in the TypeEnv so they are
232 -- available from the command line.
234 -- isGlobalName separates the user-defined top-level names from those
235 -- introduced by the type checker.
237 ; let dont_discard | ghci_mode == Interactive = isGlobalName
238 | otherwise = is_exported
245 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 <- _scc_ "pcs_middle"
260 if ghci_mode == OneShot
261 then do init_pcs <- initPersistentCompilerState
262 init_prs <- initPersistentRenamerState
264 rules = pcs_rules pcs_tc
265 orig_tc = prsOrig (pcs_PRS pcs_tc)
266 new_prs = init_prs{ prsOrig=orig_tc }
268 orig_tc `seq` rules `seq` new_prs `seq`
269 return init_pcs{ pcs_PRS = new_prs,
273 -- alive at this point:
284 core2core dflags pcs_middle hst dont_discard ds_details
289 ; cg_info_ref <- newIORef Nothing ;
290 ; let cg_info :: CgInfoEnv
291 cg_info = unsafePerformIO $ do {
292 maybe_cg_env <- readIORef cg_info_ref ;
294 Just env -> return env
295 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
296 return emptyNameEnv } }
297 -- cg_info_ref will be filled in just after restOfCodeGeneration
298 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
300 ; (pcs_simpl, tidy_details)
302 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
304 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
305 else return pcs_simpl
307 -- alive at this point:
311 ; emitExternalCore dflags new_iface tidy_details
313 ; let final_details = tidy_details {md_binds = []}
314 ; final_details `seq` return ()
317 -- PREPARE FOR CODE GENERATION
319 -- Do saturation and convert to A-normal form
320 ; prepd_details <- _scc_ "CorePrep"
321 corePrepPgm dflags tidy_details
324 -- CONVERT TO STG and COMPLETE CODE GENERATION
327 ModDetails{md_binds=binds, md_types=env_tc} = prepd_details
329 local_tycons = typeEnvTyCons env_tc
330 local_classes = typeEnvClasses env_tc
332 imported_module_names = map ideclName (hsModuleImports rdr_module)
334 mod_name_to_Module nm
335 = do m <- findModule nm ; return (fst (fromJust m))
337 (h_code,c_code,fe_binders) = foreign_stuff
339 ; imported_modules <- mapM mod_name_to_Module imported_module_names
341 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
345 ----------------- Generate byte code ------------------
346 (bcos,itbl_env) <- byteCodeGen dflags binds
347 local_tycons local_classes
349 -- Fill in the code-gen info
350 writeIORef cg_info_ref (Just emptyNameEnv)
352 ------------------ BUILD THE NEW ModIface ------------
353 final_iface <- _scc_ "MkFinalIface"
354 mkFinalIface ghci_mode dflags location
355 maybe_checked_iface new_iface tidy_details
357 return ( False, False, Just (bcos,itbl_env), final_iface )
359 then error "GHC not compiled with interpreter"
363 ----------------- Convert to STG ------------------
364 (stg_binds, cost_centre_info, stg_back_end_info)
366 myCoreToStg dflags this_mod binds
368 -- Fill in the code-gen info for the earlier tidyCorePgm
369 writeIORef cg_info_ref (Just stg_back_end_info)
371 ------------------ BUILD THE NEW ModIface ------------
372 final_iface <- _scc_ "MkFinalIface"
373 mkFinalIface ghci_mode dflags location
374 maybe_checked_iface new_iface tidy_details
377 return (False, False, Nothing, final_iface)
379 ------------------ Code generation ------------------
380 abstractC <- _scc_ "CodeGen"
381 codeGen dflags this_mod imported_modules
382 cost_centre_info fe_binders
383 local_tycons stg_binds
385 ------------------ Code output -----------------------
386 (stub_h_exists, stub_c_exists)
387 <- codeOutput dflags this_mod [] --local_tycons
389 c_code h_code abstractC
391 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
393 -- and the answer is ...
394 ; return (HscRecomp pcs_final
397 stub_h_exists stub_c_exists
401 myParseModule dflags src_filename
402 = do -------------------------- Parser ----------------
403 showPass dflags "Parser"
406 buf <- hGetStringBuffer True{-expand tabs-} src_filename
408 let glaexts | dopt Opt_GlasgowExts dflags = 1#
411 case parseModule buf PState{ bol = 0#, atbol = 1#,
412 context = [], glasgow_exts = glaexts,
413 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
415 PFailed err -> do { hPutStrLn stderr (showSDoc err);
416 freeStringBuffer buf;
419 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
421 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
423 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
424 (ppSourceStats False rdr_module) ;
426 return (Just rdr_module)
427 -- ToDo: free the string buffer later.
431 myCoreToStg dflags this_mod tidy_binds
433 () <- coreBindsSize tidy_binds `seq` return ()
434 -- TEMP: the above call zaps some space usage allocated by the
435 -- simplifier, which for reasons I don't understand, persists
436 -- thoroughout code generation -- JRS
438 -- This is still necessary. -- SDM (10 Dec 2001)
440 stg_binds <- _scc_ "Core2Stg"
441 coreToStg dflags tidy_binds
443 (stg_binds2, cost_centre_info) <- _scc_ "Core2Stg"
444 stg2stg dflags this_mod stg_binds
446 let env_rhs :: CgInfoEnv
447 env_rhs = mkNameEnv [ caf_info `seq` (idName bndr, CgInfo caf_info)
448 | (bind,_) <- stg_binds2,
450 | stgBindHasCafRefs bind = MayHaveCafRefs
451 | otherwise = NoCafRefs,
452 bndr <- stgBinders bind ]
454 return (stg_binds2, cost_centre_info, env_rhs)
458 %************************************************************************
460 \subsection{Compiling a do-statement}
462 %************************************************************************
470 -> PersistentCompilerState -- IN: persistent compiler state
471 -> InteractiveContext -- Context for compiling
472 -> String -- The statement
473 -> Bool -- just treat it as an expression
474 -> IO ( PersistentCompilerState,
480 When the UnlinkedBCOExpr is linked you get an HValue of type
482 When you run it you get a list of HValues that should be
483 the same length as the list of names; add them to the ClosureEnv.
485 A naked expression returns a singleton Name [it].
487 What you type The IO [HValue] that hscStmt returns
488 ------------- ------------------------------------
489 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
492 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
495 expr (of IO type) ==> expr >>= \ v -> return [v]
496 [NB: result not printed] bindings: [it]
499 expr (of non-IO type,
500 result showable) ==> let v = expr in print v >> return [v]
503 expr (of non-IO type,
504 result not showable) ==> error
507 hscStmt dflags hst hit pcs0 icontext stmt just_expr
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 icontext parsed_stmt
526 ; case maybe_renamed_stmt of
527 Nothing -> return (pcs0, Nothing)
528 Just (bound_names, rn_stmt) -> do {
533 then case rn_stmt of { (ExprStmt e _ _, decls) ->
534 typecheckExpr dflags pcs1 hst (ic_type_env icontext)
535 print_unqual iNTERACTIVE (e,decls) }
536 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
537 print_unqual iNTERACTIVE bound_names rn_stmt
539 ; case maybe_tc_return of
540 Nothing -> return (pcs0, Nothing)
541 Just (pcs2, tc_expr, bound_ids, ty) -> do {
544 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
547 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
549 -- Tidy it (temporary, until coreSat does cloning)
550 ; tidy_expr <- tidyCoreExpr simpl_expr
552 -- Prepare for codegen
553 ; prepd_expr <- corePrepExpr dflags tidy_expr
556 ; bcos <- coreExprToBCOs dflags prepd_expr
559 -- Make all the bound ids "global" ids, now that
560 -- they're notionally top-level bindings. This is
561 -- important: otherwise when we come to compile an expression
562 -- using these ids later, the byte code generator will consider
563 -- the occurrences to be free rather than global.
564 global_bound_ids = map globaliseId bound_ids;
565 globaliseId id = setGlobalIdDetails id VanillaGlobal
567 ; return (pcs2, Just (global_bound_ids, ty, bcos))
571 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
572 hscParseStmt dflags str
573 = do -------------------------- Parser ----------------
574 showPass dflags "Parser"
577 buf <- stringToStringBuffer str
579 let glaexts | dopt Opt_GlasgowExts dflags = 1#
582 case parseStmt buf PState{ bol = 0#, atbol = 1#,
583 context = [], glasgow_exts = glaexts,
584 loc = mkSrcLoc SLIT("<interactive>") 1 } of {
586 PFailed err -> do { hPutStrLn stderr (showSDoc err);
587 -- Not yet implemented in <4.11 freeStringBuffer buf;
590 -- no stmt: the line consisted of just space or comments
591 POk _ Nothing -> return Nothing;
593 POk _ (Just rdr_stmt) -> do {
595 --ToDo: can't free the string buffer until we've finished this
596 -- compilation sweep and all the identifiers have gone away.
597 --freeStringBuffer buf;
598 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
599 return (Just rdr_stmt)
604 %************************************************************************
606 \subsection{Getting information about an identifer}
608 %************************************************************************
612 hscThing -- like hscStmt, but deals with a single identifier
616 -> PersistentCompilerState -- IN: persistent compiler state
617 -> InteractiveContext -- Context for compiling
618 -> String -- The identifier
619 -> IO ( PersistentCompilerState,
622 hscThing dflags hst hit pcs0 ic str
623 = do maybe_rdr_name <- myParseIdentifier dflags str
624 case maybe_rdr_name of {
625 Nothing -> return (pcs0, []);
628 -- if the identifier is a constructor (begins with an
629 -- upper-case letter), then we need to consider both
630 -- constructor and type class identifiers.
632 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
633 | otherwise = [ rdr_name ]
635 occ = rdrNameOcc rdr_name
636 tccls_occ = setOccNameSpace occ tcClsName
637 tccls_name = setRdrNameOcc rdr_name tccls_occ
639 (pcs, unqual, maybe_rn_result) <-
640 renameRdrName dflags hit hst pcs0 ic rdr_names
642 case maybe_rn_result of {
643 Nothing -> return (pcs, []);
644 Just (names, decls) -> do {
646 maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
650 Nothing -> return (pcs, []);
653 | isLocalName n = lookupNameEnv (ic_type_env ic) n
654 | otherwise = lookupType hst (pcs_PTE pcs) n
656 maybe_ty_things = map do_lookup names
658 return (pcs, catMaybes maybe_ty_things) }
661 myParseIdentifier dflags str
662 = do buf <- stringToStringBuffer str
664 let glaexts | dopt Opt_GlasgowExts dflags = 1#
667 case parseIdentifier buf
668 PState{ bol = 0#, atbol = 1#,
669 context = [], glasgow_exts = glaexts,
670 loc = mkSrcLoc SLIT("<interactive>") 1 } of
672 PFailed err -> do { hPutStrLn stderr (showSDoc err);
673 freeStringBuffer buf;
676 POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
677 return (Just rdr_name) }
681 %************************************************************************
683 \subsection{Find all the things defined in a module}
685 %************************************************************************
693 -> PersistentCompilerState -- IN: persistent compiler state
694 -> Module -- module to inspect
695 -> Bool -- grab just the exports, or the whole toplev
696 -> IO (PersistentCompilerState, Maybe [TyThing])
698 hscModuleContents dflags hst hit pcs0 mod exports_only = do {
700 -- slurp the interface if necessary
701 (pcs1, print_unqual, maybe_rn_stuff)
702 <- slurpIface dflags hit hst pcs0 mod;
704 case maybe_rn_stuff of {
705 Nothing -> return (pcs0, Nothing);
706 Just (names, rn_decls) -> do {
708 -- Typecheck the declarations
710 typecheckExtraDecls dflags pcs1 hst print_unqual iNTERACTIVE rn_decls;
713 Nothing -> return (pcs1, Nothing);
717 | exports_only = names
719 let { iface = fromJust (lookupModuleEnv hit mod);
720 env = fromJust (mi_globals iface);
721 range = rdrEnvElts env;
723 -- grab all the things from the global env that are locally def'd
724 nub [ n | elts <- range, GRE n LocalDef _ <- elts ];
728 ty_things = map (fromJust . lookupType hst pte) all_names;
732 return (pcs2, Just ty_things)
737 %************************************************************************
739 \subsection{Initial persistent state}
741 %************************************************************************
744 initPersistentCompilerState :: IO PersistentCompilerState
745 initPersistentCompilerState
746 = do prs <- initPersistentRenamerState
748 PCS { pcs_PIT = emptyIfaceTable,
749 pcs_PTE = wiredInThingEnv,
750 pcs_insts = emptyInstEnv,
751 pcs_rules = emptyRuleBase,
756 initPersistentRenamerState :: IO PersistentRenamerState
757 = do us <- mkSplitUniqSupply 'r'
759 PRS { prsOrig = NameSupply { nsUniqs = us,
760 nsNames = initOrigNames,
762 prsDecls = (emptyNameEnv, 0),
763 prsInsts = (emptyBag, 0),
764 prsRules = foldr add_rule (emptyBag, 0) builtinRules,
769 add_rule (name,rule) (rules, n_rules)
770 = (gated_decl `consBag` rules, n_rules+1)
772 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
773 mod = nameModule name
774 rdr_name = mkRdrOrig (moduleName mod) (nameOccName name)
775 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
777 initOrigNames :: FiniteMap (ModuleName,OccName) Name
779 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
781 grab names = foldl add emptyFM names
783 = addToFM env (moduleName (nameModule name), nameOccName name) name