2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 ( newHscEnv, hscCmmFile
13 , hscStmt, hscTcExpr, hscKcType
16 , hscCompileOneShot -- :: Compiler HscStatus
17 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
18 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
19 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
21 , InteractiveStatus (..)
25 #include "HsVersions.h"
28 import HsSyn ( Stmt(..), LHsExpr, LStmt, LHsType )
29 import Module ( Module )
30 import CodeOutput ( outputForeignStubs )
31 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
32 import Linker ( HValue, linkExpr )
33 import CoreSyn ( CoreExpr )
34 import CoreTidy ( tidyExpr )
35 import CorePrep ( corePrepExpr )
36 import Flattening ( flattenExpr )
37 import Desugar ( deSugarExpr )
38 import SimplCore ( simplifyExpr )
39 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
41 import PrelNames ( iNTERACTIVE )
42 import {- Kind parts of -} Type ( Kind )
43 import CoreLint ( lintUnfolding )
44 import DsMeta ( templateHaskellNames )
45 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,
54 import SrcLoc ( Located(..) )
55 import StringBuffer ( hGetStringBuffer, stringToStringBuffer )
58 import SrcLoc ( mkSrcLoc )
59 import TcRnDriver ( tcRnModule, tcRnExtCore )
60 import TcIface ( typecheckIface )
61 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
62 import IfaceEnv ( initNameCache )
63 import LoadIface ( ifaceStats, initExternalPackageState )
64 import PrelInfo ( wiredInThings, basicKnownKeyNames )
65 import MkIface ( checkOldIface, mkIface, writeIfaceFile )
66 import Desugar ( deSugar )
67 import Flattening ( flatten )
68 import SimplCore ( core2core )
69 import TidyPgm ( tidyProgram, mkBootModDetails )
70 import CorePrep ( corePrepPgm )
71 import CoreToStg ( coreToStg )
72 import TyCon ( isDataTyCon )
73 import Name ( Name, NamedThing(..) )
74 import SimplStg ( stg2stg )
75 import CodeGen ( codeGen )
76 import CmmParse ( parseCmmFile )
77 import CodeOutput ( codeOutput )
78 import NameEnv ( emptyNameEnv )
79 import Breakpoints ( noDbgSites )
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))
189 -- Status of a compilation to hard-code or nothing.
192 | HscRecomp Bool -- Has stub files.
193 -- This is a hack. We can't compile C files here
194 -- since it's done in DriverPipeline. For now we
195 -- just return True if we want the caller to compile
198 -- Status of a compilation to byte-code.
199 data InteractiveStatus
200 = InteractiveNoRecomp
201 | InteractiveRecomp Bool -- Same as HscStatus
205 -- I want Control.Monad.State! --Lemmih 03/07/2006
206 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
208 instance Monad Comp where
209 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
210 return a = Comp $ \s -> return (a,s)
213 evalComp :: Comp a -> CompState -> IO a
214 evalComp comp st = do (val,_st') <- runComp comp st
219 { compHscEnv :: HscEnv
220 , compModSummary :: ModSummary
221 , compOldIface :: Maybe ModIface
224 get :: Comp CompState
225 get = Comp $ \s -> return (s,s)
227 modify :: (CompState -> CompState) -> Comp ()
228 modify f = Comp $ \s -> return ((), f s)
230 gets :: (CompState -> a) -> Comp a
231 gets getter = do st <- get
234 liftIO :: IO a -> Comp a
235 liftIO ioA = Comp $ \s -> do a <- ioA
238 type NoRecomp result = ModIface -> Comp result
239 type FrontEnd core = Comp (Maybe core)
241 -- FIXME: The old interface and module index are only using in 'batch' and
242 -- 'interactive' mode. They should be removed from 'oneshot' mode.
243 type Compiler result = HscEnv
245 -> Bool -- True <=> source unchanged
246 -> Maybe ModIface -- Old interface, if available
247 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
251 -- This functions checks if recompilation is necessary and
252 -- then combines the FrontEnd and BackEnd to a working compiler.
253 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
254 -> (Maybe (Int,Int) -> Bool -> Comp ())
256 -> (core -> Comp result) -- Backend.
258 hscMkCompiler norecomp messenger frontend backend
259 hsc_env mod_summary source_unchanged
260 mbOldIface mbModIndex
261 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
262 do (recomp_reqd, mbCheckedIface)
263 <- {-# SCC "checkOldIface" #-}
264 liftIO $ checkOldIface hsc_env mod_summary
265 source_unchanged mbOldIface
266 -- save the interface that comes back from checkOldIface.
267 -- In one-shot mode we don't have the old iface until this
268 -- point, when checkOldIface reads it from the disk.
269 modify (\s -> s{ compOldIface = mbCheckedIface })
270 case mbCheckedIface of
271 Just iface | not recomp_reqd
272 -> do messenger mbModIndex False
273 result <- norecomp iface
276 -> do messenger mbModIndex True
282 -> do result <- backend core
285 --------------------------------------------------------------
287 --------------------------------------------------------------
290 -- Compile Haskell, boot and extCore in OneShot mode.
291 hscCompileOneShot :: Compiler HscStatus
292 hscCompileOneShot = hscCompileHardCode norecompOneShot oneShotMsg hscOneShot (hscConst (HscRecomp False))
294 -- Compile Haskell, boot and extCore in batch mode.
295 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
296 hscCompileBatch = hscCompileHardCode norecompBatch batchMsg hscBatch hscNothing
298 -- Compile to hardcode (C,asm,...). This general structure is shared by OneShot and Batch.
299 hscCompileHardCode :: NoRecomp result -- No recomp necessary
300 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
301 -> ((ModIface, ModDetails, CgGuts) -> Comp result) -- Compile normal file
302 -> ((ModIface, ModDetails, ModGuts) -> Comp result) -- Compile boot file
304 hscCompileHardCode norecomp msg compNormal compBoot hsc_env mod_summary =
305 compiler hsc_env mod_summary
306 where mkComp = hscMkCompiler norecomp msg
307 -- How to compile nonBoot files.
308 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
309 hscWriteIface >>= compNormal
310 -- How to compile boot files.
311 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= compBoot
313 = case ms_hsc_src mod_summary of
315 -> mkComp hscCoreFrontEnd nonBootComp
317 -> mkComp hscFileFrontEnd nonBootComp
319 -> mkComp hscFileFrontEnd bootComp
321 -- Type-check Haskell, boot and extCore.
322 -- Does it make sense to compile extCore to nothing?
323 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
324 hscCompileNothing hsc_env mod_summary
325 = compiler hsc_env mod_summary
326 where mkComp = hscMkCompiler norecompBatch batchMsg
327 pipeline inp = hscSimpleIface inp >>= hscIgnoreIface >>= hscNothing
329 = case ms_hsc_src mod_summary of
331 -> mkComp hscCoreFrontEnd pipeline
333 -> mkComp hscFileFrontEnd pipeline
335 -> mkComp hscFileFrontEnd pipeline
337 -- Compile Haskell, extCore to bytecode.
338 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
339 hscCompileInteractive hsc_env mod_summary =
340 hscMkCompiler norecompInteractive batchMsg
343 where backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
344 frontend = case ms_hsc_src mod_summary of
345 ExtCoreFile -> hscCoreFrontEnd
346 HsSrcFile -> hscFileFrontEnd
347 HsBootFile -> panic bootErrorMsg
348 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
349 "Use 'hscCompileBatch' instead."
351 --------------------------------------------------------------
353 --------------------------------------------------------------
355 norecompOneShot :: NoRecomp HscStatus
356 norecompOneShot old_iface
357 = do hsc_env <- gets compHscEnv
359 dumpIfaceStats hsc_env
362 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
363 norecompBatch = norecompWorker HscNoRecomp False
365 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
366 norecompInteractive = norecompWorker InteractiveNoRecomp True
368 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
369 norecompWorker a isInterp old_iface
370 = do hsc_env <- gets compHscEnv
371 mod_summary <- gets compModSummary
373 new_details <- {-# SCC "tcRnIface" #-}
374 initIfaceCheck hsc_env $
375 typecheckIface old_iface
376 dumpIfaceStats hsc_env
377 return (a, old_iface, new_details)
379 --------------------------------------------------------------
380 -- Progress displayers.
381 --------------------------------------------------------------
383 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
384 oneShotMsg _mb_mod_index recomp
385 = do hsc_env <- gets compHscEnv
389 else compilationProgressMsg (hsc_dflags hsc_env) $
390 "compilation IS NOT required"
392 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
393 batchMsg mb_mod_index recomp
394 = do hsc_env <- gets compHscEnv
395 mod_summary <- gets compModSummary
396 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
397 (showModuleIndex mb_mod_index ++
398 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
401 then showMsg "Compiling "
402 else if verbosity (hsc_dflags hsc_env) >= 1
403 then showMsg "Skipping "
406 --------------------------------------------------------------
408 --------------------------------------------------------------
410 hscCoreFrontEnd :: FrontEnd ModGuts
412 do hsc_env <- gets compHscEnv
413 mod_summary <- gets compModSummary
418 inp <- readFile (ms_hspp_file mod_summary)
419 case parseCore inp 1 of
421 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
425 -- RENAME and TYPECHECK
427 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
428 tcRnExtCore hsc_env rdr_module
429 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
430 case maybe_tc_result of
431 Nothing -> return Nothing
432 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
435 hscFileFrontEnd :: FrontEnd ModGuts
437 do hsc_env <- gets compHscEnv
438 mod_summary <- gets compModSummary
443 let dflags = hsc_dflags hsc_env
444 hspp_file = ms_hspp_file mod_summary
445 hspp_buf = ms_hspp_buf mod_summary
446 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
449 -> do printBagOfErrors dflags (unitBag err)
453 -- RENAME and TYPECHECK
455 -> do (tc_msgs, maybe_tc_result)
456 <- {-# SCC "Typecheck-Rename" #-}
457 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
458 printErrorsAndWarnings dflags tc_msgs
459 case maybe_tc_result of
466 -> {-# SCC "DeSugar" #-} deSugar hsc_env (ms_location mod_summary) tc_result
468 --------------------------------------------------------------
470 --------------------------------------------------------------
472 hscSimplify :: ModGuts -> Comp ModGuts
473 hscSimplify ds_result
474 = do hsc_env <- gets compHscEnv
476 flat_result <- {-# SCC "Flattening" #-}
477 flatten hsc_env ds_result
481 simpl_result <- {-# SCC "Core2Core" #-}
482 core2core hsc_env flat_result
485 --------------------------------------------------------------
486 -- Interface generators
487 --------------------------------------------------------------
489 -- HACK: we return ModGuts even though we know it's not gonna be used.
490 -- We do this because the type signature needs to be identical
491 -- in structure to the type of 'hscNormalIface'.
492 hscSimpleIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, ModGuts)
493 hscSimpleIface ds_result
494 = do hsc_env <- gets compHscEnv
495 mod_summary <- gets compModSummary
496 maybe_old_iface <- gets compOldIface
498 details <- mkBootModDetails hsc_env ds_result
499 (new_iface, no_change)
500 <- {-# SCC "MkFinalIface" #-}
501 mkIface hsc_env maybe_old_iface ds_result details
502 -- And the answer is ...
503 dumpIfaceStats hsc_env
504 return (new_iface, no_change, details, ds_result)
506 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
507 hscNormalIface simpl_result
508 = do hsc_env <- gets compHscEnv
509 mod_summary <- gets compModSummary
510 maybe_old_iface <- gets compOldIface
515 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
516 tidyProgram hsc_env simpl_result
519 -- BUILD THE NEW ModIface and ModDetails
520 -- and emit external core if necessary
521 -- This has to happen *after* code gen so that the back-end
522 -- info has been set. Not yet clear if it matters waiting
523 -- until after code output
524 (new_iface, no_change)
525 <- {-# SCC "MkFinalIface" #-}
526 mkIface hsc_env maybe_old_iface simpl_result details
527 -- Emit external core
528 emitExternalCore (hsc_dflags hsc_env) (availsToNameSet (mg_exports simpl_result)) cg_guts -- Move this? --Lemmih 03/07/2006
529 dumpIfaceStats hsc_env
532 -- Return the prepared code.
533 return (new_iface, no_change, details, cg_guts)
535 --------------------------------------------------------------
536 -- BackEnd combinators
537 --------------------------------------------------------------
539 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
540 hscWriteIface (iface, no_change, details, a)
541 = do mod_summary <- gets compModSummary
542 hsc_env <- gets compHscEnv
543 let dflags = hsc_dflags hsc_env
546 $ writeIfaceFile dflags (ms_location mod_summary) iface
547 return (iface, details, a)
549 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
550 hscIgnoreIface (iface, no_change, details, a)
551 = return (iface, details, a)
553 -- Don't output any code.
554 hscNothing :: (ModIface, ModDetails, a) -> Comp (HscStatus, ModIface, ModDetails)
555 hscNothing (iface, details, a)
556 = return (HscRecomp False, iface, details)
558 -- Generate code and return both the new ModIface and the ModDetails.
559 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (HscStatus, ModIface, ModDetails)
560 hscBatch (iface, details, cgguts)
561 = do hasStub <- hscCompile cgguts
562 return (HscRecomp hasStub, iface, details)
564 -- Here we don't need the ModIface and ModDetails anymore.
565 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp HscStatus
566 hscOneShot (_, _, cgguts)
567 = do hasStub <- hscCompile cgguts
568 return (HscRecomp hasStub)
570 -- Compile to hard-code.
571 hscCompile :: CgGuts -> Comp Bool
573 = do hsc_env <- gets compHscEnv
574 mod_summary <- gets compModSummary
576 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
577 -- From now on, we just use the bits we need.
578 cg_module = this_mod,
579 cg_binds = core_binds,
581 cg_dir_imps = dir_imps,
582 cg_foreign = foreign_stubs,
583 cg_dep_pkgs = dependencies,
584 cg_hpc_info = hpc_info } = cgguts
585 dflags = hsc_dflags hsc_env
586 location = ms_location mod_summary
587 data_tycons = filter isDataTyCon tycons
588 -- cg_tycons includes newtypes, for the benefit of External Core,
589 -- but we don't generate any code for newtypes
592 -- PREPARE FOR CODE GENERATION
593 -- Do saturation and convert to A-normal form
594 prepd_binds <- {-# SCC "CorePrep" #-}
595 corePrepPgm dflags core_binds data_tycons ;
596 ----------------- Convert to STG ------------------
597 (stg_binds, cost_centre_info)
598 <- {-# SCC "CoreToStg" #-}
599 myCoreToStg dflags this_mod prepd_binds
600 ------------------ Code generation ------------------
601 abstractC <- {-# SCC "CodeGen" #-}
602 codeGen dflags this_mod data_tycons
603 foreign_stubs dir_imps cost_centre_info
605 ------------------ Code output -----------------------
606 (stub_h_exists,stub_c_exists)
607 <- codeOutput dflags this_mod location foreign_stubs
608 dependencies abstractC
611 hscConst :: b -> a -> Comp b
612 hscConst b a = return b
614 hscInteractive :: (ModIface, ModDetails, CgGuts)
615 -> Comp (InteractiveStatus, ModIface, ModDetails)
616 hscInteractive (iface, details, cgguts)
618 = do hsc_env <- gets compHscEnv
619 mod_summary <- gets compModSummary
621 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
622 -- From now on, we just use the bits we need.
623 cg_module = this_mod,
624 cg_binds = core_binds,
626 cg_foreign = foreign_stubs } = cgguts
627 dflags = hsc_dflags hsc_env
628 location = ms_location mod_summary
629 data_tycons = filter isDataTyCon tycons
630 -- cg_tycons includes newtypes, for the benefit of External Core,
631 -- but we don't generate any code for newtypes
634 -- PREPARE FOR CODE GENERATION
635 -- Do saturation and convert to A-normal form
636 prepd_binds <- {-# SCC "CorePrep" #-}
637 corePrepPgm dflags core_binds data_tycons ;
638 ----------------- Generate byte code ------------------
639 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
640 ------------------ Create f-x-dynamic C-side stuff ---
641 (istub_h_exists, istub_c_exists)
642 <- outputForeignStubs dflags this_mod location foreign_stubs
643 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
645 = panic "GHC not compiled with interpreter"
648 ------------------------------
650 hscFileCheck :: HscEnv -> ModSummary -> IO (Maybe HscChecked)
651 hscFileCheck hsc_env mod_summary = do {
655 ; let dflags = hsc_dflags hsc_env
656 hspp_file = ms_hspp_file mod_summary
657 hspp_buf = ms_hspp_buf mod_summary
659 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
661 ; case maybe_parsed of {
662 Left err -> do { printBagOfErrors dflags (unitBag err)
664 Right rdr_module -> do {
667 -- RENAME and TYPECHECK
669 (tc_msgs, maybe_tc_result)
670 <- _scc_ "Typecheck-Rename"
671 tcRnModule hsc_env (ms_hsc_src mod_summary)
672 True{-save renamed syntax-}
675 ; printErrorsAndWarnings dflags tc_msgs
676 ; case maybe_tc_result of {
677 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing));
679 let type_env = tcg_type_env tc_result
682 md_exports = tcg_exports tc_result,
683 md_insts = tcg_insts tc_result,
684 md_fam_insts = tcg_fam_insts tc_result,
685 md_dbg_sites = noDbgSites,
686 md_rules = [panic "no rules"] }
687 -- Rules are CoreRules, not the
688 -- RuleDecls we get out of the typechecker
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)
695 return (Just (HscChecked rdr_module
697 (Just (tcg_binds tc_result,
698 tcg_rdr_env tc_result,
703 hscCmmFile :: DynFlags -> FilePath -> IO Bool
704 hscCmmFile dflags filename = do
705 maybe_cmm <- parseCmmFile dflags filename
707 Nothing -> return False
709 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
712 no_mod = panic "hscCmmFile: no_mod"
713 no_loc = ModLocation{ ml_hs_file = Just filename,
714 ml_hi_file = panic "hscCmmFile: no hi file",
715 ml_obj_file = panic "hscCmmFile: no obj file" }
718 myParseModule dflags src_filename maybe_src_buf
719 = -------------------------- Parser ----------------
720 showPass dflags "Parser" >>
721 {-# SCC "Parser" #-} do
723 -- sometimes we already have the buffer in memory, perhaps
724 -- because we needed to parse the imports out of it, or get the
726 buf <- case maybe_src_buf of
728 Nothing -> hGetStringBuffer src_filename
730 let loc = mkSrcLoc (mkFastString src_filename) 1 0
732 case unP parseModule (mkPState buf loc dflags) of {
734 PFailed span err -> return (Left (mkPlainErrMsg span err));
736 POk pst rdr_module -> do {
738 let {ms = getMessages pst};
739 printErrorsAndWarnings dflags ms;
740 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
742 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
744 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
745 (ppSourceStats False rdr_module) ;
747 return (Right rdr_module)
748 -- ToDo: free the string buffer later.
752 myCoreToStg dflags this_mod prepd_binds
754 stg_binds <- {-# SCC "Core2Stg" #-}
755 coreToStg (thisPackage dflags) prepd_binds
757 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
758 stg2stg dflags this_mod stg_binds
760 return (stg_binds2, cost_centre_info)
764 %************************************************************************
766 \subsection{Compiling a do-statement}
768 %************************************************************************
770 When the UnlinkedBCOExpr is linked you get an HValue of type
772 When you run it you get a list of HValues that should be
773 the same length as the list of names; add them to the ClosureEnv.
775 A naked expression returns a singleton Name [it].
777 What you type The IO [HValue] that hscStmt returns
778 ------------- ------------------------------------
779 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
782 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
785 expr (of IO type) ==> expr >>= \ v -> return [v]
786 [NB: result not printed] bindings: [it]
789 expr (of non-IO type,
790 result showable) ==> let v = expr in print v >> return [v]
793 expr (of non-IO type,
794 result not showable) ==> error
798 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
800 -> String -- The statement
801 -> IO (Maybe (HscEnv, [Name], HValue))
804 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
805 ; case maybe_stmt of {
806 Nothing -> return Nothing ; -- Parse error
807 Just Nothing -> return Nothing ; -- Empty line
808 Just (Just parsed_stmt) -> do { -- The real stuff
810 -- Rename and typecheck it
811 let icontext = hsc_IC hsc_env
812 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
814 ; case maybe_tc_result of {
815 Nothing -> return Nothing ;
816 Just (new_ic, bound_names, tc_expr) -> do {
820 ; let rdr_env = ic_rn_gbl_env new_ic
821 type_env = ic_type_env new_ic
822 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
824 ; case mb_ds_expr of {
825 Nothing -> return Nothing ;
828 -- Then desugar, code gen, and link it
829 ; let src_span = srcLocSpan interactiveSrcLoc
830 ; hval <- compileExpr hsc_env src_span ds_expr
832 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
835 hscTcExpr -- Typecheck an expression (but don't run it)
837 -> String -- The expression
840 hscTcExpr hsc_env expr
841 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
842 ; let icontext = hsc_IC hsc_env
843 ; case maybe_stmt of {
844 Nothing -> return Nothing ; -- Parse error
845 Just (Just (L _ (ExprStmt expr _ _)))
846 -> tcRnExpr hsc_env icontext expr ;
847 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
851 hscKcType -- Find the kind of a type
853 -> String -- The type
856 hscKcType hsc_env str
857 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
858 ; let icontext = hsc_IC hsc_env
859 ; case maybe_type of {
860 Just ty -> tcRnType hsc_env icontext ty ;
861 Nothing -> return Nothing } }
867 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
868 hscParseStmt = hscParseThing parseStmt
870 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
871 hscParseType = hscParseThing parseType
874 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
875 hscParseIdentifier = hscParseThing parseIdentifier
877 hscParseThing :: Outputable thing
879 -> DynFlags -> String
881 -- Nothing => Parse error (message already printed)
883 hscParseThing parser dflags str
884 = showPass dflags "Parser" >>
885 {-# SCC "Parser" #-} do
887 buf <- stringToStringBuffer str
889 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
891 case unP parser (mkPState buf loc dflags) of {
893 PFailed span err -> do { printError span err;
896 POk pst thing -> do {
898 let {ms = getMessages pst};
899 printErrorsAndWarnings dflags ms;
900 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
902 --ToDo: can't free the string buffer until we've finished this
903 -- compilation sweep and all the identifiers have gone away.
904 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
909 %************************************************************************
911 Desugar, simplify, convert to bytecode, and link an expression
913 %************************************************************************
917 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
919 compileExpr hsc_env srcspan ds_expr
920 = do { let { dflags = hsc_dflags hsc_env ;
921 lint_on = dopt Opt_DoCoreLinting dflags }
924 ; flat_expr <- flattenExpr hsc_env ds_expr
927 ; simpl_expr <- simplifyExpr dflags flat_expr
929 -- Tidy it (temporary, until coreSat does cloning)
930 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
932 -- Prepare for codegen
933 ; prepd_expr <- corePrepExpr dflags tidy_expr
936 -- ToDo: improve SrcLoc
938 case lintUnfolding noSrcLoc [] prepd_expr of
939 Just err -> pprPanic "compileExpr" err
945 ; bcos <- coreExprToBCOs dflags prepd_expr
948 ; hval <- linkExpr hsc_env srcspan bcos
956 %************************************************************************
958 Statistics on reading interfaces
960 %************************************************************************
963 dumpIfaceStats :: HscEnv -> IO ()
964 dumpIfaceStats hsc_env
965 = do { eps <- readIORef (hsc_EPS hsc_env)
966 ; dumpIfSet (dump_if_trace || dump_rn_stats)
967 "Interface statistics"
970 dflags = hsc_dflags hsc_env
971 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
972 dump_if_trace = dopt Opt_D_dump_if_trace dflags
975 %************************************************************************
977 Progress Messages: Module i of n
979 %************************************************************************
982 showModuleIndex Nothing = ""
983 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
987 padded = replicate (length n_str - length i_str) ' ' ++ i_str