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(..), LStmt, LHsType )
29 import CodeOutput ( outputForeignStubs )
30 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
31 import Linker ( HValue, linkExpr )
32 import CoreSyn ( CoreExpr )
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 )
41 import {- Kind parts of -} Type ( Kind )
42 import CoreLint ( lintUnfolding )
43 import DsMeta ( templateHaskellNames )
44 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan )
46 import VarEnv ( emptyTidyEnv )
50 import Module ( emptyModuleEnv, ModLocation(..) )
51 import RdrName ( GlobalRdrEnv, RdrName, emptyGlobalRdrEnv )
52 import HsSyn ( HsModule, LHsBinds, HsGroup, LIE, LImportDecl, HsDoc,
55 import SrcLoc ( Located(..) )
56 import StringBuffer ( hGetStringBuffer, stringToStringBuffer )
59 import SrcLoc ( mkSrcLoc )
60 import TcRnDriver ( tcRnModule, tcRnExtCore )
61 import TcIface ( typecheckIface )
62 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
63 import IfaceEnv ( initNameCache )
64 import LoadIface ( ifaceStats, initExternalPackageState )
65 import PrelInfo ( wiredInThings, basicKnownKeyNames )
66 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
67 import Desugar ( deSugar )
68 import Flattening ( flatten )
69 import SimplCore ( core2core )
70 import TidyPgm ( tidyProgram, mkBootModDetails )
71 import CorePrep ( corePrepPgm )
72 import CoreToStg ( coreToStg )
73 import TyCon ( isDataTyCon )
74 import Name ( Name, NamedThing(..) )
75 import SimplStg ( stg2stg )
76 import CodeGen ( codeGen )
77 import CmmParse ( parseCmmFile )
78 import CodeOutput ( codeOutput )
79 import NameEnv ( emptyNameEnv )
83 import UniqSupply ( mkSplitUniqSupply )
86 import HscStats ( ppSourceStats )
88 import MkExternalCore ( emitExternalCore )
90 import ParserCoreUtils
92 import UniqFM ( emptyUFM )
93 import Bag ( unitBag )
102 %************************************************************************
106 %************************************************************************
109 newHscEnv :: DynFlags -> IO HscEnv
111 = do { eps_var <- newIORef initExternalPackageState
112 ; us <- mkSplitUniqSupply 'r'
113 ; nc_var <- newIORef (initNameCache us knownKeyNames)
114 ; fc_var <- newIORef emptyUFM
115 ; mlc_var <- newIORef emptyModuleEnv
116 ; return (HscEnv { hsc_dflags = dflags,
119 hsc_IC = emptyInteractiveContext,
120 hsc_HPT = emptyHomePackageTable,
125 hsc_global_rdr_env = emptyGlobalRdrEnv,
126 hsc_global_type_env = emptyNameEnv } ) }
129 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
130 -- where templateHaskellNames are defined
131 knownKeyNames = map getName wiredInThings
132 ++ basicKnownKeyNames
134 ++ templateHaskellNames
139 %************************************************************************
141 The main compiler pipeline
143 %************************************************************************
145 --------------------------------
146 The compilation proper
147 --------------------------------
150 It's the task of the compilation proper to compile Haskell, hs-boot and
151 core files to either byte-code, hard-code (C, asm, Java, ect) or to
152 nothing at all (the module is still parsed and type-checked. This
153 feature is mostly used by IDE's and the likes).
154 Compilation can happen in either 'one-shot', 'batch', 'nothing',
155 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
156 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
158 The modes are kept separate because of their different types and meanings.
159 In 'one-shot' mode, we're only compiling a single file and can therefore
160 discard the new ModIface and ModDetails. This is also the reason it only
161 targets hard-code; compiling to byte-code or nothing doesn't make sense
162 when we discard the result.
163 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
164 and ModDetails. 'Batch' mode doesn't target byte-code since that require
165 us to return the newly compiled byte-code.
166 'Nothing' mode has exactly the same type as 'batch' mode but they're still
167 kept separate. This is because compiling to nothing is fairly special: We
168 don't output any interface files, we don't run the simplifier and we don't
170 'Interactive' mode is similar to 'batch' mode except that we return the
171 compiled byte-code together with the ModIface and ModDetails.
173 Trying to compile a hs-boot file to byte-code will result in a run-time
174 error. This is the only thing that isn't caught by the type-system.
181 (Located (HsModule RdrName))
183 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
184 Maybe (HsDoc Name), HaddockModInfo Name))
186 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
190 -- Status of a compilation to hard-code or nothing.
193 | HscRecomp Bool -- Has stub files.
194 -- This is a hack. We can't compile C files here
195 -- since it's done in DriverPipeline. For now we
196 -- just return True if we want the caller to compile
199 -- Status of a compilation to byte-code.
200 data InteractiveStatus
201 = InteractiveNoRecomp
202 | InteractiveRecomp Bool -- Same as HscStatus
206 -- I want Control.Monad.State! --Lemmih 03/07/2006
207 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
209 instance Monad Comp where
210 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
211 return a = Comp $ \s -> return (a,s)
214 evalComp :: Comp a -> CompState -> IO a
215 evalComp comp st = do (val,_st') <- runComp comp st
220 { compHscEnv :: HscEnv
221 , compModSummary :: ModSummary
222 , compOldIface :: Maybe ModIface
225 get :: Comp CompState
226 get = Comp $ \s -> return (s,s)
228 modify :: (CompState -> CompState) -> Comp ()
229 modify f = Comp $ \s -> return ((), f s)
231 gets :: (CompState -> a) -> Comp a
232 gets getter = do st <- get
235 liftIO :: IO a -> Comp a
236 liftIO ioA = Comp $ \s -> do a <- ioA
239 type NoRecomp result = ModIface -> Comp result
240 type FrontEnd core = Comp (Maybe core)
242 -- FIXME: The old interface and module index are only using in 'batch' and
243 -- 'interactive' mode. They should be removed from 'oneshot' mode.
244 type Compiler result = HscEnv
246 -> Bool -- True <=> source unchanged
247 -> Maybe ModIface -- Old interface, if available
248 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
252 -- This functions checks if recompilation is necessary and
253 -- then combines the FrontEnd and BackEnd to a working compiler.
254 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
255 -> (Maybe (Int,Int) -> Bool -> Comp ())
257 -> (core -> Comp result) -- Backend.
259 hscMkCompiler norecomp messenger frontend backend
260 hsc_env mod_summary source_unchanged
261 mbOldIface mbModIndex
262 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
263 do (recomp_reqd, mbCheckedIface)
264 <- {-# SCC "checkOldIface" #-}
265 liftIO $ checkOldIface hsc_env mod_summary
266 source_unchanged mbOldIface
267 -- save the interface that comes back from checkOldIface.
268 -- In one-shot mode we don't have the old iface until this
269 -- point, when checkOldIface reads it from the disk.
270 modify (\s -> s{ compOldIface = mbCheckedIface })
271 case mbCheckedIface of
272 Just iface | not recomp_reqd
273 -> do messenger mbModIndex False
274 result <- norecomp iface
277 -> do messenger mbModIndex True
283 -> do result <- backend core
286 --------------------------------------------------------------
288 --------------------------------------------------------------
291 -- Compile Haskell, boot and extCore in OneShot mode.
292 hscCompileOneShot :: Compiler HscStatus
293 hscCompileOneShot = hscCompileHardCode norecompOneShot oneShotMsg hscOneShot (hscConst (HscRecomp False))
295 -- Compile Haskell, boot and extCore in batch mode.
296 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
297 hscCompileBatch = hscCompileHardCode norecompBatch batchMsg hscBatch hscNothing
299 -- Compile to hardcode (C,asm,...). This general structure is shared by OneShot and Batch.
300 hscCompileHardCode :: NoRecomp result -- No recomp necessary
301 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
302 -> ((ModIface, ModDetails, CgGuts) -> Comp result) -- Compile normal file
303 -> ((ModIface, ModDetails, ModGuts) -> Comp result) -- Compile boot file
305 hscCompileHardCode norecomp msg compNormal compBoot hsc_env mod_summary =
306 compiler hsc_env mod_summary
307 where mkComp = hscMkCompiler norecomp msg
308 -- How to compile nonBoot files.
309 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
310 hscWriteIface >>= compNormal
311 -- How to compile boot files.
312 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= compBoot
314 = case ms_hsc_src mod_summary of
316 -> mkComp hscCoreFrontEnd nonBootComp
318 -> mkComp hscFileFrontEnd nonBootComp
320 -> mkComp hscFileFrontEnd bootComp
322 -- Type-check Haskell, boot and extCore.
323 -- Does it make sense to compile extCore to nothing?
324 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
325 hscCompileNothing hsc_env mod_summary
326 = compiler hsc_env mod_summary
327 where mkComp = hscMkCompiler norecompBatch batchMsg
328 pipeline inp = hscSimpleIface inp >>= hscIgnoreIface >>= hscNothing
330 = case ms_hsc_src mod_summary of
332 -> mkComp hscCoreFrontEnd pipeline
334 -> mkComp hscFileFrontEnd pipeline
336 -> mkComp hscFileFrontEnd pipeline
338 -- Compile Haskell, extCore to bytecode.
339 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
340 hscCompileInteractive hsc_env mod_summary =
341 hscMkCompiler norecompInteractive batchMsg
344 where backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
345 frontend = case ms_hsc_src mod_summary of
346 ExtCoreFile -> hscCoreFrontEnd
347 HsSrcFile -> hscFileFrontEnd
348 HsBootFile -> panic bootErrorMsg
349 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
350 "Use 'hscCompileBatch' instead."
352 --------------------------------------------------------------
354 --------------------------------------------------------------
356 norecompOneShot :: NoRecomp HscStatus
357 norecompOneShot old_iface
358 = do hsc_env <- gets compHscEnv
360 dumpIfaceStats hsc_env
363 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
364 norecompBatch = norecompWorker HscNoRecomp False
366 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
367 norecompInteractive = norecompWorker InteractiveNoRecomp True
369 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
370 norecompWorker a isInterp old_iface
371 = do hsc_env <- gets compHscEnv
372 mod_summary <- gets compModSummary
374 new_details <- {-# SCC "tcRnIface" #-}
375 initIfaceCheck hsc_env $
376 typecheckIface old_iface
377 dumpIfaceStats hsc_env
378 return (a, old_iface, new_details)
380 --------------------------------------------------------------
381 -- Progress displayers.
382 --------------------------------------------------------------
384 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
385 oneShotMsg _mb_mod_index recomp
386 = do hsc_env <- gets compHscEnv
390 else compilationProgressMsg (hsc_dflags hsc_env) $
391 "compilation IS NOT required"
393 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
394 batchMsg mb_mod_index recomp
395 = do hsc_env <- gets compHscEnv
396 mod_summary <- gets compModSummary
397 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
398 (showModuleIndex mb_mod_index ++
399 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
402 then showMsg "Compiling "
403 else if verbosity (hsc_dflags hsc_env) >= 2
404 then showMsg "Skipping "
407 --------------------------------------------------------------
409 --------------------------------------------------------------
411 hscCoreFrontEnd :: FrontEnd ModGuts
413 do hsc_env <- gets compHscEnv
414 mod_summary <- gets compModSummary
419 inp <- readFile (ms_hspp_file mod_summary)
420 case parseCore inp 1 of
422 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
426 -- RENAME and TYPECHECK
428 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
429 tcRnExtCore hsc_env rdr_module
430 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
431 case maybe_tc_result of
432 Nothing -> return Nothing
433 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
436 hscFileFrontEnd :: FrontEnd ModGuts
438 do hsc_env <- gets compHscEnv
439 mod_summary <- gets compModSummary
444 let dflags = hsc_dflags hsc_env
445 hspp_file = ms_hspp_file mod_summary
446 hspp_buf = ms_hspp_buf mod_summary
447 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
450 -> do printBagOfErrors dflags (unitBag err)
454 -- RENAME and TYPECHECK
456 -> do (tc_msgs, maybe_tc_result)
457 <- {-# SCC "Typecheck-Rename" #-}
458 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
459 printErrorsAndWarnings dflags tc_msgs
460 case maybe_tc_result of
467 -> {-# SCC "DeSugar" #-} deSugar hsc_env (ms_location mod_summary) tc_result
469 --------------------------------------------------------------
471 --------------------------------------------------------------
473 hscSimplify :: ModGuts -> Comp ModGuts
474 hscSimplify ds_result
475 = do hsc_env <- gets compHscEnv
477 flat_result <- {-# SCC "Flattening" #-}
478 flatten hsc_env ds_result
482 simpl_result <- {-# SCC "Core2Core" #-}
483 core2core hsc_env flat_result
486 --------------------------------------------------------------
487 -- Interface generators
488 --------------------------------------------------------------
490 -- HACK: we return ModGuts even though we know it's not gonna be used.
491 -- We do this because the type signature needs to be identical
492 -- in structure to the type of 'hscNormalIface'.
493 hscSimpleIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, ModGuts)
494 hscSimpleIface ds_result
495 = do hsc_env <- gets compHscEnv
496 mod_summary <- gets compModSummary
497 maybe_old_iface <- gets compOldIface
499 details <- mkBootModDetails hsc_env ds_result
500 (new_iface, no_change)
501 <- {-# SCC "MkFinalIface" #-}
502 mkIface hsc_env maybe_old_iface ds_result details
503 -- And the answer is ...
504 dumpIfaceStats hsc_env
505 return (new_iface, no_change, details, ds_result)
507 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
508 hscNormalIface simpl_result
509 = do hsc_env <- gets compHscEnv
510 mod_summary <- gets compModSummary
511 maybe_old_iface <- gets compOldIface
516 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
517 tidyProgram hsc_env simpl_result
520 -- BUILD THE NEW ModIface and ModDetails
521 -- and emit external core if necessary
522 -- This has to happen *after* code gen so that the back-end
523 -- info has been set. Not yet clear if it matters waiting
524 -- until after code output
525 (new_iface, no_change)
526 <- {-# SCC "MkFinalIface" #-}
527 mkIface hsc_env maybe_old_iface simpl_result details
528 -- Emit external core
529 emitExternalCore (hsc_dflags hsc_env) (availsToNameSet (mg_exports simpl_result)) cg_guts -- Move this? --Lemmih 03/07/2006
530 dumpIfaceStats hsc_env
533 -- Return the prepared code.
534 return (new_iface, no_change, details, cg_guts)
536 --------------------------------------------------------------
537 -- BackEnd combinators
538 --------------------------------------------------------------
540 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
541 hscWriteIface (iface, no_change, details, a)
542 = do mod_summary <- gets compModSummary
543 hsc_env <- gets compHscEnv
544 let dflags = hsc_dflags hsc_env
547 $ writeIfaceFile dflags (ms_location mod_summary) iface
548 return (iface, details, a)
550 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
551 hscIgnoreIface (iface, no_change, details, a)
552 = return (iface, details, a)
554 -- Don't output any code.
555 hscNothing :: (ModIface, ModDetails, a) -> Comp (HscStatus, ModIface, ModDetails)
556 hscNothing (iface, details, a)
557 = return (HscRecomp False, iface, details)
559 -- Generate code and return both the new ModIface and the ModDetails.
560 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (HscStatus, ModIface, ModDetails)
561 hscBatch (iface, details, cgguts)
562 = do hasStub <- hscCompile cgguts
563 return (HscRecomp hasStub, iface, details)
565 -- Here we don't need the ModIface and ModDetails anymore.
566 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp HscStatus
567 hscOneShot (_, _, cgguts)
568 = do hasStub <- hscCompile cgguts
569 return (HscRecomp hasStub)
571 -- Compile to hard-code.
572 hscCompile :: CgGuts -> Comp Bool
574 = do hsc_env <- gets compHscEnv
575 mod_summary <- gets compModSummary
577 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
578 -- From now on, we just use the bits we need.
579 cg_module = this_mod,
580 cg_binds = core_binds,
582 cg_dir_imps = dir_imps,
583 cg_foreign = foreign_stubs,
584 cg_dep_pkgs = dependencies,
585 cg_hpc_info = hpc_info } = cgguts
586 dflags = hsc_dflags hsc_env
587 location = ms_location mod_summary
588 data_tycons = filter isDataTyCon tycons
589 -- cg_tycons includes newtypes, for the benefit of External Core,
590 -- but we don't generate any code for newtypes
593 -- PREPARE FOR CODE GENERATION
594 -- Do saturation and convert to A-normal form
595 prepd_binds <- {-# SCC "CorePrep" #-}
596 corePrepPgm dflags core_binds data_tycons ;
597 ----------------- Convert to STG ------------------
598 (stg_binds, cost_centre_info)
599 <- {-# SCC "CoreToStg" #-}
600 myCoreToStg dflags this_mod prepd_binds
601 ------------------ Code generation ------------------
602 abstractC <- {-# SCC "CodeGen" #-}
603 codeGen dflags this_mod data_tycons
604 foreign_stubs dir_imps cost_centre_info
606 ------------------ Code output -----------------------
607 (stub_h_exists,stub_c_exists)
608 <- codeOutput dflags this_mod location foreign_stubs
609 dependencies abstractC
612 hscConst :: b -> a -> Comp b
613 hscConst b a = return b
615 hscInteractive :: (ModIface, ModDetails, CgGuts)
616 -> Comp (InteractiveStatus, ModIface, ModDetails)
617 hscInteractive (iface, details, cgguts)
619 = do hsc_env <- gets compHscEnv
620 mod_summary <- gets compModSummary
622 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
623 -- From now on, we just use the bits we need.
624 cg_module = this_mod,
625 cg_binds = core_binds,
627 cg_foreign = foreign_stubs } = cgguts
628 dflags = hsc_dflags hsc_env
629 location = ms_location mod_summary
630 data_tycons = filter isDataTyCon tycons
631 -- cg_tycons includes newtypes, for the benefit of External Core,
632 -- but we don't generate any code for newtypes
635 -- PREPARE FOR CODE GENERATION
636 -- Do saturation and convert to A-normal form
637 prepd_binds <- {-# SCC "CorePrep" #-}
638 corePrepPgm dflags core_binds data_tycons ;
639 ----------------- Generate byte code ------------------
640 comp_bc <- byteCodeGen dflags prepd_binds data_tycons (md_modBreaks details)
641 ------------------ Create f-x-dynamic C-side stuff ---
642 (istub_h_exists, istub_c_exists)
643 <- outputForeignStubs dflags this_mod location foreign_stubs
644 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
646 = panic "GHC not compiled with interpreter"
649 ------------------------------
651 hscFileCheck :: HscEnv -> ModSummary -> Bool -> IO (Maybe HscChecked)
652 hscFileCheck hsc_env mod_summary compileToCore = do {
656 ; let dflags = hsc_dflags hsc_env
657 hspp_file = ms_hspp_file mod_summary
658 hspp_buf = ms_hspp_buf mod_summary
660 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
662 ; case maybe_parsed of {
663 Left err -> do { printBagOfErrors dflags (unitBag err)
665 Right rdr_module -> do {
668 -- RENAME and TYPECHECK
670 (tc_msgs, maybe_tc_result)
671 <- _scc_ "Typecheck-Rename"
672 tcRnModule hsc_env (ms_hsc_src mod_summary)
673 True{-save renamed syntax-}
676 ; printErrorsAndWarnings dflags tc_msgs
677 ; case maybe_tc_result of {
678 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing Nothing));
680 let type_env = tcg_type_env tc_result
683 md_exports = tcg_exports tc_result,
684 md_insts = tcg_insts tc_result,
685 md_fam_insts = tcg_fam_insts tc_result,
686 md_modBreaks = emptyModBreaks,
687 md_rules = [panic "no rules"],
688 -- Rules are CoreRules, not the
689 -- RuleDecls we get out of the typechecker
691 panic "HscMain.hscFileCheck: no VectInfo"
692 -- VectInfo is added by the Core
693 -- vectorisation pass
695 rnInfo = do decl <- tcg_rn_decls tc_result
696 imports <- tcg_rn_imports tc_result
697 let exports = tcg_rn_exports tc_result
698 let doc = tcg_doc tc_result
699 hmi = tcg_hmi tc_result
700 return (decl,imports,exports,doc,hmi)
702 if compileToCore then
703 deSugar hsc_env (ms_location mod_summary) tc_result
706 return (Just (HscChecked rdr_module
708 (Just (tcg_binds tc_result,
709 tcg_rdr_env tc_result,
711 (fmap mg_binds maybeModGuts)))
715 hscCmmFile :: DynFlags -> FilePath -> IO Bool
716 hscCmmFile dflags filename = do
717 maybe_cmm <- parseCmmFile dflags filename
719 Nothing -> return False
721 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
724 no_mod = panic "hscCmmFile: no_mod"
725 no_loc = ModLocation{ ml_hs_file = Just filename,
726 ml_hi_file = panic "hscCmmFile: no hi file",
727 ml_obj_file = panic "hscCmmFile: no obj file" }
730 myParseModule dflags src_filename maybe_src_buf
731 = -------------------------- Parser ----------------
732 showPass dflags "Parser" >>
733 {-# SCC "Parser" #-} do
735 -- sometimes we already have the buffer in memory, perhaps
736 -- because we needed to parse the imports out of it, or get the
738 buf <- case maybe_src_buf of
740 Nothing -> hGetStringBuffer src_filename
742 let loc = mkSrcLoc (mkFastString src_filename) 1 0
744 case unP parseModule (mkPState buf loc dflags) of {
746 PFailed span err -> return (Left (mkPlainErrMsg span err));
748 POk pst rdr_module -> do {
750 let {ms = getMessages pst};
751 printErrorsAndWarnings dflags ms;
752 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
754 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
756 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
757 (ppSourceStats False rdr_module) ;
759 return (Right rdr_module)
760 -- ToDo: free the string buffer later.
764 myCoreToStg dflags this_mod prepd_binds
766 stg_binds <- {-# SCC "Core2Stg" #-}
767 coreToStg (thisPackage dflags) prepd_binds
769 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
770 stg2stg dflags this_mod stg_binds
772 return (stg_binds2, cost_centre_info)
776 %************************************************************************
778 \subsection{Compiling a do-statement}
780 %************************************************************************
782 When the UnlinkedBCOExpr is linked you get an HValue of type
784 When you run it you get a list of HValues that should be
785 the same length as the list of names; add them to the ClosureEnv.
787 A naked expression returns a singleton Name [it].
789 What you type The IO [HValue] that hscStmt returns
790 ------------- ------------------------------------
791 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
794 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
797 expr (of IO type) ==> expr >>= \ v -> return [v]
798 [NB: result not printed] bindings: [it]
801 expr (of non-IO type,
802 result showable) ==> let v = expr in print v >> return [v]
805 expr (of non-IO type,
806 result not showable) ==> error
810 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
812 -> String -- The statement
813 -> IO (Maybe ([Id], HValue))
816 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
817 ; case maybe_stmt of {
818 Nothing -> return Nothing ; -- Parse error
819 Just Nothing -> return Nothing ; -- Empty line
820 Just (Just parsed_stmt) -> do { -- The real stuff
822 -- Rename and typecheck it
823 let icontext = hsc_IC hsc_env
824 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
826 ; case maybe_tc_result of {
827 Nothing -> return Nothing ;
828 Just (ids, tc_expr) -> do {
831 ; let rdr_env = ic_rn_gbl_env icontext
832 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
833 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
835 ; case mb_ds_expr of {
836 Nothing -> return Nothing ;
839 -- Then desugar, code gen, and link it
840 ; let src_span = srcLocSpan interactiveSrcLoc
841 ; hval <- compileExpr hsc_env src_span ds_expr
843 ; return (Just (ids, hval))
846 hscTcExpr -- Typecheck an expression (but don't run it)
848 -> String -- The expression
851 hscTcExpr hsc_env expr
852 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
853 ; let icontext = hsc_IC hsc_env
854 ; case maybe_stmt of {
855 Nothing -> return Nothing ; -- Parse error
856 Just (Just (L _ (ExprStmt expr _ _)))
857 -> tcRnExpr hsc_env icontext expr ;
858 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
862 hscKcType -- Find the kind of a type
864 -> String -- The type
867 hscKcType hsc_env str
868 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
869 ; let icontext = hsc_IC hsc_env
870 ; case maybe_type of {
871 Just ty -> tcRnType hsc_env icontext ty ;
872 Nothing -> return Nothing } }
878 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
879 hscParseStmt = hscParseThing parseStmt
881 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
882 hscParseType = hscParseThing parseType
885 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
886 hscParseIdentifier = hscParseThing parseIdentifier
888 hscParseThing :: Outputable thing
890 -> DynFlags -> String
892 -- Nothing => Parse error (message already printed)
894 hscParseThing parser dflags str
895 = showPass dflags "Parser" >>
896 {-# SCC "Parser" #-} do
898 buf <- stringToStringBuffer str
900 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
902 case unP parser (mkPState buf loc dflags) of {
904 PFailed span err -> do { printError span err;
907 POk pst thing -> do {
909 let {ms = getMessages pst};
910 printErrorsAndWarnings dflags ms;
911 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
913 --ToDo: can't free the string buffer until we've finished this
914 -- compilation sweep and all the identifiers have gone away.
915 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
920 %************************************************************************
922 Desugar, simplify, convert to bytecode, and link an expression
924 %************************************************************************
928 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
930 compileExpr hsc_env srcspan ds_expr
931 = do { let { dflags = hsc_dflags hsc_env ;
932 lint_on = dopt Opt_DoCoreLinting dflags }
935 ; flat_expr <- flattenExpr hsc_env ds_expr
938 ; simpl_expr <- simplifyExpr dflags flat_expr
940 -- Tidy it (temporary, until coreSat does cloning)
941 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
943 -- Prepare for codegen
944 ; prepd_expr <- corePrepExpr dflags tidy_expr
947 -- ToDo: improve SrcLoc
949 let ictxt = hsc_IC hsc_env
950 tyvars = varSetElems (ic_tyvars ictxt)
952 case lintUnfolding noSrcLoc tyvars prepd_expr of
953 Just err -> pprPanic "compileExpr" err
959 ; bcos <- coreExprToBCOs dflags prepd_expr
962 ; hval <- linkExpr hsc_env srcspan bcos
970 %************************************************************************
972 Statistics on reading interfaces
974 %************************************************************************
977 dumpIfaceStats :: HscEnv -> IO ()
978 dumpIfaceStats hsc_env
979 = do { eps <- readIORef (hsc_EPS hsc_env)
980 ; dumpIfSet (dump_if_trace || dump_rn_stats)
981 "Interface statistics"
984 dflags = hsc_dflags hsc_env
985 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
986 dump_if_trace = dopt Opt_D_dump_if_trace dflags
989 %************************************************************************
991 Progress Messages: Module i of n
993 %************************************************************************
996 showModuleIndex Nothing = ""
997 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1001 padded = replicate (length n_str - length i_str) ' ' ++ i_str