2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 ( newHscEnv, hscCmmFile
13 , hscStmt, hscTcExpr, hscKcType
16 , hscCompileOneShot -- :: Compiler HscStatus
17 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
18 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
19 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
21 , InteractiveStatus (..)
25 #include "HsVersions.h"
28 import HsSyn ( Stmt(..), LHsExpr, LStmt, LHsType )
29 import Module ( Module )
30 import CodeOutput ( outputForeignStubs )
31 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
32 import Linker ( HValue, linkExpr )
33 import CoreTidy ( tidyExpr )
34 import CorePrep ( corePrepExpr )
35 import Flattening ( flattenExpr )
36 import Desugar ( deSugarExpr )
37 import SimplCore ( simplifyExpr )
38 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
40 import PrelNames ( iNTERACTIVE )
42 import CoreLint ( lintUnfolding )
43 import DsMeta ( templateHaskellNames )
44 import SrcLoc ( noSrcLoc )
45 import VarEnv ( emptyTidyEnv )
49 import Module ( emptyModuleEnv, ModLocation(..) )
50 import RdrName ( GlobalRdrEnv, RdrName )
51 import HsSyn ( HsModule, LHsBinds, HsGroup, LIE, LImportDecl )
52 import SrcLoc ( Located(..) )
53 import StringBuffer ( hGetStringBuffer, stringToStringBuffer )
55 import Lexer ( P(..), ParseResult(..), mkPState )
56 import SrcLoc ( mkSrcLoc )
57 import TcRnDriver ( tcRnModule, tcRnExtCore )
58 import TcIface ( typecheckIface )
59 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
60 import IfaceEnv ( initNameCache )
61 import LoadIface ( ifaceStats, initExternalPackageState )
62 import PrelInfo ( wiredInThings, basicKnownKeyNames )
63 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
64 import Desugar ( deSugar )
65 import Flattening ( flatten )
66 import SimplCore ( core2core )
67 import TidyPgm ( tidyProgram, mkBootModDetails )
68 import CorePrep ( corePrepPgm )
69 import CoreToStg ( coreToStg )
70 import TyCon ( isDataTyCon )
71 import Packages ( mkHomeModules )
72 import Name ( Name, NamedThing(..) )
73 import SimplStg ( stg2stg )
74 import CodeGen ( codeGen )
75 import CmmParse ( parseCmmFile )
76 import CodeOutput ( codeOutput )
80 import UniqSupply ( mkSplitUniqSupply )
83 import HscStats ( ppSourceStats )
85 import MkExternalCore ( emitExternalCore )
87 import ParserCoreUtils
89 import Maybes ( expectJust )
90 import Bag ( unitBag )
91 import Monad ( unless )
93 import DATA_IOREF ( newIORef, readIORef )
97 %************************************************************************
101 %************************************************************************
104 newHscEnv :: DynFlags -> IO HscEnv
106 = do { eps_var <- newIORef initExternalPackageState
107 ; us <- mkSplitUniqSupply 'r'
108 ; nc_var <- newIORef (initNameCache us knownKeyNames)
109 ; fc_var <- newIORef emptyModuleEnv
110 ; return (HscEnv { hsc_dflags = dflags,
113 hsc_IC = emptyInteractiveContext,
114 hsc_HPT = emptyHomePackageTable,
117 hsc_FC = fc_var } ) }
120 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
121 -- where templateHaskellNames are defined
122 knownKeyNames = map getName wiredInThings
123 ++ basicKnownKeyNames
125 ++ templateHaskellNames
130 %************************************************************************
132 The main compiler pipeline
134 %************************************************************************
136 --------------------------------
137 The compilation proper
138 --------------------------------
141 It's the task of the compilation proper to compile Haskell, hs-boot and
142 core files to either byte-code, hard-code (C, asm, Java, ect) or to
143 nothing at all (the module is still parsed and type-checked. This
144 feature is mostly used by IDE's and the likes).
145 Compilation can happen in either 'one-shot', 'batch', 'nothing',
146 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
147 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
149 The modes are kept separate because of their different types and meanings.
150 In 'one-shot' mode, we're only compiling a single file and can therefore
151 discard the new ModIface and ModDetails. This is also the reason it only
152 targets hard-code; compiling to byte-code or nothing doesn't make sense
153 when we discard the result.
154 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
155 and ModDetails. 'Batch' mode doesn't target byte-code since that require
156 us to return the newly compiled byte-code.
157 'Nothing' mode has exactly the same type as 'batch' mode but they're still
158 kept separate. This is because compiling to nothing is fairly special: We
159 don't output any interface files, we don't run the simplifier and we don't
161 'Interactive' mode is similar to 'batch' mode except that we return the
162 compiled byte-code together with the ModIface and ModDetails.
164 Trying to compile a hs-boot file to byte-code will result in a run-time
165 error. This is the only thing that isn't caught by the type-system.
172 (Located (HsModule RdrName))
174 (Maybe (HsGroup Name,[LImportDecl Name],Maybe [LIE Name]))
176 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
179 -- Status of a compilation to hard-code or nothing.
182 | HscRecomp Bool -- Has stub files.
183 -- This is a hack. We can't compile C files here
184 -- since it's done in DriverPipeline. For now we
185 -- just return True if we want the caller to compile
188 -- Status of a compilation to byte-code.
189 data InteractiveStatus
190 = InteractiveNoRecomp
191 | InteractiveRecomp Bool -- Same as HscStatus
195 -- I want Control.Monad.State! --Lemmih 03/07/2006
196 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
198 instance Monad Comp where
199 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
200 return a = Comp $ \s -> return (a,s)
203 evalComp :: Comp a -> CompState -> IO a
204 evalComp comp st = do (val,_st') <- runComp comp st
209 { compHscEnv :: HscEnv
210 , compModSummary :: ModSummary
211 , compOldIface :: Maybe ModIface
214 get :: Comp CompState
215 get = Comp $ \s -> return (s,s)
217 gets :: (CompState -> a) -> Comp a
218 gets getter = do st <- get
221 liftIO :: IO a -> Comp a
222 liftIO ioA = Comp $ \s -> do a <- ioA
225 type NoRecomp result = ModIface -> Comp result
226 type FrontEnd core = Comp (Maybe core)
228 -- FIXME: The old interface and module index are only using in 'batch' and
229 -- 'interactive' mode. They should be removed from 'oneshot' mode.
230 type Compiler result = HscEnv
232 -> Bool -- True <=> source unchanged
233 -> Maybe ModIface -- Old interface, if available
234 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
238 -- This functions checks if recompilation is necessary and
239 -- then combines the FrontEnd and BackEnd to a working compiler.
240 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
241 -> (Maybe (Int,Int) -> Bool -> Comp ())
243 -> (core -> Comp result) -- Backend.
245 hscMkCompiler norecomp messenger frontend backend
246 hsc_env mod_summary source_unchanged
247 mbOldIface mbModIndex
248 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
249 do (recomp_reqd, mbCheckedIface)
250 <- {-# SCC "checkOldIface" #-}
251 liftIO $ checkOldIface hsc_env mod_summary
252 source_unchanged mbOldIface
253 case mbCheckedIface of
254 Just iface | not recomp_reqd
255 -> do messenger mbModIndex False
256 result <- norecomp iface
259 -> do messenger mbModIndex True
265 -> do result <- backend core
268 --------------------------------------------------------------
270 --------------------------------------------------------------
273 -- Compile Haskell, boot and extCore in OneShot mode.
274 hscCompileOneShot :: Compiler HscStatus
275 hscCompileOneShot hsc_env mod_summary =
276 compiler hsc_env mod_summary
277 where mkComp = hscMkCompiler (norecompOneShot HscNoRecomp) oneShotMsg
278 -- How to compile nonBoot files.
279 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
280 hscWriteIface >>= hscOneShot
281 -- How to compile boot files.
282 bootComp inp = hscBootIface inp >>= hscWriteIface >>= hscConst (HscRecomp False)
284 = case ms_hsc_src mod_summary of
286 -> mkComp hscCoreFrontEnd nonBootComp
288 -> mkComp hscFileFrontEnd nonBootComp
290 -> mkComp hscFileFrontEnd bootComp
292 -- Compile Haskell, boot and extCore in batch mode.
293 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
294 hscCompileBatch hsc_env mod_summary
295 = compiler hsc_env mod_summary
296 where mkComp = hscMkCompiler norecompBatch (batchMsg False)
297 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
298 hscWriteIface >>= hscBatch
299 bootComp inp = hscBootIface inp >>= hscWriteIface >>= hscNothing
301 = case ms_hsc_src mod_summary of
303 -> mkComp hscCoreFrontEnd nonBootComp
305 -> mkComp hscFileFrontEnd nonBootComp
307 -> mkComp hscFileFrontEnd bootComp
309 -- Type-check Haskell, boot and extCore.
310 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
311 hscCompileNothing hsc_env mod_summary
312 = compiler hsc_env mod_summary
313 where mkComp = hscMkCompiler norecompBatch (batchMsg False)
314 nonBootComp inp = hscNormalIface inp >>= hscIgnoreIface >>= hscNothing
315 bootComp inp = hscBootIface inp >>= hscIgnoreIface >>= hscNothing
317 = case ms_hsc_src mod_summary of
319 -> mkComp hscCoreFrontEnd nonBootComp
321 -> mkComp hscFileFrontEnd nonBootComp
323 -> mkComp hscFileFrontEnd bootComp
325 -- Compile Haskell, extCore to bytecode.
326 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
327 hscCompileInteractive hsc_env mod_summary =
328 hscMkCompiler norecompInteractive (batchMsg True)
331 where backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
332 frontend = case ms_hsc_src mod_summary of
333 ExtCoreFile -> hscCoreFrontEnd
334 HsSrcFile -> hscFileFrontEnd
335 HsBootFile -> panic bootErrorMsg
336 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
337 "Use 'hscCompileBatch' instead."
339 --------------------------------------------------------------
341 --------------------------------------------------------------
343 norecompOneShot :: a -> NoRecomp a
344 norecompOneShot a old_iface
345 = do hsc_env <- gets compHscEnv
347 dumpIfaceStats hsc_env
350 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
351 norecompBatch = norecompWorker HscNoRecomp False
353 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
354 norecompInteractive = norecompWorker InteractiveNoRecomp True
356 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
357 norecompWorker a isInterp old_iface
358 = do hsc_env <- gets compHscEnv
359 mod_summary <- gets compModSummary
361 new_details <- {-# SCC "tcRnIface" #-}
362 initIfaceCheck hsc_env $
363 typecheckIface old_iface
364 dumpIfaceStats hsc_env
365 return (a, old_iface, new_details)
367 --------------------------------------------------------------
368 -- Progress displayers.
369 --------------------------------------------------------------
371 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
372 oneShotMsg _mb_mod_index recomp
373 = do hsc_env <- gets compHscEnv
377 else compilationProgressMsg (hsc_dflags hsc_env) $
378 "compilation IS NOT required"
380 batchMsg :: Bool -> Maybe (Int,Int) -> Bool -> Comp ()
381 batchMsg toInterp mb_mod_index recomp
382 = do hsc_env <- gets compHscEnv
383 mod_summary <- gets compModSummary
384 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
385 (showModuleIndex mb_mod_index ++
386 msg ++ showModMsg (not toInterp) mod_summary)
389 then showMsg "Compiling "
390 else showMsg "Skipping "
394 --------------------------------------------------------------
396 --------------------------------------------------------------
398 hscCoreFrontEnd :: FrontEnd ModGuts
400 do hsc_env <- gets compHscEnv
401 mod_summary <- gets compModSummary
406 inp <- readFile (expectJust "hscCoreFrontEnd" (ms_hspp_file mod_summary))
407 case parseCore inp 1 of
409 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
413 -- RENAME and TYPECHECK
415 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
416 tcRnExtCore hsc_env rdr_module
417 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
418 case maybe_tc_result of
419 Nothing -> return Nothing
420 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
423 hscFileFrontEnd :: FrontEnd ModGuts
425 do hsc_env <- gets compHscEnv
426 mod_summary <- gets compModSummary
431 let dflags = hsc_dflags hsc_env
432 hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
433 hspp_buf = ms_hspp_buf mod_summary
434 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
437 -> do printBagOfErrors dflags (unitBag err)
441 -- RENAME and TYPECHECK
443 -> do (tc_msgs, maybe_tc_result)
444 <- {-# SCC "Typecheck-Rename" #-}
445 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
446 printErrorsAndWarnings dflags tc_msgs
447 case maybe_tc_result of
454 -> do (warns, maybe_ds_result) <- {-# SCC "DeSugar" #-}
455 deSugar hsc_env tc_result
456 printBagOfWarnings dflags warns
457 return maybe_ds_result
459 --------------------------------------------------------------
461 --------------------------------------------------------------
463 hscSimplify :: ModGuts -> Comp ModGuts
464 hscSimplify ds_result
465 = do hsc_env <- gets compHscEnv
467 flat_result <- {-# SCC "Flattening" #-}
468 flatten hsc_env ds_result
472 simpl_result <- {-# SCC "Core2Core" #-}
473 core2core hsc_env flat_result
476 --------------------------------------------------------------
477 -- Interface generators
478 --------------------------------------------------------------
480 -- HACK: we return ModGuts even though we know it's not gonna be used.
481 -- We do this because the type signature needs to be identical
482 -- in structure to the type of 'hscNormalIface'.
483 hscBootIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, ModGuts)
484 hscBootIface ds_result
485 = do hsc_env <- gets compHscEnv
486 mod_summary <- gets compModSummary
487 maybe_old_iface <- gets compOldIface
489 details <- mkBootModDetails hsc_env ds_result
490 (new_iface, no_change)
491 <- {-# SCC "MkFinalIface" #-}
492 mkIface hsc_env maybe_old_iface ds_result details
493 -- And the answer is ...
494 dumpIfaceStats hsc_env
495 return (new_iface, no_change, details, ds_result)
497 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
498 hscNormalIface simpl_result
499 = do hsc_env <- gets compHscEnv
500 mod_summary <- gets compModSummary
501 maybe_old_iface <- gets compOldIface
506 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
507 tidyProgram hsc_env simpl_result
510 -- BUILD THE NEW ModIface and ModDetails
511 -- and emit external core if necessary
512 -- This has to happen *after* code gen so that the back-end
513 -- info has been set. Not yet clear if it matters waiting
514 -- until after code output
515 (new_iface, no_change)
516 <- {-# SCC "MkFinalIface" #-}
517 mkIface hsc_env maybe_old_iface simpl_result details
518 -- Emit external core
519 emitExternalCore (hsc_dflags hsc_env) cg_guts -- Move this? --Lemmih 03/07/2006
522 -- Return the prepared code.
523 return (new_iface, no_change, details, cg_guts)
525 --------------------------------------------------------------
526 -- BackEnd combinators
527 --------------------------------------------------------------
529 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
530 hscWriteIface (iface, no_change, details, a)
531 = do mod_summary <- gets compModSummary
534 $ writeIfaceFile (ms_location mod_summary) iface
535 return (iface, details, a)
537 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
538 hscIgnoreIface (iface, no_change, details, a)
539 = return (iface, details, a)
541 -- Don't output any code.
542 hscNothing :: (ModIface, ModDetails, a) -> Comp (HscStatus, ModIface, ModDetails)
543 hscNothing (iface, details, a)
544 = return (HscRecomp False, iface, details)
546 -- Generate code and return both the new ModIface and the ModDetails.
547 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (HscStatus, ModIface, ModDetails)
548 hscBatch (iface, details, cgguts)
549 = do hasStub <- hscCompile cgguts
550 return (HscRecomp hasStub, iface, details)
552 -- Here we don't need the ModIface and ModDetails anymore.
553 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp HscStatus
554 hscOneShot (_, _, cgguts)
555 = do hasStub <- hscCompile cgguts
556 return (HscRecomp hasStub)
558 -- Compile to hard-code.
559 hscCompile :: CgGuts -> Comp Bool
561 = do hsc_env <- gets compHscEnv
562 mod_summary <- gets compModSummary
564 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
565 -- From now on, we just use the bits we need.
566 cg_module = this_mod,
567 cg_binds = core_binds,
569 cg_dir_imps = dir_imps,
570 cg_foreign = foreign_stubs,
571 cg_home_mods = home_mods,
572 cg_dep_pkgs = dependencies } = cgguts
573 dflags = hsc_dflags hsc_env
574 location = ms_location mod_summary
575 data_tycons = filter isDataTyCon tycons
576 -- cg_tycons includes newtypes, for the benefit of External Core,
577 -- but we don't generate any code for newtypes
580 -- PREPARE FOR CODE GENERATION
581 -- Do saturation and convert to A-normal form
582 prepd_binds <- {-# SCC "CorePrep" #-}
583 corePrepPgm dflags core_binds data_tycons ;
584 ----------------- Convert to STG ------------------
585 (stg_binds, cost_centre_info)
586 <- {-# SCC "CoreToStg" #-}
587 myCoreToStg dflags home_mods this_mod prepd_binds
588 ------------------ Code generation ------------------
589 abstractC <- {-# SCC "CodeGen" #-}
590 codeGen dflags home_mods this_mod data_tycons
591 foreign_stubs dir_imps cost_centre_info
593 ------------------ Code output -----------------------
594 (stub_h_exists,stub_c_exists)
595 <- codeOutput dflags this_mod location foreign_stubs
596 dependencies abstractC
599 hscConst :: b -> a -> Comp b
600 hscConst b a = return b
602 hscInteractive :: (ModIface, ModDetails, CgGuts)
603 -> Comp (InteractiveStatus, ModIface, ModDetails)
604 hscInteractive (iface, details, cgguts)
606 = do hsc_env <- gets compHscEnv
607 mod_summary <- gets compModSummary
609 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
610 -- From now on, we just use the bits we need.
611 cg_module = this_mod,
612 cg_binds = core_binds,
614 cg_foreign = foreign_stubs } = cgguts
615 dflags = hsc_dflags hsc_env
616 location = ms_location mod_summary
617 data_tycons = filter isDataTyCon tycons
618 -- cg_tycons includes newtypes, for the benefit of External Core,
619 -- but we don't generate any code for newtypes
622 -- PREPARE FOR CODE GENERATION
623 -- Do saturation and convert to A-normal form
624 prepd_binds <- {-# SCC "CorePrep" #-}
625 corePrepPgm dflags core_binds data_tycons ;
626 ----------------- Generate byte code ------------------
627 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
628 ------------------ Create f-x-dynamic C-side stuff ---
629 (istub_h_exists, istub_c_exists)
630 <- outputForeignStubs dflags this_mod location foreign_stubs
631 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
633 = panic "GHC not compiled with interpreter"
636 ------------------------------
638 hscFileCheck :: HscEnv -> ModSummary -> IO (Maybe HscChecked)
639 hscFileCheck hsc_env mod_summary = do {
643 ; let dflags = hsc_dflags hsc_env
644 hspp_file = expectJust "hscFileFrontEnd" (ms_hspp_file mod_summary)
645 hspp_buf = ms_hspp_buf mod_summary
647 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
649 ; case maybe_parsed of {
650 Left err -> do { printBagOfErrors dflags (unitBag err)
652 Right rdr_module -> do {
655 -- RENAME and TYPECHECK
657 (tc_msgs, maybe_tc_result)
658 <- _scc_ "Typecheck-Rename"
659 tcRnModule hsc_env (ms_hsc_src mod_summary)
660 True{-save renamed syntax-}
663 ; printErrorsAndWarnings dflags tc_msgs
664 ; case maybe_tc_result of {
665 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing));
667 let md = ModDetails {
668 md_types = tcg_type_env tc_result,
669 md_exports = tcg_exports tc_result,
670 md_insts = tcg_insts tc_result,
671 md_rules = [panic "no rules"] }
672 -- Rules are CoreRules, not the
673 -- RuleDecls we get out of the typechecker
674 rnInfo = do decl <- tcg_rn_decls tc_result
675 imports <- tcg_rn_imports tc_result
676 let exports = tcg_rn_exports tc_result
677 return (decl,imports,exports)
678 return (Just (HscChecked rdr_module
680 (Just (tcg_binds tc_result,
681 tcg_rdr_env tc_result,
686 hscCmmFile :: DynFlags -> FilePath -> IO Bool
687 hscCmmFile dflags filename = do
688 maybe_cmm <- parseCmmFile dflags (mkHomeModules []) filename
690 Nothing -> return False
692 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
695 no_mod = panic "hscCmmFile: no_mod"
696 no_loc = ModLocation{ ml_hs_file = Just filename,
697 ml_hi_file = panic "hscCmmFile: no hi file",
698 ml_obj_file = panic "hscCmmFile: no obj file" }
701 myParseModule dflags src_filename maybe_src_buf
702 = -------------------------- Parser ----------------
703 showPass dflags "Parser" >>
704 {-# SCC "Parser" #-} do
706 -- sometimes we already have the buffer in memory, perhaps
707 -- because we needed to parse the imports out of it, or get the
709 buf <- case maybe_src_buf of
711 Nothing -> hGetStringBuffer src_filename
713 let loc = mkSrcLoc (mkFastString src_filename) 1 0
715 case unP parseModule (mkPState buf loc dflags) of {
717 PFailed span err -> return (Left (mkPlainErrMsg span err));
719 POk _ rdr_module -> do {
721 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
723 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
724 (ppSourceStats False rdr_module) ;
726 return (Right rdr_module)
727 -- ToDo: free the string buffer later.
731 myCoreToStg dflags home_mods this_mod prepd_binds
733 stg_binds <- {-# SCC "Core2Stg" #-}
734 coreToStg home_mods prepd_binds
736 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
737 stg2stg dflags home_mods this_mod stg_binds
739 return (stg_binds2, cost_centre_info)
743 %************************************************************************
745 \subsection{Compiling a do-statement}
747 %************************************************************************
749 When the UnlinkedBCOExpr is linked you get an HValue of type
751 When you run it you get a list of HValues that should be
752 the same length as the list of names; add them to the ClosureEnv.
754 A naked expression returns a singleton Name [it].
756 What you type The IO [HValue] that hscStmt returns
757 ------------- ------------------------------------
758 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
761 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
764 expr (of IO type) ==> expr >>= \ v -> return [v]
765 [NB: result not printed] bindings: [it]
768 expr (of non-IO type,
769 result showable) ==> let v = expr in print v >> return [v]
772 expr (of non-IO type,
773 result not showable) ==> error
777 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
779 -> String -- The statement
780 -> IO (Maybe (HscEnv, [Name], HValue))
783 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
784 ; case maybe_stmt of {
785 Nothing -> return Nothing ; -- Parse error
786 Just Nothing -> return Nothing ; -- Empty line
787 Just (Just parsed_stmt) -> do { -- The real stuff
789 -- Rename and typecheck it
790 let icontext = hsc_IC hsc_env
791 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
793 ; case maybe_tc_result of {
794 Nothing -> return Nothing ;
795 Just (new_ic, bound_names, tc_expr) -> do {
797 -- Then desugar, code gen, and link it
798 ; hval <- compileExpr hsc_env iNTERACTIVE
799 (ic_rn_gbl_env new_ic)
803 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
806 hscTcExpr -- Typecheck an expression (but don't run it)
808 -> String -- The expression
811 hscTcExpr hsc_env expr
812 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
813 ; let icontext = hsc_IC hsc_env
814 ; case maybe_stmt of {
815 Nothing -> return Nothing ; -- Parse error
816 Just (Just (L _ (ExprStmt expr _ _)))
817 -> tcRnExpr hsc_env icontext expr ;
818 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
822 hscKcType -- Find the kind of a type
824 -> String -- The type
827 hscKcType hsc_env str
828 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
829 ; let icontext = hsc_IC hsc_env
830 ; case maybe_type of {
831 Just ty -> tcRnType hsc_env icontext ty ;
832 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an type:" <+> quotes (text str)) ;
834 Nothing -> return Nothing } }
840 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
841 hscParseStmt = hscParseThing parseStmt
843 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
844 hscParseType = hscParseThing parseType
847 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
848 hscParseIdentifier = hscParseThing parseIdentifier
850 hscParseThing :: Outputable thing
852 -> DynFlags -> String
854 -- Nothing => Parse error (message already printed)
856 hscParseThing parser dflags str
857 = showPass dflags "Parser" >>
858 {-# SCC "Parser" #-} do
860 buf <- stringToStringBuffer str
862 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
864 case unP parser (mkPState buf loc dflags) of {
866 PFailed span err -> do { printError span err;
871 --ToDo: can't free the string buffer until we've finished this
872 -- compilation sweep and all the identifiers have gone away.
873 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
878 %************************************************************************
880 Desugar, simplify, convert to bytecode, and link an expression
882 %************************************************************************
886 compileExpr :: HscEnv
887 -> Module -> GlobalRdrEnv -> TypeEnv
891 compileExpr hsc_env this_mod rdr_env type_env tc_expr
892 = do { let { dflags = hsc_dflags hsc_env ;
893 lint_on = dopt Opt_DoCoreLinting dflags }
896 ; ds_expr <- deSugarExpr hsc_env this_mod rdr_env type_env tc_expr
899 ; flat_expr <- flattenExpr hsc_env ds_expr
902 ; simpl_expr <- simplifyExpr dflags flat_expr
904 -- Tidy it (temporary, until coreSat does cloning)
905 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
907 -- Prepare for codegen
908 ; prepd_expr <- corePrepExpr dflags tidy_expr
911 -- ToDo: improve SrcLoc
913 case lintUnfolding noSrcLoc [] prepd_expr of
914 Just err -> pprPanic "compileExpr" err
920 ; bcos <- coreExprToBCOs dflags prepd_expr
923 ; hval <- linkExpr hsc_env bcos
931 %************************************************************************
933 Statistics on reading interfaces
935 %************************************************************************
938 dumpIfaceStats :: HscEnv -> IO ()
939 dumpIfaceStats hsc_env
940 = do { eps <- readIORef (hsc_EPS hsc_env)
941 ; dumpIfSet (dump_if_trace || dump_rn_stats)
942 "Interface statistics"
945 dflags = hsc_dflags hsc_env
946 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
947 dump_if_trace = dopt Opt_D_dump_if_trace dflags
950 %************************************************************************
952 Progress Messages: Module i of n
954 %************************************************************************
957 showModuleIndex Nothing = ""
958 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
962 padded = replicate (length n_str - length i_str) ' ' ++ i_str