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 )
79 import CodeOutput ( codeOutput )
80 import NameEnv ( emptyNameEnv )
84 import UniqSupply ( mkSplitUniqSupply )
87 import HscStats ( ppSourceStats )
89 import MkExternalCore ( emitExternalCore )
91 import ParserCoreUtils
93 import UniqFM ( emptyUFM )
94 import Bag ( unitBag )
103 %************************************************************************
107 %************************************************************************
110 newHscEnv :: DynFlags -> IO HscEnv
112 = do { eps_var <- newIORef initExternalPackageState
113 ; us <- mkSplitUniqSupply 'r'
114 ; nc_var <- newIORef (initNameCache us knownKeyNames)
115 ; fc_var <- newIORef emptyUFM
116 ; mlc_var <- newIORef emptyModuleEnv
117 ; return (HscEnv { hsc_dflags = dflags,
120 hsc_IC = emptyInteractiveContext,
121 hsc_HPT = emptyHomePackageTable,
126 hsc_global_rdr_env = emptyGlobalRdrEnv,
127 hsc_global_type_env = emptyNameEnv } ) }
130 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
131 -- where templateHaskellNames are defined
132 knownKeyNames = map getName wiredInThings
133 ++ basicKnownKeyNames
135 ++ templateHaskellNames
140 %************************************************************************
142 The main compiler pipeline
144 %************************************************************************
146 --------------------------------
147 The compilation proper
148 --------------------------------
151 It's the task of the compilation proper to compile Haskell, hs-boot and
152 core files to either byte-code, hard-code (C, asm, Java, ect) or to
153 nothing at all (the module is still parsed and type-checked. This
154 feature is mostly used by IDE's and the likes).
155 Compilation can happen in either 'one-shot', 'batch', 'nothing',
156 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
157 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
159 The modes are kept separate because of their different types and meanings.
160 In 'one-shot' mode, we're only compiling a single file and can therefore
161 discard the new ModIface and ModDetails. This is also the reason it only
162 targets hard-code; compiling to byte-code or nothing doesn't make sense
163 when we discard the result.
164 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
165 and ModDetails. 'Batch' mode doesn't target byte-code since that require
166 us to return the newly compiled byte-code.
167 'Nothing' mode has exactly the same type as 'batch' mode but they're still
168 kept separate. This is because compiling to nothing is fairly special: We
169 don't output any interface files, we don't run the simplifier and we don't
171 'Interactive' mode is similar to 'batch' mode except that we return the
172 compiled byte-code together with the ModIface and ModDetails.
174 Trying to compile a hs-boot file to byte-code will result in a run-time
175 error. This is the only thing that isn't caught by the type-system.
182 (Located (HsModule RdrName))
184 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
185 Maybe (HsDoc Name), HaddockModInfo Name))
187 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
191 -- Status of a compilation to hard-code or nothing.
194 | HscRecomp Bool -- Has stub files.
195 -- This is a hack. We can't compile C files here
196 -- since it's done in DriverPipeline. For now we
197 -- just return True if we want the caller to compile
200 -- Status of a compilation to byte-code.
201 data InteractiveStatus
202 = InteractiveNoRecomp
203 | InteractiveRecomp Bool -- Same as HscStatus
207 -- I want Control.Monad.State! --Lemmih 03/07/2006
208 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
210 instance Monad Comp where
211 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
212 return a = Comp $ \s -> return (a,s)
215 evalComp :: Comp a -> CompState -> IO a
216 evalComp comp st = do (val,_st') <- runComp comp st
221 { compHscEnv :: HscEnv
222 , compModSummary :: ModSummary
223 , compOldIface :: Maybe ModIface
226 get :: Comp CompState
227 get = Comp $ \s -> return (s,s)
229 modify :: (CompState -> CompState) -> Comp ()
230 modify f = Comp $ \s -> return ((), f s)
232 gets :: (CompState -> a) -> Comp a
233 gets getter = do st <- get
236 liftIO :: IO a -> Comp a
237 liftIO ioA = Comp $ \s -> do a <- ioA
240 type NoRecomp result = ModIface -> Comp result
241 type FrontEnd core = Comp (Maybe core)
243 -- FIXME: The old interface and module index are only using in 'batch' and
244 -- 'interactive' mode. They should be removed from 'oneshot' mode.
245 type Compiler result = HscEnv
247 -> Bool -- True <=> source unchanged
248 -> Maybe ModIface -- Old interface, if available
249 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
253 -- This functions checks if recompilation is necessary and
254 -- then combines the FrontEnd and BackEnd to a working compiler.
255 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
256 -> (Maybe (Int,Int) -> Bool -> Comp ())
258 -> (core -> Comp result) -- Backend.
260 hscMkCompiler norecomp messenger frontend backend
261 hsc_env mod_summary source_unchanged
262 mbOldIface mbModIndex
263 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
264 do (recomp_reqd, mbCheckedIface)
265 <- {-# SCC "checkOldIface" #-}
266 liftIO $ checkOldIface hsc_env mod_summary
267 source_unchanged mbOldIface
268 -- save the interface that comes back from checkOldIface.
269 -- In one-shot mode we don't have the old iface until this
270 -- point, when checkOldIface reads it from the disk.
271 modify (\s -> s{ compOldIface = mbCheckedIface })
272 case mbCheckedIface of
273 Just iface | not recomp_reqd
274 -> do messenger mbModIndex False
275 result <- norecomp iface
278 -> do messenger mbModIndex True
284 -> do result <- backend core
287 --------------------------------------------------------------
289 --------------------------------------------------------------
292 -- Compile Haskell, boot and extCore in OneShot mode.
293 hscCompileOneShot :: Compiler HscStatus
294 hscCompileOneShot = hscCompileHardCode norecompOneShot oneShotMsg hscOneShot (hscConst (HscRecomp False))
296 -- Compile Haskell, boot and extCore in batch mode.
297 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
298 hscCompileBatch = hscCompileHardCode norecompBatch batchMsg hscBatch hscNothing
300 -- Compile to hardcode (C,asm,...). This general structure is shared by OneShot and Batch.
301 hscCompileHardCode :: NoRecomp result -- No recomp necessary
302 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
303 -> ((ModIface, ModDetails, CgGuts) -> Comp result) -- Compile normal file
304 -> ((ModIface, ModDetails, ModGuts) -> Comp result) -- Compile boot file
306 hscCompileHardCode norecomp msg compNormal compBoot hsc_env mod_summary =
307 compiler hsc_env mod_summary
308 where mkComp = hscMkCompiler norecomp msg
309 -- How to compile nonBoot files.
310 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
311 hscWriteIface >>= compNormal
312 -- How to compile boot files.
313 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= compBoot
315 = case ms_hsc_src mod_summary of
317 -> mkComp hscCoreFrontEnd nonBootComp
319 -> mkComp hscFileFrontEnd nonBootComp
321 -> mkComp hscFileFrontEnd bootComp
323 -- Type-check Haskell, boot and extCore.
324 -- Does it make sense to compile extCore to nothing?
325 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
326 hscCompileNothing hsc_env mod_summary
327 = compiler hsc_env mod_summary
328 where mkComp = hscMkCompiler norecompBatch batchMsg
329 pipeline inp = hscSimpleIface inp >>= hscIgnoreIface >>= hscNothing
331 = case ms_hsc_src mod_summary of
333 -> mkComp hscCoreFrontEnd pipeline
335 -> mkComp hscFileFrontEnd pipeline
337 -> mkComp hscFileFrontEnd pipeline
339 -- Compile Haskell, extCore to bytecode.
340 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
341 hscCompileInteractive hsc_env mod_summary =
342 hscMkCompiler norecompInteractive batchMsg
345 where backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
346 frontend = case ms_hsc_src mod_summary of
347 ExtCoreFile -> hscCoreFrontEnd
348 HsSrcFile -> hscFileFrontEnd
349 HsBootFile -> panic bootErrorMsg
350 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
351 "Use 'hscCompileBatch' instead."
353 --------------------------------------------------------------
355 --------------------------------------------------------------
357 norecompOneShot :: NoRecomp HscStatus
358 norecompOneShot old_iface
359 = do hsc_env <- gets compHscEnv
361 dumpIfaceStats hsc_env
364 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
365 norecompBatch = norecompWorker HscNoRecomp False
367 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
368 norecompInteractive = norecompWorker InteractiveNoRecomp True
370 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
371 norecompWorker a isInterp old_iface
372 = do hsc_env <- gets compHscEnv
373 mod_summary <- gets compModSummary
375 new_details <- {-# SCC "tcRnIface" #-}
376 initIfaceCheck hsc_env $
377 typecheckIface old_iface
378 dumpIfaceStats hsc_env
379 return (a, old_iface, new_details)
381 --------------------------------------------------------------
382 -- Progress displayers.
383 --------------------------------------------------------------
385 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
386 oneShotMsg _mb_mod_index recomp
387 = do hsc_env <- gets compHscEnv
391 else compilationProgressMsg (hsc_dflags hsc_env) $
392 "compilation IS NOT required"
394 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
395 batchMsg mb_mod_index recomp
396 = do hsc_env <- gets compHscEnv
397 mod_summary <- gets compModSummary
398 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
399 (showModuleIndex mb_mod_index ++
400 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
403 then showMsg "Compiling "
404 else if verbosity (hsc_dflags hsc_env) >= 2
405 then showMsg "Skipping "
408 --------------------------------------------------------------
410 --------------------------------------------------------------
412 hscCoreFrontEnd :: FrontEnd ModGuts
414 do hsc_env <- gets compHscEnv
415 mod_summary <- gets compModSummary
420 inp <- readFile (ms_hspp_file mod_summary)
421 case parseCore inp 1 of
423 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
427 -- RENAME and TYPECHECK
429 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
430 tcRnExtCore hsc_env rdr_module
431 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
432 case maybe_tc_result of
433 Nothing -> return Nothing
434 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
437 hscFileFrontEnd :: FrontEnd ModGuts
439 do hsc_env <- gets compHscEnv
440 mod_summary <- gets compModSummary
445 let dflags = hsc_dflags hsc_env
446 hspp_file = ms_hspp_file mod_summary
447 hspp_buf = ms_hspp_buf mod_summary
448 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
451 -> do printBagOfErrors dflags (unitBag err)
455 -- RENAME and TYPECHECK
457 -> do (tc_msgs, maybe_tc_result)
458 <- {-# SCC "Typecheck-Rename" #-}
459 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
460 printErrorsAndWarnings dflags tc_msgs
461 case maybe_tc_result of
468 -> {-# SCC "DeSugar" #-} deSugar hsc_env (ms_location mod_summary) tc_result
470 --------------------------------------------------------------
472 --------------------------------------------------------------
474 hscSimplify :: ModGuts -> Comp ModGuts
475 hscSimplify ds_result
476 = do hsc_env <- gets compHscEnv
478 flat_result <- {-# SCC "Flattening" #-}
479 flatten hsc_env ds_result
483 simpl_result <- {-# SCC "Core2Core" #-}
484 core2core hsc_env flat_result
487 --------------------------------------------------------------
488 -- Interface generators
489 --------------------------------------------------------------
491 -- HACK: we return ModGuts even though we know it's not gonna be used.
492 -- We do this because the type signature needs to be identical
493 -- in structure to the type of 'hscNormalIface'.
494 hscSimpleIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, ModGuts)
495 hscSimpleIface ds_result
496 = do hsc_env <- gets compHscEnv
497 mod_summary <- gets compModSummary
498 maybe_old_iface <- gets compOldIface
500 details <- mkBootModDetails hsc_env ds_result
501 (new_iface, no_change)
502 <- {-# SCC "MkFinalIface" #-}
503 mkIface hsc_env maybe_old_iface ds_result details
504 -- And the answer is ...
505 dumpIfaceStats hsc_env
506 return (new_iface, no_change, details, ds_result)
508 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
509 hscNormalIface simpl_result
510 = do hsc_env <- gets compHscEnv
511 mod_summary <- gets compModSummary
512 maybe_old_iface <- gets compOldIface
517 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
518 tidyProgram hsc_env simpl_result
521 -- BUILD THE NEW ModIface and ModDetails
522 -- and emit external core if necessary
523 -- This has to happen *after* code gen so that the back-end
524 -- info has been set. Not yet clear if it matters waiting
525 -- until after code output
526 (new_iface, no_change)
527 <- {-# SCC "MkFinalIface" #-}
528 mkIface hsc_env maybe_old_iface simpl_result details
529 -- Emit external core
530 emitExternalCore (hsc_dflags hsc_env) (availsToNameSet (mg_exports simpl_result)) cg_guts -- Move this? --Lemmih 03/07/2006
531 dumpIfaceStats hsc_env
534 -- Return the prepared code.
535 return (new_iface, no_change, details, cg_guts)
537 --------------------------------------------------------------
538 -- BackEnd combinators
539 --------------------------------------------------------------
541 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
542 hscWriteIface (iface, no_change, details, a)
543 = do mod_summary <- gets compModSummary
544 hsc_env <- gets compHscEnv
545 let dflags = hsc_dflags hsc_env
548 $ writeIfaceFile dflags (ms_location mod_summary) iface
549 return (iface, details, a)
551 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
552 hscIgnoreIface (iface, no_change, details, a)
553 = return (iface, details, a)
555 -- Don't output any code.
556 hscNothing :: (ModIface, ModDetails, a) -> Comp (HscStatus, ModIface, ModDetails)
557 hscNothing (iface, details, a)
558 = return (HscRecomp False, iface, details)
560 -- Generate code and return both the new ModIface and the ModDetails.
561 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (HscStatus, ModIface, ModDetails)
562 hscBatch (iface, details, cgguts)
563 = do hasStub <- hscCompile cgguts
564 return (HscRecomp hasStub, iface, details)
566 -- Here we don't need the ModIface and ModDetails anymore.
567 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp HscStatus
568 hscOneShot (_, _, cgguts)
569 = do hasStub <- hscCompile cgguts
570 return (HscRecomp hasStub)
572 -- Compile to hard-code.
573 hscCompile :: CgGuts -> Comp Bool
575 = do hsc_env <- gets compHscEnv
576 mod_summary <- gets compModSummary
578 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
579 -- From now on, we just use the bits we need.
580 cg_module = this_mod,
581 cg_binds = core_binds,
583 cg_dir_imps = dir_imps,
584 cg_foreign = foreign_stubs,
585 cg_dep_pkgs = dependencies,
586 cg_hpc_info = hpc_info } = cgguts
587 dflags = hsc_dflags hsc_env
588 location = ms_location mod_summary
589 data_tycons = filter isDataTyCon tycons
590 -- cg_tycons includes newtypes, for the benefit of External Core,
591 -- but we don't generate any code for newtypes
594 -- PREPARE FOR CODE GENERATION
595 -- Do saturation and convert to A-normal form
596 prepd_binds <- {-# SCC "CorePrep" #-}
597 corePrepPgm dflags core_binds data_tycons ;
598 ----------------- Convert to STG ------------------
599 (stg_binds, cost_centre_info)
600 <- {-# SCC "CoreToStg" #-}
601 myCoreToStg dflags this_mod prepd_binds
602 ------------------ Code generation ------------------
603 abstractC <- {-# SCC "CodeGen" #-}
604 codeGen dflags this_mod data_tycons
605 foreign_stubs dir_imps cost_centre_info
607 ------------------ Convert to CPS --------------------
608 continuationC <- cmmCPS dflags abstractC
609 ------------------ Code output -----------------------
610 (stub_h_exists,stub_c_exists)
611 <- codeOutput dflags this_mod location foreign_stubs
612 dependencies continuationC
615 hscConst :: b -> a -> Comp b
616 hscConst b a = return b
618 hscInteractive :: (ModIface, ModDetails, CgGuts)
619 -> Comp (InteractiveStatus, ModIface, ModDetails)
620 hscInteractive (iface, details, cgguts)
622 = do hsc_env <- gets compHscEnv
623 mod_summary <- gets compModSummary
625 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
626 -- From now on, we just use the bits we need.
627 cg_module = this_mod,
628 cg_binds = core_binds,
630 cg_foreign = foreign_stubs } = cgguts
631 dflags = hsc_dflags hsc_env
632 location = ms_location mod_summary
633 data_tycons = filter isDataTyCon tycons
634 -- cg_tycons includes newtypes, for the benefit of External Core,
635 -- but we don't generate any code for newtypes
638 -- PREPARE FOR CODE GENERATION
639 -- Do saturation and convert to A-normal form
640 prepd_binds <- {-# SCC "CorePrep" #-}
641 corePrepPgm dflags core_binds data_tycons ;
642 ----------------- Generate byte code ------------------
643 comp_bc <- byteCodeGen dflags prepd_binds data_tycons (md_modBreaks details)
644 ------------------ Create f-x-dynamic C-side stuff ---
645 (istub_h_exists, istub_c_exists)
646 <- outputForeignStubs dflags this_mod location foreign_stubs
647 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
649 = panic "GHC not compiled with interpreter"
652 ------------------------------
654 hscFileCheck :: HscEnv -> ModSummary -> Bool -> IO (Maybe HscChecked)
655 hscFileCheck hsc_env mod_summary compileToCore = do {
659 ; let dflags = hsc_dflags hsc_env
660 hspp_file = ms_hspp_file mod_summary
661 hspp_buf = ms_hspp_buf mod_summary
663 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
665 ; case maybe_parsed of {
666 Left err -> do { printBagOfErrors dflags (unitBag err)
668 Right rdr_module -> do {
671 -- RENAME and TYPECHECK
673 (tc_msgs, maybe_tc_result)
674 <- _scc_ "Typecheck-Rename"
675 tcRnModule hsc_env (ms_hsc_src mod_summary)
676 True{-save renamed syntax-}
679 ; printErrorsAndWarnings dflags tc_msgs
680 ; case maybe_tc_result of {
681 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing Nothing));
683 let type_env = tcg_type_env tc_result
686 md_exports = tcg_exports tc_result,
687 md_insts = tcg_insts tc_result,
688 md_fam_insts = tcg_fam_insts tc_result,
689 md_modBreaks = emptyModBreaks,
690 md_rules = [panic "no rules"],
691 -- Rules are CoreRules, not the
692 -- RuleDecls we get out of the typechecker
694 panic "HscMain.hscFileCheck: no VectInfo"
695 -- VectInfo is added by the Core
696 -- vectorisation pass
698 rnInfo = do decl <- tcg_rn_decls tc_result
699 imports <- tcg_rn_imports tc_result
700 let exports = tcg_rn_exports tc_result
701 let doc = tcg_doc tc_result
702 hmi = tcg_hmi tc_result
703 return (decl,imports,exports,doc,hmi)
705 if compileToCore then
706 deSugar hsc_env (ms_location mod_summary) tc_result
709 return (Just (HscChecked rdr_module
711 (Just (tcg_binds tc_result,
712 tcg_rdr_env tc_result,
714 (fmap mg_binds maybeModGuts)))
718 hscCmmFile :: DynFlags -> FilePath -> IO Bool
719 hscCmmFile dflags filename = do
720 maybe_cmm <- parseCmmFile dflags filename
722 Nothing -> return False
724 continuationC <- cmmCPS dflags [cmm]
725 codeOutput dflags no_mod no_loc NoStubs [] continuationC
728 no_mod = panic "hscCmmFile: no_mod"
729 no_loc = ModLocation{ ml_hs_file = Just filename,
730 ml_hi_file = panic "hscCmmFile: no hi file",
731 ml_obj_file = panic "hscCmmFile: no obj file" }
734 myParseModule dflags src_filename maybe_src_buf
735 = -------------------------- Parser ----------------
736 showPass dflags "Parser" >>
737 {-# SCC "Parser" #-} do
739 -- sometimes we already have the buffer in memory, perhaps
740 -- because we needed to parse the imports out of it, or get the
742 buf <- case maybe_src_buf of
744 Nothing -> hGetStringBuffer src_filename
746 let loc = mkSrcLoc (mkFastString src_filename) 1 0
748 case unP parseModule (mkPState buf loc dflags) of {
750 PFailed span err -> return (Left (mkPlainErrMsg span err));
752 POk pst rdr_module -> do {
754 let {ms = getMessages pst};
755 printErrorsAndWarnings dflags ms;
756 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
758 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
760 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
761 (ppSourceStats False rdr_module) ;
763 return (Right rdr_module)
764 -- ToDo: free the string buffer later.
768 myCoreToStg dflags this_mod prepd_binds
770 stg_binds <- {-# SCC "Core2Stg" #-}
771 coreToStg (thisPackage dflags) prepd_binds
773 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
774 stg2stg dflags this_mod stg_binds
776 return (stg_binds2, cost_centre_info)
780 %************************************************************************
782 \subsection{Compiling a do-statement}
784 %************************************************************************
786 When the UnlinkedBCOExpr is linked you get an HValue of type
788 When you run it you get a list of HValues that should be
789 the same length as the list of names; add them to the ClosureEnv.
791 A naked expression returns a singleton Name [it].
793 What you type The IO [HValue] that hscStmt returns
794 ------------- ------------------------------------
795 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
798 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
801 expr (of IO type) ==> expr >>= \ v -> return [v]
802 [NB: result not printed] bindings: [it]
805 expr (of non-IO type,
806 result showable) ==> let v = expr in print v >> return [v]
809 expr (of non-IO type,
810 result not showable) ==> error
814 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
816 -> String -- The statement
817 -> IO (Maybe ([Id], HValue))
820 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
821 ; case maybe_stmt of {
822 Nothing -> return Nothing ; -- Parse error
823 Just Nothing -> return Nothing ; -- Empty line
824 Just (Just parsed_stmt) -> do { -- The real stuff
826 -- Rename and typecheck it
827 let icontext = hsc_IC hsc_env
828 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
830 ; case maybe_tc_result of {
831 Nothing -> return Nothing ;
832 Just (ids, tc_expr) -> do {
835 ; let rdr_env = ic_rn_gbl_env icontext
836 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
837 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
839 ; case mb_ds_expr of {
840 Nothing -> return Nothing ;
843 -- Then desugar, code gen, and link it
844 ; let src_span = srcLocSpan interactiveSrcLoc
845 ; hval <- compileExpr hsc_env src_span ds_expr
847 ; return (Just (ids, hval))
850 hscTcExpr -- Typecheck an expression (but don't run it)
852 -> String -- The expression
855 hscTcExpr hsc_env expr
856 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
857 ; let icontext = hsc_IC hsc_env
858 ; case maybe_stmt of {
859 Nothing -> return Nothing ; -- Parse error
860 Just (Just (L _ (ExprStmt expr _ _)))
861 -> tcRnExpr hsc_env icontext expr ;
862 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
866 hscKcType -- Find the kind of a type
868 -> String -- The type
871 hscKcType hsc_env str
872 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
873 ; let icontext = hsc_IC hsc_env
874 ; case maybe_type of {
875 Just ty -> tcRnType hsc_env icontext ty ;
876 Nothing -> return Nothing } }
882 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
883 hscParseStmt = hscParseThing parseStmt
885 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
886 hscParseType = hscParseThing parseType
889 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
890 hscParseIdentifier = hscParseThing parseIdentifier
892 hscParseThing :: Outputable thing
894 -> DynFlags -> String
896 -- Nothing => Parse error (message already printed)
898 hscParseThing parser dflags str
899 = showPass dflags "Parser" >>
900 {-# SCC "Parser" #-} do
902 buf <- stringToStringBuffer str
904 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
906 case unP parser (mkPState buf loc dflags) of {
908 PFailed span err -> do { printError span err;
911 POk pst thing -> do {
913 let {ms = getMessages pst};
914 printErrorsAndWarnings dflags ms;
915 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
917 --ToDo: can't free the string buffer until we've finished this
918 -- compilation sweep and all the identifiers have gone away.
919 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
924 %************************************************************************
926 Desugar, simplify, convert to bytecode, and link an expression
928 %************************************************************************
932 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
934 compileExpr hsc_env srcspan ds_expr
935 = do { let { dflags = hsc_dflags hsc_env ;
936 lint_on = dopt Opt_DoCoreLinting dflags }
939 ; flat_expr <- flattenExpr hsc_env ds_expr
942 ; simpl_expr <- simplifyExpr dflags flat_expr
944 -- Tidy it (temporary, until coreSat does cloning)
945 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
947 -- Prepare for codegen
948 ; prepd_expr <- corePrepExpr dflags tidy_expr
951 -- ToDo: improve SrcLoc
953 let ictxt = hsc_IC hsc_env
954 tyvars = varSetElems (ic_tyvars ictxt)
956 case lintUnfolding noSrcLoc tyvars prepd_expr of
957 Just err -> pprPanic "compileExpr" err
963 ; bcos <- coreExprToBCOs dflags prepd_expr
966 ; hval <- linkExpr hsc_env srcspan bcos
974 %************************************************************************
976 Statistics on reading interfaces
978 %************************************************************************
981 dumpIfaceStats :: HscEnv -> IO ()
982 dumpIfaceStats hsc_env
983 = do { eps <- readIORef (hsc_EPS hsc_env)
984 ; dumpIfSet (dump_if_trace || dump_rn_stats)
985 "Interface statistics"
988 dflags = hsc_dflags hsc_env
989 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
990 dump_if_trace = dopt Opt_D_dump_if_trace dflags
993 %************************************************************************
995 Progress Messages: Module i of n
997 %************************************************************************
1000 showModuleIndex Nothing = ""
1001 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1005 padded = replicate (length n_str - length i_str) ' ' ++ i_str