2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 ( newHscEnv, hscCmmFile
20 , hscStmt, hscTcExpr, hscKcType
23 , hscCompileOneShot -- :: Compiler HscStatus
24 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
25 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
26 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
28 , InteractiveStatus (..)
32 #include "HsVersions.h"
35 import HsSyn ( Stmt(..), LStmt, LHsType )
36 import CodeOutput ( outputForeignStubs )
37 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
38 import Linker ( HValue, linkExpr )
39 import CoreSyn ( CoreExpr )
40 import CoreTidy ( tidyExpr )
41 import CorePrep ( corePrepExpr )
42 import Flattening ( flattenExpr )
43 import Desugar ( deSugarExpr )
44 import SimplCore ( simplifyExpr )
45 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
47 import PrelNames ( iNTERACTIVE )
48 import {- Kind parts of -} Type ( Kind )
49 import CoreLint ( lintUnfolding )
50 import DsMeta ( templateHaskellNames )
51 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan )
53 import VarEnv ( emptyTidyEnv )
57 import Module ( emptyModuleEnv, ModLocation(..) )
58 import RdrName ( GlobalRdrEnv, RdrName, emptyGlobalRdrEnv )
59 import HsSyn ( HsModule, LHsBinds, HsGroup, LIE, LImportDecl, HsDoc,
62 import SrcLoc ( Located(..) )
66 import SrcLoc ( mkSrcLoc )
67 import TcRnDriver ( tcRnModule, tcRnExtCore )
68 import TcIface ( typecheckIface )
69 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
70 import IfaceEnv ( initNameCache )
71 import LoadIface ( ifaceStats, initExternalPackageState )
72 import PrelInfo ( wiredInThings, basicKnownKeyNames )
73 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
74 import Desugar ( deSugar )
75 import Flattening ( flatten )
76 import SimplCore ( core2core )
77 import TidyPgm ( tidyProgram, mkBootModDetails )
78 import CorePrep ( corePrepPgm )
79 import CoreToStg ( coreToStg )
80 import TyCon ( isDataTyCon )
81 import Name ( Name, NamedThing(..) )
82 import SimplStg ( stg2stg )
83 import CodeGen ( codeGen )
84 import CmmParse ( parseCmmFile )
87 import CodeOutput ( codeOutput )
88 import NameEnv ( emptyNameEnv )
92 import UniqSupply ( mkSplitUniqSupply )
95 import HscStats ( ppSourceStats )
97 import MkExternalCore ( emitExternalCore )
99 import ParserCoreUtils
101 import UniqFM ( emptyUFM )
102 import Bag ( unitBag )
111 %************************************************************************
115 %************************************************************************
118 newHscEnv :: DynFlags -> IO HscEnv
120 = do { eps_var <- newIORef initExternalPackageState
121 ; us <- mkSplitUniqSupply 'r'
122 ; nc_var <- newIORef (initNameCache us knownKeyNames)
123 ; fc_var <- newIORef emptyUFM
124 ; mlc_var <- newIORef emptyModuleEnv
125 ; return (HscEnv { hsc_dflags = dflags,
128 hsc_IC = emptyInteractiveContext,
129 hsc_HPT = emptyHomePackageTable,
134 hsc_global_rdr_env = emptyGlobalRdrEnv,
135 hsc_global_type_env = emptyNameEnv } ) }
138 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
139 -- where templateHaskellNames are defined
140 knownKeyNames = map getName wiredInThings
141 ++ basicKnownKeyNames
143 ++ templateHaskellNames
148 %************************************************************************
150 The main compiler pipeline
152 %************************************************************************
154 --------------------------------
155 The compilation proper
156 --------------------------------
159 It's the task of the compilation proper to compile Haskell, hs-boot and
160 core files to either byte-code, hard-code (C, asm, Java, ect) or to
161 nothing at all (the module is still parsed and type-checked. This
162 feature is mostly used by IDE's and the likes).
163 Compilation can happen in either 'one-shot', 'batch', 'nothing',
164 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
165 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
167 The modes are kept separate because of their different types and meanings.
168 In 'one-shot' mode, we're only compiling a single file and can therefore
169 discard the new ModIface and ModDetails. This is also the reason it only
170 targets hard-code; compiling to byte-code or nothing doesn't make sense
171 when we discard the result.
172 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
173 and ModDetails. 'Batch' mode doesn't target byte-code since that require
174 us to return the newly compiled byte-code.
175 'Nothing' mode has exactly the same type as 'batch' mode but they're still
176 kept separate. This is because compiling to nothing is fairly special: We
177 don't output any interface files, we don't run the simplifier and we don't
179 'Interactive' mode is similar to 'batch' mode except that we return the
180 compiled byte-code together with the ModIface and ModDetails.
182 Trying to compile a hs-boot file to byte-code will result in a run-time
183 error. This is the only thing that isn't caught by the type-system.
190 (Located (HsModule RdrName))
192 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
193 Maybe (HsDoc Name), HaddockModInfo Name))
195 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
199 -- Status of a compilation to hard-code or nothing.
202 | HscRecomp Bool -- Has stub files.
203 -- This is a hack. We can't compile C files here
204 -- since it's done in DriverPipeline. For now we
205 -- just return True if we want the caller to compile
208 -- Status of a compilation to byte-code.
209 data InteractiveStatus
210 = InteractiveNoRecomp
211 | InteractiveRecomp Bool -- Same as HscStatus
216 -- I want Control.Monad.State! --Lemmih 03/07/2006
217 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
219 instance Monad Comp where
220 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
221 return a = Comp $ \s -> return (a,s)
224 evalComp :: Comp a -> CompState -> IO a
225 evalComp comp st = do (val,_st') <- runComp comp st
230 { compHscEnv :: HscEnv
231 , compModSummary :: ModSummary
232 , compOldIface :: Maybe ModIface
235 get :: Comp CompState
236 get = Comp $ \s -> return (s,s)
238 modify :: (CompState -> CompState) -> Comp ()
239 modify f = Comp $ \s -> return ((), f s)
241 gets :: (CompState -> a) -> Comp a
242 gets getter = do st <- get
245 liftIO :: IO a -> Comp a
246 liftIO ioA = Comp $ \s -> do a <- ioA
249 type NoRecomp result = ModIface -> Comp result
251 -- FIXME: The old interface and module index are only using in 'batch' and
252 -- 'interactive' mode. They should be removed from 'oneshot' mode.
253 type Compiler result = HscEnv
255 -> Bool -- True <=> source unchanged
256 -> Maybe ModIface -- Old interface, if available
257 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
261 -- This functions checks if recompilation is necessary and
262 -- then combines the FrontEnd and BackEnd to a working compiler.
263 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
264 -> (Maybe (Int,Int) -> Bool -> Comp ())
265 -> Comp (Maybe ModGuts) -- Front end
266 -> (ModGuts -> Comp result) -- Backend.
268 hscMkCompiler norecomp messenger frontend backend
269 hsc_env mod_summary source_unchanged
270 mbOldIface mbModIndex
271 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
272 do (recomp_reqd, mbCheckedIface)
273 <- {-# SCC "checkOldIface" #-}
274 liftIO $ checkOldIface hsc_env mod_summary
275 source_unchanged mbOldIface
276 -- save the interface that comes back from checkOldIface.
277 -- In one-shot mode we don't have the old iface until this
278 -- point, when checkOldIface reads it from the disk.
279 modify (\s -> s{ compOldIface = mbCheckedIface })
280 case mbCheckedIface of
281 Just iface | not recomp_reqd
282 -> do messenger mbModIndex False
283 result <- norecomp iface
286 -> do messenger mbModIndex True
292 -> do result <- backend core
295 --------------------------------------------------------------
297 --------------------------------------------------------------
299 -- Compile Haskell, boot and extCore in OneShot mode.
300 hscCompileOneShot :: Compiler HscStatus
302 = hscCompiler norecompOneShot oneShotMsg backend boot_backend
304 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscOneShot
305 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >> return (HscRecomp False)
307 -- Compile Haskell, boot and extCore in batch mode.
308 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
310 = hscCompiler norecompBatch batchMsg backend boot_backend
312 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscBatch
313 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
315 -- Type-check Haskell, boot and extCore.
316 -- Does it make sense to compile extCore to nothing?
317 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
319 = hscCompiler norecompBatch batchMsg backend backend
321 backend inp = hscSimpleIface inp >>= hscIgnoreIface >>= hscNothing
323 -- Compile Haskell, extCore to bytecode.
324 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
325 hscCompileInteractive
326 = hscCompiler norecompInteractive batchMsg backend boot_backend
328 backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
329 boot_backend = panic "hscCompileInteractive: can't do boot files here"
332 :: NoRecomp result -- No recomp necessary
333 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
334 -> (ModGuts -> Comp result) -- Compile normal file
335 -> (ModGuts -> Comp result) -- Compile boot file
337 hscCompiler norecomp msg nonBootComp bootComp hsc_env mod_summary =
338 hscMkCompiler norecomp msg frontend backend hsc_env mod_summary
341 = case ms_hsc_src mod_summary of
342 ExtCoreFile -> (hscCoreFrontEnd, nonBootComp)
343 HsSrcFile -> (hscFileFrontEnd, nonBootComp)
344 HsBootFile -> (hscFileFrontEnd, bootComp)
346 --------------------------------------------------------------
348 --------------------------------------------------------------
350 norecompOneShot :: NoRecomp HscStatus
351 norecompOneShot old_iface
352 = do hsc_env <- gets compHscEnv
354 dumpIfaceStats hsc_env
357 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
358 norecompBatch = norecompWorker HscNoRecomp False
360 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
361 norecompInteractive = norecompWorker InteractiveNoRecomp True
363 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
364 norecompWorker a isInterp old_iface
365 = do hsc_env <- gets compHscEnv
366 mod_summary <- gets compModSummary
368 new_details <- {-# SCC "tcRnIface" #-}
369 initIfaceCheck hsc_env $
370 typecheckIface old_iface
371 dumpIfaceStats hsc_env
372 return (a, old_iface, new_details)
374 --------------------------------------------------------------
375 -- Progress displayers.
376 --------------------------------------------------------------
378 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
379 oneShotMsg _mb_mod_index recomp
380 = do hsc_env <- gets compHscEnv
384 else compilationProgressMsg (hsc_dflags hsc_env) $
385 "compilation IS NOT required"
387 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
388 batchMsg mb_mod_index recomp
389 = do hsc_env <- gets compHscEnv
390 mod_summary <- gets compModSummary
391 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
392 (showModuleIndex mb_mod_index ++
393 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
396 then showMsg "Compiling "
397 else if verbosity (hsc_dflags hsc_env) >= 2
398 then showMsg "Skipping "
401 --------------------------------------------------------------
403 --------------------------------------------------------------
405 hscCoreFrontEnd :: Comp (Maybe ModGuts)
407 do hsc_env <- gets compHscEnv
408 mod_summary <- gets compModSummary
413 inp <- readFile (ms_hspp_file mod_summary)
414 case parseCore inp 1 of
416 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
420 -- RENAME and TYPECHECK
422 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
423 tcRnExtCore hsc_env rdr_module
424 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
425 case maybe_tc_result of
426 Nothing -> return Nothing
427 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
430 hscFileFrontEnd :: Comp (Maybe ModGuts)
432 do hsc_env <- gets compHscEnv
433 mod_summary <- gets compModSummary
438 let dflags = hsc_dflags hsc_env
439 hspp_file = ms_hspp_file mod_summary
440 hspp_buf = ms_hspp_buf mod_summary
441 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
444 -> do printBagOfErrors dflags (unitBag err)
448 -- RENAME and TYPECHECK
450 -> do (tc_msgs, maybe_tc_result)
451 <- {-# SCC "Typecheck-Rename" #-}
452 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
453 printErrorsAndWarnings dflags tc_msgs
454 case maybe_tc_result of
461 -> {-# SCC "DeSugar" #-} deSugar hsc_env (ms_location mod_summary) tc_result
463 --------------------------------------------------------------
465 --------------------------------------------------------------
467 hscSimplify :: ModGuts -> Comp ModGuts
468 hscSimplify ds_result
469 = do hsc_env <- gets compHscEnv
474 simpl_result <- {-# SCC "Core2Core" #-}
475 core2core hsc_env ds_result
478 --------------------------------------------------------------
479 -- Interface generators
480 --------------------------------------------------------------
482 -- HACK: we return ModGuts even though we know it's not gonna be used.
483 -- We do this because the type signature needs to be identical
484 -- in structure to the type of 'hscNormalIface'.
485 hscSimpleIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, ModGuts)
486 hscSimpleIface ds_result
487 = do hsc_env <- gets compHscEnv
488 mod_summary <- gets compModSummary
489 maybe_old_iface <- gets compOldIface
491 details <- mkBootModDetails hsc_env ds_result
492 (new_iface, no_change)
493 <- {-# SCC "MkFinalIface" #-}
494 mkIface hsc_env maybe_old_iface ds_result details
495 -- And the answer is ...
496 dumpIfaceStats hsc_env
497 return (new_iface, no_change, details, ds_result)
499 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
500 hscNormalIface simpl_result
501 = do hsc_env <- gets compHscEnv
502 mod_summary <- gets compModSummary
503 maybe_old_iface <- gets compOldIface
508 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
509 tidyProgram hsc_env simpl_result
512 -- BUILD THE NEW ModIface and ModDetails
513 -- and emit external core if necessary
514 -- This has to happen *after* code gen so that the back-end
515 -- info has been set. Not yet clear if it matters waiting
516 -- until after code output
517 (new_iface, no_change)
518 <- {-# SCC "MkFinalIface" #-}
519 mkIface hsc_env maybe_old_iface simpl_result details
520 -- Emit external core
521 emitExternalCore (hsc_dflags hsc_env) (availsToNameSet (mg_exports simpl_result)) cg_guts -- Move this? --Lemmih 03/07/2006
522 dumpIfaceStats hsc_env
525 -- Return the prepared code.
526 return (new_iface, no_change, details, cg_guts)
528 --------------------------------------------------------------
529 -- BackEnd combinators
530 --------------------------------------------------------------
532 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
533 hscWriteIface (iface, no_change, details, a)
534 = do mod_summary <- gets compModSummary
535 hsc_env <- gets compHscEnv
536 let dflags = hsc_dflags hsc_env
539 $ writeIfaceFile dflags (ms_location mod_summary) iface
540 return (iface, details, a)
542 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
543 hscIgnoreIface (iface, no_change, details, a)
544 = return (iface, details, a)
546 -- Don't output any code.
547 hscNothing :: (ModIface, ModDetails, a) -> Comp (HscStatus, ModIface, ModDetails)
548 hscNothing (iface, details, a)
549 = return (HscRecomp False, iface, details)
551 -- Generate code and return both the new ModIface and the ModDetails.
552 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (HscStatus, ModIface, ModDetails)
553 hscBatch (iface, details, cgguts)
554 = do hasStub <- hscCompile cgguts
555 return (HscRecomp hasStub, iface, details)
557 -- Here we don't need the ModIface and ModDetails anymore.
558 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp HscStatus
559 hscOneShot (_, _, cgguts)
560 = do hasStub <- hscCompile cgguts
561 return (HscRecomp hasStub)
563 -- Compile to hard-code.
564 hscCompile :: CgGuts -> Comp Bool
566 = do hsc_env <- gets compHscEnv
567 mod_summary <- gets compModSummary
569 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
570 -- From now on, we just use the bits we need.
571 cg_module = this_mod,
572 cg_binds = core_binds,
574 cg_dir_imps = dir_imps,
575 cg_foreign = foreign_stubs,
576 cg_dep_pkgs = dependencies,
577 cg_hpc_info = hpc_info } = cgguts
578 dflags = hsc_dflags hsc_env
579 location = ms_location mod_summary
580 data_tycons = filter isDataTyCon tycons
581 -- cg_tycons includes newtypes, for the benefit of External Core,
582 -- but we don't generate any code for newtypes
585 -- PREPARE FOR CODE GENERATION
586 -- Do saturation and convert to A-normal form
587 prepd_binds <- {-# SCC "CorePrep" #-}
588 corePrepPgm dflags core_binds data_tycons ;
589 ----------------- Convert to STG ------------------
590 (stg_binds, cost_centre_info)
591 <- {-# SCC "CoreToStg" #-}
592 myCoreToStg dflags this_mod prepd_binds
593 ------------------ Code generation ------------------
594 abstractC <- {-# SCC "CodeGen" #-}
595 codeGen dflags this_mod data_tycons
596 dir_imps cost_centre_info
598 ------------------ Convert to CPS --------------------
599 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
600 continuationC <- cmmToRawCmm abstractC
601 ------------------ Code output -----------------------
602 (stub_h_exists,stub_c_exists)
603 <- codeOutput dflags this_mod location foreign_stubs
604 dependencies continuationC
607 hscConst :: b -> a -> Comp b
608 hscConst b a = return b
610 hscInteractive :: (ModIface, ModDetails, CgGuts)
611 -> Comp (InteractiveStatus, ModIface, ModDetails)
612 hscInteractive (iface, details, cgguts)
614 = do hsc_env <- gets compHscEnv
615 mod_summary <- gets compModSummary
617 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
618 -- From now on, we just use the bits we need.
619 cg_module = this_mod,
620 cg_binds = core_binds,
622 cg_foreign = foreign_stubs,
623 cg_modBreaks = mod_breaks } = cgguts
624 dflags = hsc_dflags hsc_env
625 location = ms_location mod_summary
626 data_tycons = filter isDataTyCon tycons
627 -- cg_tycons includes newtypes, for the benefit of External Core,
628 -- but we don't generate any code for newtypes
631 -- PREPARE FOR CODE GENERATION
632 -- Do saturation and convert to A-normal form
633 prepd_binds <- {-# SCC "CorePrep" #-}
634 corePrepPgm dflags core_binds data_tycons ;
635 ----------------- Generate byte code ------------------
636 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
637 ------------------ Create f-x-dynamic C-side stuff ---
638 (istub_h_exists, istub_c_exists)
639 <- outputForeignStubs dflags this_mod location foreign_stubs
640 return (InteractiveRecomp istub_c_exists comp_bc mod_breaks, iface, details)
642 = panic "GHC not compiled with interpreter"
645 ------------------------------
647 hscFileCheck :: HscEnv -> ModSummary -> Bool -> IO (Maybe HscChecked)
648 hscFileCheck hsc_env mod_summary compileToCore = do {
652 ; let dflags = hsc_dflags hsc_env
653 hspp_file = ms_hspp_file mod_summary
654 hspp_buf = ms_hspp_buf mod_summary
656 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
658 ; case maybe_parsed of {
659 Left err -> do { printBagOfErrors dflags (unitBag err)
661 Right rdr_module -> do {
664 -- RENAME and TYPECHECK
666 (tc_msgs, maybe_tc_result)
667 <- {-# SCC "Typecheck-Rename" #-}
668 tcRnModule hsc_env (ms_hsc_src mod_summary)
669 True{-save renamed syntax-}
672 ; printErrorsAndWarnings dflags tc_msgs
673 ; case maybe_tc_result of {
674 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing Nothing));
676 let type_env = tcg_type_env tc_result
679 md_exports = tcg_exports tc_result,
680 md_insts = tcg_insts tc_result,
681 md_fam_insts = tcg_fam_insts tc_result,
682 md_rules = [panic "no rules"],
683 -- Rules are CoreRules, not the
684 -- RuleDecls we get out of the typechecker
685 md_vect_info = noVectInfo
686 -- VectInfo is added by the Core
687 -- vectorisation pass
689 rnInfo = do decl <- tcg_rn_decls tc_result
690 imports <- tcg_rn_imports tc_result
691 let exports = tcg_rn_exports tc_result
692 let doc = tcg_doc tc_result
693 hmi = tcg_hmi tc_result
694 return (decl,imports,exports,doc,hmi)
696 if compileToCore then
697 deSugar hsc_env (ms_location mod_summary) tc_result
700 return (Just (HscChecked rdr_module
702 (Just (tcg_binds tc_result,
703 tcg_rdr_env tc_result,
705 (fmap mg_binds maybeModGuts)))
709 hscCmmFile :: DynFlags -> FilePath -> IO Bool
710 hscCmmFile dflags filename = do
711 maybe_cmm <- parseCmmFile dflags filename
713 Nothing -> return False
715 --continuationC <- cmmCPS dflags [cmm] >>= cmmToRawCmm
716 continuationC <- cmmToRawCmm [cmm]
717 codeOutput dflags no_mod no_loc NoStubs [] continuationC
720 no_mod = panic "hscCmmFile: no_mod"
721 no_loc = ModLocation{ ml_hs_file = Just filename,
722 ml_hi_file = panic "hscCmmFile: no hi file",
723 ml_obj_file = panic "hscCmmFile: no obj file" }
726 myParseModule :: DynFlags -> FilePath -> Maybe StringBuffer
727 -> IO (Either ErrMsg (Located (HsModule RdrName)))
728 myParseModule dflags src_filename maybe_src_buf
729 = -------------------------- Parser ----------------
730 showPass dflags "Parser" >>
731 {-# SCC "Parser" #-} do
733 -- sometimes we already have the buffer in memory, perhaps
734 -- because we needed to parse the imports out of it, or get the
736 buf <- case maybe_src_buf of
738 Nothing -> hGetStringBuffer src_filename
740 let loc = mkSrcLoc (mkFastString src_filename) 1 0
742 case unP parseModule (mkPState buf loc dflags) of {
744 PFailed span err -> return (Left (mkPlainErrMsg span err));
746 POk pst rdr_module -> do {
748 let {ms = getMessages pst};
749 printErrorsAndWarnings dflags ms;
750 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
752 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
754 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
755 (ppSourceStats False rdr_module) ;
757 return (Right rdr_module)
758 -- ToDo: free the string buffer later.
762 myCoreToStg dflags this_mod prepd_binds
764 stg_binds <- {-# SCC "Core2Stg" #-}
765 coreToStg (thisPackage dflags) prepd_binds
767 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
768 stg2stg dflags this_mod stg_binds
770 return (stg_binds2, cost_centre_info)
774 %************************************************************************
776 \subsection{Compiling a do-statement}
778 %************************************************************************
780 When the UnlinkedBCOExpr is linked you get an HValue of type
782 When you run it you get a list of HValues that should be
783 the same length as the list of names; add them to the ClosureEnv.
785 A naked expression returns a singleton Name [it].
787 What you type The IO [HValue] that hscStmt returns
788 ------------- ------------------------------------
789 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
792 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
795 expr (of IO type) ==> expr >>= \ v -> return [v]
796 [NB: result not printed] bindings: [it]
799 expr (of non-IO type,
800 result showable) ==> let v = expr in print v >> return [v]
803 expr (of non-IO type,
804 result not showable) ==> error
808 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
810 -> String -- The statement
811 -> IO (Maybe ([Id], HValue))
814 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
815 ; case maybe_stmt of {
816 Nothing -> return Nothing ; -- Parse error
817 Just Nothing -> return Nothing ; -- Empty line
818 Just (Just parsed_stmt) -> do { -- The real stuff
820 -- Rename and typecheck it
821 let icontext = hsc_IC hsc_env
822 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
824 ; case maybe_tc_result of {
825 Nothing -> return Nothing ;
826 Just (ids, tc_expr) -> do {
829 ; let rdr_env = ic_rn_gbl_env icontext
830 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
831 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
833 ; case mb_ds_expr of {
834 Nothing -> return Nothing ;
837 -- Then desugar, code gen, and link it
838 ; let src_span = srcLocSpan interactiveSrcLoc
839 ; hval <- compileExpr hsc_env src_span ds_expr
841 ; return (Just (ids, hval))
844 hscTcExpr -- Typecheck an expression (but don't run it)
846 -> String -- The expression
849 hscTcExpr hsc_env expr
850 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
851 ; let icontext = hsc_IC hsc_env
852 ; case maybe_stmt of {
853 Nothing -> return Nothing ; -- Parse error
854 Just (Just (L _ (ExprStmt expr _ _)))
855 -> tcRnExpr hsc_env icontext expr ;
856 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
860 hscKcType -- Find the kind of a type
862 -> String -- The type
865 hscKcType hsc_env str
866 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
867 ; let icontext = hsc_IC hsc_env
868 ; case maybe_type of {
869 Just ty -> tcRnType hsc_env icontext ty ;
870 Nothing -> return Nothing } }
876 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
877 hscParseStmt = hscParseThing parseStmt
879 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
880 hscParseType = hscParseThing parseType
883 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
884 hscParseIdentifier = hscParseThing parseIdentifier
886 hscParseThing :: Outputable thing
888 -> DynFlags -> String
890 -- Nothing => Parse error (message already printed)
892 hscParseThing parser dflags str
893 = showPass dflags "Parser" >>
894 {-# SCC "Parser" #-} do
896 buf <- stringToStringBuffer str
898 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
900 case unP parser (mkPState buf loc dflags) of {
902 PFailed span err -> do { printError span err;
905 POk pst thing -> do {
907 let {ms = getMessages pst};
908 printErrorsAndWarnings dflags ms;
909 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
911 --ToDo: can't free the string buffer until we've finished this
912 -- compilation sweep and all the identifiers have gone away.
913 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
918 %************************************************************************
920 Desugar, simplify, convert to bytecode, and link an expression
922 %************************************************************************
926 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
928 compileExpr hsc_env srcspan ds_expr
929 = do { let { dflags = hsc_dflags hsc_env ;
930 lint_on = dopt Opt_DoCoreLinting dflags }
933 ; flat_expr <- flattenExpr hsc_env ds_expr
936 ; simpl_expr <- simplifyExpr dflags flat_expr
938 -- Tidy it (temporary, until coreSat does cloning)
939 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
941 -- Prepare for codegen
942 ; prepd_expr <- corePrepExpr dflags tidy_expr
945 -- ToDo: improve SrcLoc
947 let ictxt = hsc_IC hsc_env
948 tyvars = varSetElems (ic_tyvars ictxt)
950 case lintUnfolding noSrcLoc tyvars prepd_expr of
951 Just err -> pprPanic "compileExpr" err
957 ; bcos <- coreExprToBCOs dflags prepd_expr
960 ; hval <- linkExpr hsc_env srcspan bcos
968 %************************************************************************
970 Statistics on reading interfaces
972 %************************************************************************
975 dumpIfaceStats :: HscEnv -> IO ()
976 dumpIfaceStats hsc_env
977 = do { eps <- readIORef (hsc_EPS hsc_env)
978 ; dumpIfSet (dump_if_trace || dump_rn_stats)
979 "Interface statistics"
982 dflags = hsc_dflags hsc_env
983 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
984 dump_if_trace = dopt Opt_D_dump_if_trace dflags
987 %************************************************************************
989 Progress Messages: Module i of n
991 %************************************************************************
994 showModuleIndex Nothing = ""
995 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
999 padded = replicate (length n_str - length i_str) ' ' ++ i_str