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 )
80 import CodeOutput ( codeOutput )
81 import NameEnv ( emptyNameEnv )
85 import UniqSupply ( mkSplitUniqSupply )
88 import HscStats ( ppSourceStats )
90 import MkExternalCore ( emitExternalCore )
92 import ParserCoreUtils
94 import UniqFM ( emptyUFM )
95 import Bag ( unitBag )
104 %************************************************************************
108 %************************************************************************
111 newHscEnv :: DynFlags -> IO HscEnv
113 = do { eps_var <- newIORef initExternalPackageState
114 ; us <- mkSplitUniqSupply 'r'
115 ; nc_var <- newIORef (initNameCache us knownKeyNames)
116 ; fc_var <- newIORef emptyUFM
117 ; mlc_var <- newIORef emptyModuleEnv
118 ; return (HscEnv { hsc_dflags = dflags,
121 hsc_IC = emptyInteractiveContext,
122 hsc_HPT = emptyHomePackageTable,
127 hsc_global_rdr_env = emptyGlobalRdrEnv,
128 hsc_global_type_env = emptyNameEnv } ) }
131 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
132 -- where templateHaskellNames are defined
133 knownKeyNames = map getName wiredInThings
134 ++ basicKnownKeyNames
136 ++ templateHaskellNames
141 %************************************************************************
143 The main compiler pipeline
145 %************************************************************************
147 --------------------------------
148 The compilation proper
149 --------------------------------
152 It's the task of the compilation proper to compile Haskell, hs-boot and
153 core files to either byte-code, hard-code (C, asm, Java, ect) or to
154 nothing at all (the module is still parsed and type-checked. This
155 feature is mostly used by IDE's and the likes).
156 Compilation can happen in either 'one-shot', 'batch', 'nothing',
157 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
158 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
160 The modes are kept separate because of their different types and meanings.
161 In 'one-shot' mode, we're only compiling a single file and can therefore
162 discard the new ModIface and ModDetails. This is also the reason it only
163 targets hard-code; compiling to byte-code or nothing doesn't make sense
164 when we discard the result.
165 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
166 and ModDetails. 'Batch' mode doesn't target byte-code since that require
167 us to return the newly compiled byte-code.
168 'Nothing' mode has exactly the same type as 'batch' mode but they're still
169 kept separate. This is because compiling to nothing is fairly special: We
170 don't output any interface files, we don't run the simplifier and we don't
172 'Interactive' mode is similar to 'batch' mode except that we return the
173 compiled byte-code together with the ModIface and ModDetails.
175 Trying to compile a hs-boot file to byte-code will result in a run-time
176 error. This is the only thing that isn't caught by the type-system.
183 (Located (HsModule RdrName))
185 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
186 Maybe (HsDoc Name), HaddockModInfo Name))
188 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
192 -- Status of a compilation to hard-code or nothing.
195 | HscRecomp Bool -- Has stub files.
196 -- This is a hack. We can't compile C files here
197 -- since it's done in DriverPipeline. For now we
198 -- just return True if we want the caller to compile
201 -- Status of a compilation to byte-code.
202 data InteractiveStatus
203 = InteractiveNoRecomp
204 | InteractiveRecomp Bool -- Same as HscStatus
208 -- I want Control.Monad.State! --Lemmih 03/07/2006
209 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
211 instance Monad Comp where
212 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
213 return a = Comp $ \s -> return (a,s)
216 evalComp :: Comp a -> CompState -> IO a
217 evalComp comp st = do (val,_st') <- runComp comp st
222 { compHscEnv :: HscEnv
223 , compModSummary :: ModSummary
224 , compOldIface :: Maybe ModIface
227 get :: Comp CompState
228 get = Comp $ \s -> return (s,s)
230 modify :: (CompState -> CompState) -> Comp ()
231 modify f = Comp $ \s -> return ((), f s)
233 gets :: (CompState -> a) -> Comp a
234 gets getter = do st <- get
237 liftIO :: IO a -> Comp a
238 liftIO ioA = Comp $ \s -> do a <- ioA
241 type NoRecomp result = ModIface -> Comp result
242 type FrontEnd core = Comp (Maybe core)
244 -- FIXME: The old interface and module index are only using in 'batch' and
245 -- 'interactive' mode. They should be removed from 'oneshot' mode.
246 type Compiler result = HscEnv
248 -> Bool -- True <=> source unchanged
249 -> Maybe ModIface -- Old interface, if available
250 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
254 -- This functions checks if recompilation is necessary and
255 -- then combines the FrontEnd and BackEnd to a working compiler.
256 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
257 -> (Maybe (Int,Int) -> Bool -> Comp ())
259 -> (core -> Comp result) -- Backend.
261 hscMkCompiler norecomp messenger frontend backend
262 hsc_env mod_summary source_unchanged
263 mbOldIface mbModIndex
264 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
265 do (recomp_reqd, mbCheckedIface)
266 <- {-# SCC "checkOldIface" #-}
267 liftIO $ checkOldIface hsc_env mod_summary
268 source_unchanged mbOldIface
269 -- save the interface that comes back from checkOldIface.
270 -- In one-shot mode we don't have the old iface until this
271 -- point, when checkOldIface reads it from the disk.
272 modify (\s -> s{ compOldIface = mbCheckedIface })
273 case mbCheckedIface of
274 Just iface | not recomp_reqd
275 -> do messenger mbModIndex False
276 result <- norecomp iface
279 -> do messenger mbModIndex True
285 -> do result <- backend core
288 --------------------------------------------------------------
290 --------------------------------------------------------------
293 -- Compile Haskell, boot and extCore in OneShot mode.
294 hscCompileOneShot :: Compiler HscStatus
295 hscCompileOneShot = hscCompileHardCode norecompOneShot oneShotMsg hscOneShot (hscConst (HscRecomp False))
297 -- Compile Haskell, boot and extCore in batch mode.
298 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
299 hscCompileBatch = hscCompileHardCode norecompBatch batchMsg hscBatch hscNothing
301 -- Compile to hardcode (C,asm,...). This general structure is shared by OneShot and Batch.
302 hscCompileHardCode :: NoRecomp result -- No recomp necessary
303 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
304 -> ((ModIface, ModDetails, CgGuts) -> Comp result) -- Compile normal file
305 -> ((ModIface, ModDetails, ModGuts) -> Comp result) -- Compile boot file
307 hscCompileHardCode norecomp msg compNormal compBoot hsc_env mod_summary =
308 compiler hsc_env mod_summary
309 where mkComp = hscMkCompiler norecomp msg
310 -- How to compile nonBoot files.
311 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
312 hscWriteIface >>= compNormal
313 -- How to compile boot files.
314 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= compBoot
316 = case ms_hsc_src mod_summary of
318 -> mkComp hscCoreFrontEnd nonBootComp
320 -> mkComp hscFileFrontEnd nonBootComp
322 -> mkComp hscFileFrontEnd bootComp
324 -- Type-check Haskell, boot and extCore.
325 -- Does it make sense to compile extCore to nothing?
326 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
327 hscCompileNothing hsc_env mod_summary
328 = compiler hsc_env mod_summary
329 where mkComp = hscMkCompiler norecompBatch batchMsg
330 pipeline inp = hscSimpleIface inp >>= hscIgnoreIface >>= hscNothing
332 = case ms_hsc_src mod_summary of
334 -> mkComp hscCoreFrontEnd pipeline
336 -> mkComp hscFileFrontEnd pipeline
338 -> mkComp hscFileFrontEnd pipeline
340 -- Compile Haskell, extCore to bytecode.
341 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
342 hscCompileInteractive hsc_env mod_summary =
343 hscMkCompiler norecompInteractive batchMsg
346 where backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
347 frontend = case ms_hsc_src mod_summary of
348 ExtCoreFile -> hscCoreFrontEnd
349 HsSrcFile -> hscFileFrontEnd
350 HsBootFile -> panic bootErrorMsg
351 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
352 "Use 'hscCompileBatch' instead."
354 --------------------------------------------------------------
356 --------------------------------------------------------------
358 norecompOneShot :: NoRecomp HscStatus
359 norecompOneShot old_iface
360 = do hsc_env <- gets compHscEnv
362 dumpIfaceStats hsc_env
365 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
366 norecompBatch = norecompWorker HscNoRecomp False
368 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
369 norecompInteractive = norecompWorker InteractiveNoRecomp True
371 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
372 norecompWorker a isInterp old_iface
373 = do hsc_env <- gets compHscEnv
374 mod_summary <- gets compModSummary
376 new_details <- {-# SCC "tcRnIface" #-}
377 initIfaceCheck hsc_env $
378 typecheckIface old_iface
379 dumpIfaceStats hsc_env
380 return (a, old_iface, new_details)
382 --------------------------------------------------------------
383 -- Progress displayers.
384 --------------------------------------------------------------
386 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
387 oneShotMsg _mb_mod_index recomp
388 = do hsc_env <- gets compHscEnv
392 else compilationProgressMsg (hsc_dflags hsc_env) $
393 "compilation IS NOT required"
395 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
396 batchMsg mb_mod_index recomp
397 = do hsc_env <- gets compHscEnv
398 mod_summary <- gets compModSummary
399 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
400 (showModuleIndex mb_mod_index ++
401 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
404 then showMsg "Compiling "
405 else if verbosity (hsc_dflags hsc_env) >= 2
406 then showMsg "Skipping "
409 --------------------------------------------------------------
411 --------------------------------------------------------------
413 hscCoreFrontEnd :: FrontEnd ModGuts
415 do hsc_env <- gets compHscEnv
416 mod_summary <- gets compModSummary
421 inp <- readFile (ms_hspp_file mod_summary)
422 case parseCore inp 1 of
424 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
428 -- RENAME and TYPECHECK
430 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
431 tcRnExtCore hsc_env rdr_module
432 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
433 case maybe_tc_result of
434 Nothing -> return Nothing
435 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
438 hscFileFrontEnd :: FrontEnd ModGuts
440 do hsc_env <- gets compHscEnv
441 mod_summary <- gets compModSummary
446 let dflags = hsc_dflags hsc_env
447 hspp_file = ms_hspp_file mod_summary
448 hspp_buf = ms_hspp_buf mod_summary
449 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
452 -> do printBagOfErrors dflags (unitBag err)
456 -- RENAME and TYPECHECK
458 -> do (tc_msgs, maybe_tc_result)
459 <- {-# SCC "Typecheck-Rename" #-}
460 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
461 printErrorsAndWarnings dflags tc_msgs
462 case maybe_tc_result of
469 -> {-# SCC "DeSugar" #-} deSugar hsc_env (ms_location mod_summary) tc_result
471 --------------------------------------------------------------
473 --------------------------------------------------------------
475 hscSimplify :: ModGuts -> Comp ModGuts
476 hscSimplify ds_result
477 = do hsc_env <- gets compHscEnv
482 simpl_result <- {-# SCC "Core2Core" #-}
483 core2core hsc_env ds_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 ------------------ Convert to CPS --------------------
607 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
608 continuationC <- cmmToRawCmm 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
693 md_vect_info = noVectInfo
694 -- VectInfo is added by the Core
695 -- vectorisation pass
697 rnInfo = do decl <- tcg_rn_decls tc_result
698 imports <- tcg_rn_imports tc_result
699 let exports = tcg_rn_exports tc_result
700 let doc = tcg_doc tc_result
701 hmi = tcg_hmi tc_result
702 return (decl,imports,exports,doc,hmi)
704 if compileToCore then
705 deSugar hsc_env (ms_location mod_summary) tc_result
708 return (Just (HscChecked rdr_module
710 (Just (tcg_binds tc_result,
711 tcg_rdr_env tc_result,
713 (fmap mg_binds maybeModGuts)))
717 hscCmmFile :: DynFlags -> FilePath -> IO Bool
718 hscCmmFile dflags filename = do
719 maybe_cmm <- parseCmmFile dflags filename
721 Nothing -> return False
723 --continuationC <- cmmCPS dflags [cmm] >>= cmmToRawCmm
724 continuationC <- cmmToRawCmm [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