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
137 showPass dflags ("Checking old interface for hs = "
138 ++ show (ml_hs_file location)
139 ++ ", hspp = " ++ show (ml_hspp_file location));
141 (pcs_ch, errs_found, (recomp_reqd, maybe_checked_iface))
142 <- _scc_ "checkOldIface"
143 checkOldIface ghci_mode dflags hit hst pcs (ml_hi_file location)
144 source_unchanged maybe_old_iface;
147 return (HscFail pcs_ch)
150 let no_old_iface = not (isJust maybe_checked_iface)
151 what_next | recomp_reqd || no_old_iface = hscRecomp
152 | otherwise = hscNoRecomp
154 what_next ghci_mode dflags have_object mod location
155 maybe_checked_iface hst hit pcs_ch
159 -- we definitely expect to have the old interface available
160 hscNoRecomp ghci_mode dflags have_object
161 mod location (Just old_iface) hst hit pcs_ch
162 | ghci_mode == OneShot
164 when (verbosity dflags > 0) $
165 hPutStrLn stderr "compilation IS NOT required";
166 let { bomb = panic "hscNoRecomp:OneShot" };
167 return (HscNoRecomp pcs_ch bomb bomb)
171 when (verbosity dflags >= 1) $
172 hPutStrLn stderr ("Skipping " ++
173 compMsg have_object mod location);
176 (pcs_cl, closure_errs, cl_hs_decls)
177 <- closeIfaceDecls dflags hit hst pcs_ch old_iface ;
179 return (HscFail pcs_cl)
184 <- typecheckIface dflags pcs_cl hst old_iface cl_hs_decls;
186 case maybe_tc_result of {
187 Nothing -> return (HscFail pcs_cl);
188 Just (pcs_tc, new_details) ->
190 return (HscNoRecomp pcs_tc new_details old_iface)
193 compMsg use_object mod location =
194 mod_str ++ take (max 0 (16 - length mod_str)) (repeat ' ')
195 ++" ( " ++ unJust "hscRecomp" (ml_hs_file location) ++ ", "
197 then unJust "hscRecomp" (ml_obj_file location)
200 where mod_str = moduleUserString mod
203 hscRecomp ghci_mode dflags have_object
204 mod location maybe_checked_iface hst hit pcs_ch
206 -- what target are we shooting for?
207 ; let toInterp = dopt_HscLang dflags == HscInterpreted
208 ; let toNothing = dopt_HscLang dflags == HscNothing
210 ; when (verbosity dflags >= 1) $
211 hPutStrLn stderr ("Compiling " ++
212 compMsg (not toInterp) mod location);
217 ; maybe_parsed <- myParseModule dflags
218 (unJust "hscRecomp:hspp" (ml_hspp_file location))
219 ; case maybe_parsed of {
220 Nothing -> return (HscFail pcs_ch);
221 Just rdr_module -> do {
222 ; let this_mod = mkHomeModule (hsModuleName rdr_module)
227 ; (pcs_rn, print_unqualified, maybe_rn_result)
229 renameModule dflags hit hst pcs_ch this_mod rdr_module
230 ; case maybe_rn_result of {
231 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
232 Just (is_exported, new_iface, rn_hs_decls) -> do {
234 -- In interactive mode, we don't want to discard any top-level entities at
235 -- all (eg. do not inline them away during simplification), and retain them
236 -- all in the TypeEnv so they are available from the command line.
238 -- isGlobalName separates the user-defined top-level names from those
239 -- introduced by the type checker.
240 ; let dont_discard | ghci_mode == Interactive = isGlobalName
241 | otherwise = is_exported
247 <- _scc_ "TypeCheck" typecheckModule dflags pcs_rn hst new_iface
248 print_unqualified rn_hs_decls
249 ; case maybe_tc_result of {
250 Nothing -> return (HscFail pcs_ch{-was: pcs_rn-});
251 Just (pcs_tc, tc_result) -> do {
256 ; (ds_details, foreign_stuff)
258 deSugar dflags pcs_tc hst this_mod print_unqualified tc_result
261 <- if ghci_mode == OneShot
262 then do init_pcs <- initPersistentCompilerState
263 init_prs <- initPersistentRenamerState
265 rules = pcs_rules pcs_tc
266 orig_tc = prsOrig (pcs_PRS pcs_tc)
267 new_prs = init_prs{ prsOrig=orig_tc }
269 orig_tc `seq` rules `seq` new_prs `seq`
270 return init_pcs{ pcs_PRS = new_prs,
279 core2core dflags pcs_middle hst dont_discard ds_details
284 ; cg_info_ref <- newIORef Nothing ;
285 ; let cg_info :: CgInfoEnv
286 cg_info = unsafePerformIO $ do {
287 maybe_cg_env <- readIORef cg_info_ref ;
289 Just env -> return env
290 Nothing -> do { printError "Urk! Looked at CgInfo too early!";
291 return emptyNameEnv } }
292 -- cg_info_ref will be filled in just after restOfCodeGeneration
293 -- Meanwhile, tidyCorePgm is careful not to look at cg_info!
295 ; (pcs_simpl, tidy_details)
297 tidyCorePgm dflags this_mod pcs_middle cg_info simpl_details
299 ; pcs_final <- if ghci_mode == OneShot then initPersistentCompilerState
300 else return pcs_simpl
302 -- alive at this point:
306 ; emitExternalCore dflags new_iface tidy_details
308 -- PREPARE FOR CODE GENERATION
310 -- Do saturation and convert to A-normal form
311 ; prepd_details <- _scc_ "CorePrep" 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,fe_binders) = foreign_stuff
329 ; imported_modules <- mapM mod_name_to_Module imported_module_names
331 ; (stub_h_exists, stub_c_exists, maybe_bcos, final_iface )
335 ----------------- Generate byte code ------------------
336 (bcos,itbl_env) <- byteCodeGen dflags binds
337 local_tycons local_classes
339 -- Fill in the code-gen info
340 writeIORef cg_info_ref (Just emptyNameEnv)
342 ------------------ BUILD THE NEW ModIface ------------
343 final_iface <- _scc_ "MkFinalIface"
344 mkFinalIface ghci_mode dflags location
345 maybe_checked_iface new_iface tidy_details
347 return ( False, False, Just (bcos,itbl_env), final_iface )
349 then error "GHC not compiled with interpreter"
353 ----------------- Convert to STG ------------------
354 (stg_binds, cost_centre_info, stg_back_end_info)
356 myCoreToStg dflags this_mod binds
358 -- Fill in the code-gen info for the earlier tidyCorePgm
359 writeIORef cg_info_ref (Just stg_back_end_info)
361 ------------------ BUILD THE NEW ModIface ------------
362 final_iface <- _scc_ "MkFinalIface"
363 mkFinalIface ghci_mode dflags location
364 maybe_checked_iface new_iface tidy_details
368 return (False, False, Nothing, final_iface)
370 ------------------ Code generation ------------------
371 abstractC <- _scc_ "CodeGen"
372 codeGen dflags this_mod imported_modules
373 cost_centre_info fe_binders
374 local_tycons stg_binds
376 ------------------ Code output -----------------------
377 (stub_h_exists, stub_c_exists)
378 <- codeOutput dflags this_mod local_tycons
380 c_code h_code abstractC
382 return (stub_h_exists, stub_c_exists, Nothing, final_iface)
384 ; let final_details = tidy_details {md_binds = []}
387 -- and the answer is ...
388 ; return (HscRecomp pcs_final
391 stub_h_exists stub_c_exists
395 myParseModule dflags src_filename
396 = do -------------------------- Parser ----------------
397 showPass dflags "Parser"
400 buf <- hGetStringBuffer True{-expand tabs-} src_filename
402 let glaexts | dopt Opt_GlasgowExts dflags = 1#
405 case parseModule buf PState{ bol = 0#, atbol = 1#,
406 context = [], glasgow_exts = glaexts,
407 loc = mkSrcLoc (_PK_ src_filename) 1 } of {
409 PFailed err -> do { hPutStrLn stderr (showSDoc err);
410 freeStringBuffer buf;
413 POk _ rdr_module@(HsModule mod_name _ _ _ _ _ _) -> do {
415 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
417 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
418 (ppSourceStats False rdr_module) ;
420 return (Just rdr_module)
421 -- ToDo: free the string buffer later.
425 myCoreToStg dflags this_mod tidy_binds
427 () <- coreBindsSize tidy_binds `seq` return ()
428 -- TEMP: the above call zaps some space usage allocated by the
429 -- simplifier, which for reasons I don't understand, persists
430 -- thoroughout code generation
432 stg_binds <- _scc_ "Core2Stg" coreToStg dflags tidy_binds
434 (stg_binds2, cost_centre_info)
435 <- _scc_ "Core2Stg" stg2stg dflags this_mod stg_binds
437 let env_rhs :: CgInfoEnv
438 env_rhs = mkNameEnv [ (idName bndr, CgInfo caf_info)
439 | (bind,_) <- stg_binds2,
441 | stgBindHasCafRefs bind = MayHaveCafRefs
442 | otherwise = NoCafRefs,
443 bndr <- stgBinders bind ]
445 return (stg_binds2, cost_centre_info, env_rhs)
449 %************************************************************************
451 \subsection{Compiling a do-statement}
453 %************************************************************************
461 -> PersistentCompilerState -- IN: persistent compiler state
462 -> InteractiveContext -- Context for compiling
463 -> String -- The statement
464 -> Bool -- just treat it as an expression
465 -> IO ( PersistentCompilerState,
471 When the UnlinkedBCOExpr is linked you get an HValue of type
473 When you run it you get a list of HValues that should be
474 the same length as the list of names; add them to the ClosureEnv.
476 A naked expression returns a singleton Name [it].
478 What you type The IO [HValue] that hscStmt returns
479 ------------- ------------------------------------
480 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
483 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
486 expr (of IO type) ==> expr >>= \ v -> return [v]
487 [NB: result not printed] bindings: [it]
490 expr (of non-IO type,
491 result showable) ==> let v = expr in print v >> return [v]
494 expr (of non-IO type,
495 result not showable) ==> error
498 hscStmt dflags hst hit pcs0 icontext stmt just_expr
499 = do { maybe_stmt <- hscParseStmt dflags stmt
501 Nothing -> return (pcs0, Nothing)
502 Just parsed_stmt -> do {
504 let { notExprStmt (ExprStmt _ _ _) = False;
508 if (just_expr && notExprStmt parsed_stmt)
509 then do hPutStrLn stderr ("not an expression: `" ++ stmt ++ "'")
510 return (pcs0, Nothing)
514 (pcs1, print_unqual, maybe_renamed_stmt)
515 <- renameStmt dflags hit hst pcs0
516 iNTERACTIVE icontext parsed_stmt
518 ; case maybe_renamed_stmt of
519 Nothing -> return (pcs0, Nothing)
520 Just (bound_names, rn_stmt) -> do {
525 then case rn_stmt of { (ExprStmt e _ _, decls) ->
526 typecheckExpr dflags pcs1 hst (ic_type_env icontext)
527 print_unqual iNTERACTIVE (e,decls) }
528 else typecheckStmt dflags pcs1 hst (ic_type_env icontext)
529 print_unqual iNTERACTIVE bound_names rn_stmt
531 ; case maybe_tc_return of
532 Nothing -> return (pcs0, Nothing)
533 Just (pcs2, tc_expr, bound_ids, ty) -> do {
536 ds_expr <- deSugarExpr dflags pcs2 hst iNTERACTIVE print_unqual tc_expr
539 ; simpl_expr <- simplifyExpr dflags pcs2 hst ds_expr
541 -- Tidy it (temporary, until coreSat does cloning)
542 ; tidy_expr <- tidyCoreExpr simpl_expr
544 -- Prepare for codegen
545 ; prepd_expr <- corePrepExpr dflags tidy_expr
548 ; bcos <- coreExprToBCOs dflags prepd_expr
551 -- Make all the bound ids "global" ids, now that
552 -- they're notionally top-level bindings. This is
553 -- important: otherwise when we come to compile an expression
554 -- using these ids later, the byte code generator will consider
555 -- the occurrences to be free rather than global.
556 global_bound_ids = map globaliseId bound_ids;
557 globaliseId id = setGlobalIdDetails id VanillaGlobal
559 ; return (pcs2, Just (global_bound_ids, ty, bcos))
563 hscParseStmt :: DynFlags -> String -> IO (Maybe RdrNameStmt)
564 hscParseStmt dflags str
565 = do -------------------------- Parser ----------------
566 showPass dflags "Parser"
569 buf <- stringToStringBuffer str
571 let glaexts | dopt Opt_GlasgowExts dflags = 1#
574 case parseStmt buf PState{ bol = 0#, atbol = 1#,
575 context = [], glasgow_exts = glaexts,
576 loc = mkSrcLoc SLIT("<interactive>") 1 } of {
578 PFailed err -> do { hPutStrLn stderr (showSDoc err);
579 -- Not yet implemented in <4.11 freeStringBuffer buf;
582 -- no stmt: the line consisted of just space or comments
583 POk _ Nothing -> return Nothing;
585 POk _ (Just rdr_stmt) -> do {
587 --ToDo: can't free the string buffer until we've finished this
588 -- compilation sweep and all the identifiers have gone away.
589 --freeStringBuffer buf;
590 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_stmt);
591 return (Just rdr_stmt)
596 %************************************************************************
598 \subsection{Getting information about an identifer}
600 %************************************************************************
604 hscThing -- like hscStmt, but deals with a single identifier
608 -> PersistentCompilerState -- IN: persistent compiler state
609 -> InteractiveContext -- Context for compiling
610 -> String -- The identifier
611 -> IO ( PersistentCompilerState,
614 hscThing dflags hst hit pcs0 icontext str
615 = do maybe_rdr_name <- myParseIdentifier dflags str
616 case maybe_rdr_name of {
617 Nothing -> return (pcs0, []);
620 -- if the identifier is a constructor (begins with an
621 -- upper-case letter), then we need to consider both
622 -- constructor and type class identifiers.
624 | occNameSpace occ == dataName = [ rdr_name, tccls_name ]
625 | otherwise = [ rdr_name ]
627 occ = rdrNameOcc rdr_name
628 tccls_occ = setOccNameSpace occ tcClsName
629 tccls_name = setRdrNameOcc rdr_name tccls_occ
631 (pcs, unqual, maybe_rn_result) <-
632 renameRdrName dflags hit hst pcs0 iNTERACTIVE icontext rdr_names
634 case maybe_rn_result of {
635 Nothing -> return (pcs, []);
636 Just (names, decls) -> do {
638 maybe_pcs <- typecheckExtraDecls dflags pcs hst unqual
642 Nothing -> return (pcs, []);
644 let maybe_ty_things = map (lookupType hst (pcs_PTE pcs)) names
646 return (pcs, catMaybes maybe_ty_things) }
649 myParseIdentifier dflags str
650 = do buf <- stringToStringBuffer str
652 let glaexts | dopt Opt_GlasgowExts dflags = 1#
655 case parseIdentifier buf
656 PState{ bol = 0#, atbol = 1#,
657 context = [], glasgow_exts = glaexts,
658 loc = mkSrcLoc SLIT("<interactive>") 1 } of
660 PFailed err -> do { hPutStrLn stderr (showSDoc err);
661 freeStringBuffer buf;
664 POk _ rdr_name -> do { --should, but can't: freeStringBuffer buf;
665 return (Just rdr_name) }
669 %************************************************************************
671 \subsection{Initial persistent state}
673 %************************************************************************
676 initPersistentCompilerState :: IO PersistentCompilerState
677 initPersistentCompilerState
678 = do prs <- initPersistentRenamerState
680 PCS { pcs_PIT = emptyIfaceTable,
681 pcs_PTE = wiredInThingEnv,
682 pcs_insts = emptyInstEnv,
683 pcs_rules = emptyRuleBase,
688 initPersistentRenamerState :: IO PersistentRenamerState
689 = do us <- mkSplitUniqSupply 'r'
691 PRS { prsOrig = NameSupply { nsUniqs = us,
692 nsNames = initOrigNames,
694 prsDecls = (emptyNameEnv, 0),
695 prsInsts = (emptyBag, 0),
696 prsRules = foldr add_rule (emptyBag, 0) builtinRules,
701 add_rule (name,rule) (rules, n_rules)
702 = (gated_decl `consBag` rules, n_rules+1)
704 gated_decl = (gate_fn, (mod, IfaceRuleOut rdr_name rule))
705 mod = nameModule name
706 rdr_name = mkRdrOrig (moduleName mod) (nameOccName name)
707 gate_fn vis_fn = vis_fn name -- Load the rule whenever name is visible
709 initOrigNames :: FiniteMap (ModuleName,OccName) Name
711 = grab knownKeyNames `plusFM` grab (map getName wiredInThings)
713 grab names = foldl add emptyFM names
715 = addToFM env (moduleName (nameModule name), nameOccName name) name