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 hsc_env mod_summary =
293 compiler hsc_env mod_summary
294 where mkComp = hscMkCompiler norecompOneShot oneShotMsg
295 -- How to compile nonBoot files.
296 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
297 hscWriteIface >>= hscOneShot
298 -- How to compile boot files.
299 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= hscConst (HscRecomp False)
301 = case ms_hsc_src mod_summary of
303 -> mkComp hscCoreFrontEnd nonBootComp
305 -> mkComp hscFileFrontEnd nonBootComp
307 -> mkComp hscFileFrontEnd bootComp
309 -- Compile Haskell, boot and extCore in batch mode.
310 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
311 hscCompileBatch hsc_env mod_summary
312 = compiler hsc_env mod_summary
313 where mkComp = hscMkCompiler norecompBatch batchMsg
314 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
315 hscWriteIface >>= hscBatch
316 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
318 = case ms_hsc_src mod_summary of
320 -> mkComp hscCoreFrontEnd nonBootComp
322 -> mkComp hscFileFrontEnd nonBootComp
324 -> mkComp hscFileFrontEnd bootComp
326 -- Type-check Haskell, boot and extCore.
327 -- Does it make sense to compile extCore to nothing?
328 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
329 hscCompileNothing hsc_env mod_summary
330 = compiler hsc_env mod_summary
331 where mkComp = hscMkCompiler norecompBatch batchMsg
332 pipeline inp = hscSimpleIface inp >>= hscIgnoreIface >>= hscNothing
334 = case ms_hsc_src mod_summary of
336 -> mkComp hscCoreFrontEnd pipeline
338 -> mkComp hscFileFrontEnd pipeline
340 -> mkComp hscFileFrontEnd pipeline
342 -- Compile Haskell, extCore to bytecode.
343 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
344 hscCompileInteractive hsc_env mod_summary =
345 hscMkCompiler norecompInteractive batchMsg
348 where backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
349 frontend = case ms_hsc_src mod_summary of
350 ExtCoreFile -> hscCoreFrontEnd
351 HsSrcFile -> hscFileFrontEnd
352 HsBootFile -> panic bootErrorMsg
353 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
354 "Use 'hscCompileBatch' instead."
356 --------------------------------------------------------------
358 --------------------------------------------------------------
360 norecompOneShot :: NoRecomp HscStatus
361 norecompOneShot old_iface
362 = do hsc_env <- gets compHscEnv
364 dumpIfaceStats hsc_env
367 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
368 norecompBatch = norecompWorker HscNoRecomp False
370 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
371 norecompInteractive = norecompWorker InteractiveNoRecomp True
373 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
374 norecompWorker a isInterp old_iface
375 = do hsc_env <- gets compHscEnv
376 mod_summary <- gets compModSummary
378 new_details <- {-# SCC "tcRnIface" #-}
379 initIfaceCheck hsc_env $
380 typecheckIface old_iface
381 dumpIfaceStats hsc_env
382 return (a, old_iface, new_details)
384 --------------------------------------------------------------
385 -- Progress displayers.
386 --------------------------------------------------------------
388 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
389 oneShotMsg _mb_mod_index recomp
390 = do hsc_env <- gets compHscEnv
394 else compilationProgressMsg (hsc_dflags hsc_env) $
395 "compilation IS NOT required"
397 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
398 batchMsg mb_mod_index recomp
399 = do hsc_env <- gets compHscEnv
400 mod_summary <- gets compModSummary
401 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
402 (showModuleIndex mb_mod_index ++
403 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
406 then showMsg "Compiling "
407 else if verbosity (hsc_dflags hsc_env) >= 1
408 then showMsg "Skipping "
411 --------------------------------------------------------------
413 --------------------------------------------------------------
415 hscCoreFrontEnd :: FrontEnd ModGuts
417 do hsc_env <- gets compHscEnv
418 mod_summary <- gets compModSummary
423 inp <- readFile (ms_hspp_file mod_summary)
424 case parseCore inp 1 of
426 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
430 -- RENAME and TYPECHECK
432 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
433 tcRnExtCore hsc_env rdr_module
434 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
435 case maybe_tc_result of
436 Nothing -> return Nothing
437 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
440 hscFileFrontEnd :: FrontEnd ModGuts
442 do hsc_env <- gets compHscEnv
443 mod_summary <- gets compModSummary
448 let dflags = hsc_dflags hsc_env
449 hspp_file = ms_hspp_file mod_summary
450 hspp_buf = ms_hspp_buf mod_summary
451 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
454 -> do printBagOfErrors dflags (unitBag err)
458 -- RENAME and TYPECHECK
460 -> do (tc_msgs, maybe_tc_result)
461 <- {-# SCC "Typecheck-Rename" #-}
462 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
463 printErrorsAndWarnings dflags tc_msgs
464 case maybe_tc_result of
471 -> {-# SCC "DeSugar" #-} deSugar hsc_env (ms_location mod_summary) tc_result
473 --------------------------------------------------------------
475 --------------------------------------------------------------
477 hscSimplify :: ModGuts -> Comp ModGuts
478 hscSimplify ds_result
479 = do hsc_env <- gets compHscEnv
481 flat_result <- {-# SCC "Flattening" #-}
482 flatten hsc_env ds_result
486 simpl_result <- {-# SCC "Core2Core" #-}
487 core2core hsc_env flat_result
490 --------------------------------------------------------------
491 -- Interface generators
492 --------------------------------------------------------------
494 -- HACK: we return ModGuts even though we know it's not gonna be used.
495 -- We do this because the type signature needs to be identical
496 -- in structure to the type of 'hscNormalIface'.
497 hscSimpleIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, ModGuts)
498 hscSimpleIface ds_result
499 = do hsc_env <- gets compHscEnv
500 mod_summary <- gets compModSummary
501 maybe_old_iface <- gets compOldIface
503 details <- mkBootModDetails hsc_env ds_result
504 (new_iface, no_change)
505 <- {-# SCC "MkFinalIface" #-}
506 mkIface hsc_env maybe_old_iface ds_result details
507 -- And the answer is ...
508 dumpIfaceStats hsc_env
509 return (new_iface, no_change, details, ds_result)
511 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
512 hscNormalIface simpl_result
513 = do hsc_env <- gets compHscEnv
514 mod_summary <- gets compModSummary
515 maybe_old_iface <- gets compOldIface
520 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
521 tidyProgram hsc_env simpl_result
524 -- BUILD THE NEW ModIface and ModDetails
525 -- and emit external core if necessary
526 -- This has to happen *after* code gen so that the back-end
527 -- info has been set. Not yet clear if it matters waiting
528 -- until after code output
529 (new_iface, no_change)
530 <- {-# SCC "MkFinalIface" #-}
531 mkIface hsc_env maybe_old_iface simpl_result details
532 -- Emit external core
533 emitExternalCore (hsc_dflags hsc_env) (availsToNameSet (mg_exports simpl_result)) cg_guts -- Move this? --Lemmih 03/07/2006
534 dumpIfaceStats hsc_env
537 -- Return the prepared code.
538 return (new_iface, no_change, details, cg_guts)
540 --------------------------------------------------------------
541 -- BackEnd combinators
542 --------------------------------------------------------------
544 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
545 hscWriteIface (iface, no_change, details, a)
546 = do mod_summary <- gets compModSummary
547 hsc_env <- gets compHscEnv
548 let dflags = hsc_dflags hsc_env
551 $ writeIfaceFile dflags (ms_location mod_summary) iface
552 return (iface, details, a)
554 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
555 hscIgnoreIface (iface, no_change, details, a)
556 = return (iface, details, a)
558 -- Don't output any code.
559 hscNothing :: (ModIface, ModDetails, a) -> Comp (HscStatus, ModIface, ModDetails)
560 hscNothing (iface, details, a)
561 = return (HscRecomp False, iface, details)
563 -- Generate code and return both the new ModIface and the ModDetails.
564 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (HscStatus, ModIface, ModDetails)
565 hscBatch (iface, details, cgguts)
566 = do hasStub <- hscCompile cgguts
567 return (HscRecomp hasStub, iface, details)
569 -- Here we don't need the ModIface and ModDetails anymore.
570 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp HscStatus
571 hscOneShot (_, _, cgguts)
572 = do hasStub <- hscCompile cgguts
573 return (HscRecomp hasStub)
575 -- Compile to hard-code.
576 hscCompile :: CgGuts -> Comp Bool
578 = do hsc_env <- gets compHscEnv
579 mod_summary <- gets compModSummary
581 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
582 -- From now on, we just use the bits we need.
583 cg_module = this_mod,
584 cg_binds = core_binds,
586 cg_dir_imps = dir_imps,
587 cg_foreign = foreign_stubs,
588 cg_dep_pkgs = dependencies,
589 cg_hpc_info = hpc_info } = cgguts
590 dflags = hsc_dflags hsc_env
591 location = ms_location mod_summary
592 data_tycons = filter isDataTyCon tycons
593 -- cg_tycons includes newtypes, for the benefit of External Core,
594 -- but we don't generate any code for newtypes
597 -- PREPARE FOR CODE GENERATION
598 -- Do saturation and convert to A-normal form
599 prepd_binds <- {-# SCC "CorePrep" #-}
600 corePrepPgm dflags core_binds data_tycons ;
601 ----------------- Convert to STG ------------------
602 (stg_binds, cost_centre_info)
603 <- {-# SCC "CoreToStg" #-}
604 myCoreToStg dflags this_mod prepd_binds
605 ------------------ Code generation ------------------
606 abstractC <- {-# SCC "CodeGen" #-}
607 codeGen dflags this_mod data_tycons
608 foreign_stubs dir_imps cost_centre_info
610 ------------------ Code output -----------------------
611 (stub_h_exists,stub_c_exists)
612 <- codeOutput dflags this_mod location foreign_stubs
613 dependencies abstractC
616 hscConst :: b -> a -> Comp b
617 hscConst b a = return b
619 hscInteractive :: (ModIface, ModDetails, CgGuts)
620 -> Comp (InteractiveStatus, ModIface, ModDetails)
621 hscInteractive (iface, details, cgguts)
623 = do hsc_env <- gets compHscEnv
624 mod_summary <- gets compModSummary
626 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
627 -- From now on, we just use the bits we need.
628 cg_module = this_mod,
629 cg_binds = core_binds,
631 cg_foreign = foreign_stubs } = cgguts
632 dflags = hsc_dflags hsc_env
633 location = ms_location mod_summary
634 data_tycons = filter isDataTyCon tycons
635 -- cg_tycons includes newtypes, for the benefit of External Core,
636 -- but we don't generate any code for newtypes
639 -- PREPARE FOR CODE GENERATION
640 -- Do saturation and convert to A-normal form
641 prepd_binds <- {-# SCC "CorePrep" #-}
642 corePrepPgm dflags core_binds data_tycons ;
643 ----------------- Generate byte code ------------------
644 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
645 ------------------ Create f-x-dynamic C-side stuff ---
646 (istub_h_exists, istub_c_exists)
647 <- outputForeignStubs dflags this_mod location foreign_stubs
648 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
650 = panic "GHC not compiled with interpreter"
653 ------------------------------
655 hscFileCheck :: HscEnv -> ModSummary -> IO (Maybe HscChecked)
656 hscFileCheck hsc_env mod_summary = do {
660 ; let dflags = hsc_dflags hsc_env
661 hspp_file = ms_hspp_file mod_summary
662 hspp_buf = ms_hspp_buf mod_summary
664 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
666 ; case maybe_parsed of {
667 Left err -> do { printBagOfErrors dflags (unitBag err)
669 Right rdr_module -> do {
672 -- RENAME and TYPECHECK
674 (tc_msgs, maybe_tc_result)
675 <- _scc_ "Typecheck-Rename"
676 tcRnModule hsc_env (ms_hsc_src mod_summary)
677 True{-save renamed syntax-}
680 ; printErrorsAndWarnings dflags tc_msgs
681 ; case maybe_tc_result of {
682 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing));
684 let type_env = tcg_type_env tc_result
687 md_exports = tcg_exports tc_result,
688 md_insts = tcg_insts tc_result,
689 md_fam_insts = tcg_fam_insts tc_result,
690 md_dbg_sites = noDbgSites,
691 md_rules = [panic "no rules"] }
692 -- Rules are CoreRules, not the
693 -- RuleDecls we get out of the typechecker
694 rnInfo = do decl <- tcg_rn_decls tc_result
695 imports <- tcg_rn_imports tc_result
696 let exports = tcg_rn_exports tc_result
697 let doc = tcg_doc tc_result
698 hmi = tcg_hmi tc_result
699 return (decl,imports,exports,doc,hmi)
700 return (Just (HscChecked rdr_module
702 (Just (tcg_binds tc_result,
703 tcg_rdr_env tc_result,
708 hscCmmFile :: DynFlags -> FilePath -> IO Bool
709 hscCmmFile dflags filename = do
710 maybe_cmm <- parseCmmFile dflags filename
712 Nothing -> return False
714 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
717 no_mod = panic "hscCmmFile: no_mod"
718 no_loc = ModLocation{ ml_hs_file = Just filename,
719 ml_hi_file = panic "hscCmmFile: no hi file",
720 ml_obj_file = panic "hscCmmFile: no obj file" }
723 myParseModule dflags src_filename maybe_src_buf
724 = -------------------------- Parser ----------------
725 showPass dflags "Parser" >>
726 {-# SCC "Parser" #-} do
728 -- sometimes we already have the buffer in memory, perhaps
729 -- because we needed to parse the imports out of it, or get the
731 buf <- case maybe_src_buf of
733 Nothing -> hGetStringBuffer src_filename
735 let loc = mkSrcLoc (mkFastString src_filename) 1 0
737 case unP parseModule (mkPState buf loc dflags) of {
739 PFailed span err -> return (Left (mkPlainErrMsg span err));
741 POk pst rdr_module -> do {
743 let {ms = getMessages pst};
744 printErrorsAndWarnings dflags ms;
745 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
747 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
749 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
750 (ppSourceStats False rdr_module) ;
752 return (Right rdr_module)
753 -- ToDo: free the string buffer later.
757 myCoreToStg dflags this_mod prepd_binds
759 stg_binds <- {-# SCC "Core2Stg" #-}
760 coreToStg (thisPackage dflags) prepd_binds
762 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
763 stg2stg dflags this_mod stg_binds
765 return (stg_binds2, cost_centre_info)
769 %************************************************************************
771 \subsection{Compiling a do-statement}
773 %************************************************************************
775 When the UnlinkedBCOExpr is linked you get an HValue of type
777 When you run it you get a list of HValues that should be
778 the same length as the list of names; add them to the ClosureEnv.
780 A naked expression returns a singleton Name [it].
782 What you type The IO [HValue] that hscStmt returns
783 ------------- ------------------------------------
784 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
787 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
790 expr (of IO type) ==> expr >>= \ v -> return [v]
791 [NB: result not printed] bindings: [it]
794 expr (of non-IO type,
795 result showable) ==> let v = expr in print v >> return [v]
798 expr (of non-IO type,
799 result not showable) ==> error
803 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
805 -> String -- The statement
806 -> IO (Maybe (HscEnv, [Name], HValue))
809 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
810 ; case maybe_stmt of {
811 Nothing -> return Nothing ; -- Parse error
812 Just Nothing -> return Nothing ; -- Empty line
813 Just (Just parsed_stmt) -> do { -- The real stuff
815 -- Rename and typecheck it
816 let icontext = hsc_IC hsc_env
817 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
819 ; case maybe_tc_result of {
820 Nothing -> return Nothing ;
821 Just (new_ic, bound_names, tc_expr) -> do {
825 ; let rdr_env = ic_rn_gbl_env new_ic
826 type_env = ic_type_env new_ic
827 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
829 ; case mb_ds_expr of {
830 Nothing -> return Nothing ;
833 -- Then desugar, code gen, and link it
834 ; let src_span = srcLocSpan interactiveSrcLoc
835 ; hval <- compileExpr hsc_env src_span ds_expr
837 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
840 hscTcExpr -- Typecheck an expression (but don't run it)
842 -> String -- The expression
845 hscTcExpr hsc_env expr
846 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
847 ; let icontext = hsc_IC hsc_env
848 ; case maybe_stmt of {
849 Nothing -> return Nothing ; -- Parse error
850 Just (Just (L _ (ExprStmt expr _ _)))
851 -> tcRnExpr hsc_env icontext expr ;
852 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
856 hscKcType -- Find the kind of a type
858 -> String -- The type
861 hscKcType hsc_env str
862 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
863 ; let icontext = hsc_IC hsc_env
864 ; case maybe_type of {
865 Just ty -> tcRnType hsc_env icontext ty ;
866 Nothing -> return Nothing } }
872 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
873 hscParseStmt = hscParseThing parseStmt
875 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
876 hscParseType = hscParseThing parseType
879 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
880 hscParseIdentifier = hscParseThing parseIdentifier
882 hscParseThing :: Outputable thing
884 -> DynFlags -> String
886 -- Nothing => Parse error (message already printed)
888 hscParseThing parser dflags str
889 = showPass dflags "Parser" >>
890 {-# SCC "Parser" #-} do
892 buf <- stringToStringBuffer str
894 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
896 case unP parser (mkPState buf loc dflags) of {
898 PFailed span err -> do { printError span err;
901 POk pst thing -> do {
903 let {ms = getMessages pst};
904 printErrorsAndWarnings dflags ms;
905 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
907 --ToDo: can't free the string buffer until we've finished this
908 -- compilation sweep and all the identifiers have gone away.
909 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
914 %************************************************************************
916 Desugar, simplify, convert to bytecode, and link an expression
918 %************************************************************************
922 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
924 compileExpr hsc_env srcspan ds_expr
925 = do { let { dflags = hsc_dflags hsc_env ;
926 lint_on = dopt Opt_DoCoreLinting dflags }
929 ; flat_expr <- flattenExpr hsc_env ds_expr
932 ; simpl_expr <- simplifyExpr dflags flat_expr
934 -- Tidy it (temporary, until coreSat does cloning)
935 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
937 -- Prepare for codegen
938 ; prepd_expr <- corePrepExpr dflags tidy_expr
941 -- ToDo: improve SrcLoc
943 case lintUnfolding noSrcLoc [] prepd_expr of
944 Just err -> pprPanic "compileExpr" err
950 ; bcos <- coreExprToBCOs dflags prepd_expr
953 ; hval <- linkExpr hsc_env srcspan bcos
961 %************************************************************************
963 Statistics on reading interfaces
965 %************************************************************************
968 dumpIfaceStats :: HscEnv -> IO ()
969 dumpIfaceStats hsc_env
970 = do { eps <- readIORef (hsc_EPS hsc_env)
971 ; dumpIfSet (dump_if_trace || dump_rn_stats)
972 "Interface statistics"
975 dflags = hsc_dflags hsc_env
976 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
977 dump_if_trace = dopt Opt_D_dump_if_trace dflags
980 %************************************************************************
982 Progress Messages: Module i of n
984 %************************************************************************
987 showModuleIndex Nothing = ""
988 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
992 padded = replicate (length n_str - length i_str) ' ' ++ i_str