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 )
57 import Lexer ( P(..), ParseResult(..), mkPState )
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 )
82 import UniqSupply ( mkSplitUniqSupply )
85 import HscStats ( ppSourceStats )
87 import MkExternalCore ( emitExternalCore )
89 import ParserCoreUtils
91 import UniqFM ( emptyUFM )
92 import Bag ( unitBag )
93 import Monad ( unless )
95 import DATA_IOREF ( newIORef, readIORef )
99 %************************************************************************
103 %************************************************************************
106 newHscEnv :: DynFlags -> IO HscEnv
108 = do { eps_var <- newIORef initExternalPackageState
109 ; us <- mkSplitUniqSupply 'r'
110 ; nc_var <- newIORef (initNameCache us knownKeyNames)
111 ; fc_var <- newIORef emptyUFM
112 ; mlc_var <- newIORef emptyModuleEnv
113 ; return (HscEnv { hsc_dflags = dflags,
116 hsc_IC = emptyInteractiveContext,
117 hsc_HPT = emptyHomePackageTable,
122 hsc_global_rdr_env = emptyGlobalRdrEnv,
123 hsc_global_type_env = emptyNameEnv } ) }
126 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
127 -- where templateHaskellNames are defined
128 knownKeyNames = map getName wiredInThings
129 ++ basicKnownKeyNames
131 ++ templateHaskellNames
136 %************************************************************************
138 The main compiler pipeline
140 %************************************************************************
142 --------------------------------
143 The compilation proper
144 --------------------------------
147 It's the task of the compilation proper to compile Haskell, hs-boot and
148 core files to either byte-code, hard-code (C, asm, Java, ect) or to
149 nothing at all (the module is still parsed and type-checked. This
150 feature is mostly used by IDE's and the likes).
151 Compilation can happen in either 'one-shot', 'batch', 'nothing',
152 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
153 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
155 The modes are kept separate because of their different types and meanings.
156 In 'one-shot' mode, we're only compiling a single file and can therefore
157 discard the new ModIface and ModDetails. This is also the reason it only
158 targets hard-code; compiling to byte-code or nothing doesn't make sense
159 when we discard the result.
160 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
161 and ModDetails. 'Batch' mode doesn't target byte-code since that require
162 us to return the newly compiled byte-code.
163 'Nothing' mode has exactly the same type as 'batch' mode but they're still
164 kept separate. This is because compiling to nothing is fairly special: We
165 don't output any interface files, we don't run the simplifier and we don't
167 'Interactive' mode is similar to 'batch' mode except that we return the
168 compiled byte-code together with the ModIface and ModDetails.
170 Trying to compile a hs-boot file to byte-code will result in a run-time
171 error. This is the only thing that isn't caught by the type-system.
178 (Located (HsModule RdrName))
180 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
181 Maybe (HsDoc Name), HaddockModInfo Name))
183 (Maybe (LHsBinds Id, GlobalRdrEnv, ModDetails))
186 -- Status of a compilation to hard-code or nothing.
189 | HscRecomp Bool -- Has stub files.
190 -- This is a hack. We can't compile C files here
191 -- since it's done in DriverPipeline. For now we
192 -- just return True if we want the caller to compile
195 -- Status of a compilation to byte-code.
196 data InteractiveStatus
197 = InteractiveNoRecomp
198 | InteractiveRecomp Bool -- Same as HscStatus
202 -- I want Control.Monad.State! --Lemmih 03/07/2006
203 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
205 instance Monad Comp where
206 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
207 return a = Comp $ \s -> return (a,s)
210 evalComp :: Comp a -> CompState -> IO a
211 evalComp comp st = do (val,_st') <- runComp comp st
216 { compHscEnv :: HscEnv
217 , compModSummary :: ModSummary
218 , compOldIface :: Maybe ModIface
221 get :: Comp CompState
222 get = Comp $ \s -> return (s,s)
224 modify :: (CompState -> CompState) -> Comp ()
225 modify f = Comp $ \s -> return ((), f s)
227 gets :: (CompState -> a) -> Comp a
228 gets getter = do st <- get
231 liftIO :: IO a -> Comp a
232 liftIO ioA = Comp $ \s -> do a <- ioA
235 type NoRecomp result = ModIface -> Comp result
236 type FrontEnd core = Comp (Maybe core)
238 -- FIXME: The old interface and module index are only using in 'batch' and
239 -- 'interactive' mode. They should be removed from 'oneshot' mode.
240 type Compiler result = HscEnv
242 -> Bool -- True <=> source unchanged
243 -> Maybe ModIface -- Old interface, if available
244 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
248 -- This functions checks if recompilation is necessary and
249 -- then combines the FrontEnd and BackEnd to a working compiler.
250 hscMkCompiler :: NoRecomp result -- What to do when recompilation isn't required.
251 -> (Maybe (Int,Int) -> Bool -> Comp ())
253 -> (core -> Comp result) -- Backend.
255 hscMkCompiler norecomp messenger frontend backend
256 hsc_env mod_summary source_unchanged
257 mbOldIface mbModIndex
258 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
259 do (recomp_reqd, mbCheckedIface)
260 <- {-# SCC "checkOldIface" #-}
261 liftIO $ checkOldIface hsc_env mod_summary
262 source_unchanged mbOldIface
263 -- save the interface that comes back from checkOldIface.
264 -- In one-shot mode we don't have the old iface until this
265 -- point, when checkOldIface reads it from the disk.
266 modify (\s -> s{ compOldIface = mbCheckedIface })
267 case mbCheckedIface of
268 Just iface | not recomp_reqd
269 -> do messenger mbModIndex False
270 result <- norecomp iface
273 -> do messenger mbModIndex True
279 -> do result <- backend core
282 --------------------------------------------------------------
284 --------------------------------------------------------------
287 -- Compile Haskell, boot and extCore in OneShot mode.
288 hscCompileOneShot :: Compiler HscStatus
289 hscCompileOneShot hsc_env mod_summary =
290 compiler hsc_env mod_summary
291 where mkComp = hscMkCompiler norecompOneShot oneShotMsg
292 -- How to compile nonBoot files.
293 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
294 hscWriteIface >>= hscOneShot
295 -- How to compile boot files.
296 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= hscConst (HscRecomp False)
298 = case ms_hsc_src mod_summary of
300 -> mkComp hscCoreFrontEnd nonBootComp
302 -> mkComp hscFileFrontEnd nonBootComp
304 -> mkComp hscFileFrontEnd bootComp
306 -- Compile Haskell, boot and extCore in batch mode.
307 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
308 hscCompileBatch hsc_env mod_summary
309 = compiler hsc_env mod_summary
310 where mkComp = hscMkCompiler norecompBatch batchMsg
311 nonBootComp inp = hscSimplify inp >>= hscNormalIface >>=
312 hscWriteIface >>= hscBatch
313 bootComp inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
315 = case ms_hsc_src mod_summary of
317 -> mkComp hscCoreFrontEnd nonBootComp
319 -> mkComp hscFileFrontEnd nonBootComp
321 -> mkComp hscFileFrontEnd bootComp
323 -- Type-check Haskell, boot and extCore.
324 -- Does it make sense to compile extCore to nothing?
325 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
326 hscCompileNothing hsc_env mod_summary
327 = compiler hsc_env mod_summary
328 where mkComp = hscMkCompiler norecompBatch batchMsg
329 pipeline inp = hscSimpleIface inp >>= hscIgnoreIface >>= hscNothing
331 = case ms_hsc_src mod_summary of
333 -> mkComp hscCoreFrontEnd pipeline
335 -> mkComp hscFileFrontEnd pipeline
337 -> mkComp hscFileFrontEnd pipeline
339 -- Compile Haskell, extCore to bytecode.
340 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
341 hscCompileInteractive hsc_env mod_summary =
342 hscMkCompiler norecompInteractive batchMsg
345 where backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
346 frontend = case ms_hsc_src mod_summary of
347 ExtCoreFile -> hscCoreFrontEnd
348 HsSrcFile -> hscFileFrontEnd
349 HsBootFile -> panic bootErrorMsg
350 bootErrorMsg = "Compiling a HsBootFile to bytecode doesn't make sense. " ++
351 "Use 'hscCompileBatch' instead."
353 --------------------------------------------------------------
355 --------------------------------------------------------------
357 norecompOneShot :: NoRecomp HscStatus
358 norecompOneShot old_iface
359 = do hsc_env <- gets compHscEnv
361 dumpIfaceStats hsc_env
364 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
365 norecompBatch = norecompWorker HscNoRecomp False
367 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
368 norecompInteractive = norecompWorker InteractiveNoRecomp True
370 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
371 norecompWorker a isInterp old_iface
372 = do hsc_env <- gets compHscEnv
373 mod_summary <- gets compModSummary
375 new_details <- {-# SCC "tcRnIface" #-}
376 initIfaceCheck hsc_env $
377 typecheckIface old_iface
378 dumpIfaceStats hsc_env
379 return (a, old_iface, new_details)
381 --------------------------------------------------------------
382 -- Progress displayers.
383 --------------------------------------------------------------
385 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
386 oneShotMsg _mb_mod_index recomp
387 = do hsc_env <- gets compHscEnv
391 else compilationProgressMsg (hsc_dflags hsc_env) $
392 "compilation IS NOT required"
394 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
395 batchMsg mb_mod_index recomp
396 = do hsc_env <- gets compHscEnv
397 mod_summary <- gets compModSummary
398 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
399 (showModuleIndex mb_mod_index ++
400 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
403 then showMsg "Compiling "
404 else if verbosity (hsc_dflags hsc_env) >= 1
405 then showMsg "Skipping "
408 --------------------------------------------------------------
410 --------------------------------------------------------------
412 hscCoreFrontEnd :: FrontEnd ModGuts
414 do hsc_env <- gets compHscEnv
415 mod_summary <- gets compModSummary
420 inp <- readFile (ms_hspp_file mod_summary)
421 case parseCore inp 1 of
423 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
427 -- RENAME and TYPECHECK
429 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
430 tcRnExtCore hsc_env rdr_module
431 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
432 case maybe_tc_result of
433 Nothing -> return Nothing
434 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
437 hscFileFrontEnd :: FrontEnd ModGuts
439 do hsc_env <- gets compHscEnv
440 mod_summary <- gets compModSummary
445 let dflags = hsc_dflags hsc_env
446 hspp_file = ms_hspp_file mod_summary
447 hspp_buf = ms_hspp_buf mod_summary
448 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
451 -> do printBagOfErrors dflags (unitBag err)
455 -- RENAME and TYPECHECK
457 -> do (tc_msgs, maybe_tc_result)
458 <- {-# SCC "Typecheck-Rename" #-}
459 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
460 printErrorsAndWarnings dflags tc_msgs
461 case maybe_tc_result of
468 -> {-# SCC "DeSugar" #-} deSugar hsc_env tc_result
470 --------------------------------------------------------------
472 --------------------------------------------------------------
474 hscSimplify :: ModGuts -> Comp ModGuts
475 hscSimplify ds_result
476 = do hsc_env <- gets compHscEnv
478 flat_result <- {-# SCC "Flattening" #-}
479 flatten hsc_env ds_result
483 simpl_result <- {-# SCC "Core2Core" #-}
484 core2core hsc_env flat_result
487 --------------------------------------------------------------
488 -- Interface generators
489 --------------------------------------------------------------
491 -- HACK: we return ModGuts even though we know it's not gonna be used.
492 -- We do this because the type signature needs to be identical
493 -- in structure to the type of 'hscNormalIface'.
494 hscSimpleIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, ModGuts)
495 hscSimpleIface ds_result
496 = do hsc_env <- gets compHscEnv
497 mod_summary <- gets compModSummary
498 maybe_old_iface <- gets compOldIface
500 details <- mkBootModDetails hsc_env ds_result
501 (new_iface, no_change)
502 <- {-# SCC "MkFinalIface" #-}
503 mkIface hsc_env maybe_old_iface ds_result details
504 -- And the answer is ...
505 dumpIfaceStats hsc_env
506 return (new_iface, no_change, details, ds_result)
508 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
509 hscNormalIface simpl_result
510 = do hsc_env <- gets compHscEnv
511 mod_summary <- gets compModSummary
512 maybe_old_iface <- gets compOldIface
517 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
518 tidyProgram hsc_env simpl_result
521 -- BUILD THE NEW ModIface and ModDetails
522 -- and emit external core if necessary
523 -- This has to happen *after* code gen so that the back-end
524 -- info has been set. Not yet clear if it matters waiting
525 -- until after code output
526 (new_iface, no_change)
527 <- {-# SCC "MkFinalIface" #-}
528 mkIface hsc_env maybe_old_iface simpl_result details
529 -- Emit external core
530 emitExternalCore (hsc_dflags hsc_env) (mg_exports simpl_result) cg_guts -- Move this? --Lemmih 03/07/2006
531 dumpIfaceStats hsc_env
534 -- Return the prepared code.
535 return (new_iface, no_change, details, cg_guts)
537 --------------------------------------------------------------
538 -- BackEnd combinators
539 --------------------------------------------------------------
541 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
542 hscWriteIface (iface, no_change, details, a)
543 = do mod_summary <- gets compModSummary
546 $ writeIfaceFile (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 } = cgguts
584 dflags = hsc_dflags hsc_env
585 location = ms_location mod_summary
586 data_tycons = filter isDataTyCon tycons
587 -- cg_tycons includes newtypes, for the benefit of External Core,
588 -- but we don't generate any code for newtypes
591 -- PREPARE FOR CODE GENERATION
592 -- Do saturation and convert to A-normal form
593 prepd_binds <- {-# SCC "CorePrep" #-}
594 corePrepPgm dflags core_binds data_tycons ;
595 ----------------- Convert to STG ------------------
596 (stg_binds, cost_centre_info)
597 <- {-# SCC "CoreToStg" #-}
598 myCoreToStg dflags this_mod prepd_binds
599 ------------------ Code generation ------------------
600 abstractC <- {-# SCC "CodeGen" #-}
601 codeGen dflags this_mod data_tycons
602 foreign_stubs dir_imps cost_centre_info
604 ------------------ Code output -----------------------
605 (stub_h_exists,stub_c_exists)
606 <- codeOutput dflags this_mod location foreign_stubs
607 dependencies abstractC
610 hscConst :: b -> a -> Comp b
611 hscConst b a = return b
613 hscInteractive :: (ModIface, ModDetails, CgGuts)
614 -> Comp (InteractiveStatus, ModIface, ModDetails)
615 hscInteractive (iface, details, cgguts)
617 = do hsc_env <- gets compHscEnv
618 mod_summary <- gets compModSummary
620 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
621 -- From now on, we just use the bits we need.
622 cg_module = this_mod,
623 cg_binds = core_binds,
625 cg_foreign = foreign_stubs } = cgguts
626 dflags = hsc_dflags hsc_env
627 location = ms_location mod_summary
628 data_tycons = filter isDataTyCon tycons
629 -- cg_tycons includes newtypes, for the benefit of External Core,
630 -- but we don't generate any code for newtypes
633 -- PREPARE FOR CODE GENERATION
634 -- Do saturation and convert to A-normal form
635 prepd_binds <- {-# SCC "CorePrep" #-}
636 corePrepPgm dflags core_binds data_tycons ;
637 ----------------- Generate byte code ------------------
638 comp_bc <- byteCodeGen dflags prepd_binds data_tycons
639 ------------------ Create f-x-dynamic C-side stuff ---
640 (istub_h_exists, istub_c_exists)
641 <- outputForeignStubs dflags this_mod location foreign_stubs
642 return (InteractiveRecomp istub_c_exists comp_bc, iface, details)
644 = panic "GHC not compiled with interpreter"
647 ------------------------------
649 hscFileCheck :: HscEnv -> ModSummary -> IO (Maybe HscChecked)
650 hscFileCheck hsc_env mod_summary = do {
654 ; let dflags = hsc_dflags hsc_env
655 hspp_file = ms_hspp_file mod_summary
656 hspp_buf = ms_hspp_buf mod_summary
658 ; maybe_parsed <- myParseModule dflags hspp_file hspp_buf
660 ; case maybe_parsed of {
661 Left err -> do { printBagOfErrors dflags (unitBag err)
663 Right rdr_module -> do {
666 -- RENAME and TYPECHECK
668 (tc_msgs, maybe_tc_result)
669 <- _scc_ "Typecheck-Rename"
670 tcRnModule hsc_env (ms_hsc_src mod_summary)
671 True{-save renamed syntax-}
674 ; printErrorsAndWarnings dflags tc_msgs
675 ; case maybe_tc_result of {
676 Nothing -> return (Just (HscChecked rdr_module Nothing Nothing));
678 let type_env = tcg_type_env tc_result
681 md_exports = tcg_exports tc_result,
682 md_insts = tcg_insts tc_result,
683 md_fam_insts = mkDetailsFamInstCache type_env,
684 md_rules = [panic "no rules"] }
685 -- Rules are CoreRules, not the
686 -- RuleDecls we get out of the typechecker
687 rnInfo = do decl <- tcg_rn_decls tc_result
688 imports <- tcg_rn_imports tc_result
689 let exports = tcg_rn_exports tc_result
690 let doc = tcg_doc tc_result
691 hmi = tcg_hmi tc_result
692 return (decl,imports,exports,doc,hmi)
693 return (Just (HscChecked rdr_module
695 (Just (tcg_binds tc_result,
696 tcg_rdr_env tc_result,
701 hscCmmFile :: DynFlags -> FilePath -> IO Bool
702 hscCmmFile dflags filename = do
703 maybe_cmm <- parseCmmFile dflags filename
705 Nothing -> return False
707 codeOutput dflags no_mod no_loc NoStubs [] [cmm]
710 no_mod = panic "hscCmmFile: no_mod"
711 no_loc = ModLocation{ ml_hs_file = Just filename,
712 ml_hi_file = panic "hscCmmFile: no hi file",
713 ml_obj_file = panic "hscCmmFile: no obj file" }
716 myParseModule dflags src_filename maybe_src_buf
717 = -------------------------- Parser ----------------
718 showPass dflags "Parser" >>
719 {-# SCC "Parser" #-} do
721 -- sometimes we already have the buffer in memory, perhaps
722 -- because we needed to parse the imports out of it, or get the
724 buf <- case maybe_src_buf of
726 Nothing -> hGetStringBuffer src_filename
728 let loc = mkSrcLoc (mkFastString src_filename) 1 0
730 case unP parseModule (mkPState buf loc dflags) of {
732 PFailed span err -> return (Left (mkPlainErrMsg span err));
734 POk _ rdr_module -> do {
736 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
738 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
739 (ppSourceStats False rdr_module) ;
741 return (Right rdr_module)
742 -- ToDo: free the string buffer later.
746 myCoreToStg dflags this_mod prepd_binds
748 stg_binds <- {-# SCC "Core2Stg" #-}
749 coreToStg (thisPackage dflags) prepd_binds
751 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
752 stg2stg dflags this_mod stg_binds
754 return (stg_binds2, cost_centre_info)
758 %************************************************************************
760 \subsection{Compiling a do-statement}
762 %************************************************************************
764 When the UnlinkedBCOExpr is linked you get an HValue of type
766 When you run it you get a list of HValues that should be
767 the same length as the list of names; add them to the ClosureEnv.
769 A naked expression returns a singleton Name [it].
771 What you type The IO [HValue] that hscStmt returns
772 ------------- ------------------------------------
773 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
776 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
779 expr (of IO type) ==> expr >>= \ v -> return [v]
780 [NB: result not printed] bindings: [it]
783 expr (of non-IO type,
784 result showable) ==> let v = expr in print v >> return [v]
787 expr (of non-IO type,
788 result not showable) ==> error
792 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
794 -> String -- The statement
795 -> IO (Maybe (HscEnv, [Name], HValue))
798 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
799 ; case maybe_stmt of {
800 Nothing -> return Nothing ; -- Parse error
801 Just Nothing -> return Nothing ; -- Empty line
802 Just (Just parsed_stmt) -> do { -- The real stuff
804 -- Rename and typecheck it
805 let icontext = hsc_IC hsc_env
806 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
808 ; case maybe_tc_result of {
809 Nothing -> return Nothing ;
810 Just (new_ic, bound_names, tc_expr) -> do {
814 ; let rdr_env = ic_rn_gbl_env new_ic
815 type_env = ic_type_env new_ic
816 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
818 ; case mb_ds_expr of {
819 Nothing -> return Nothing ;
822 -- Then desugar, code gen, and link it
823 ; let src_span = srcLocSpan interactiveSrcLoc
824 ; hval <- compileExpr hsc_env src_span ds_expr
826 ; return (Just (hsc_env{ hsc_IC=new_ic }, bound_names, hval))
829 hscTcExpr -- Typecheck an expression (but don't run it)
831 -> String -- The expression
834 hscTcExpr hsc_env expr
835 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
836 ; let icontext = hsc_IC hsc_env
837 ; case maybe_stmt of {
838 Nothing -> return Nothing ; -- Parse error
839 Just (Just (L _ (ExprStmt expr _ _)))
840 -> tcRnExpr hsc_env icontext expr ;
841 Just other -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
845 hscKcType -- Find the kind of a type
847 -> String -- The type
850 hscKcType hsc_env str
851 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
852 ; let icontext = hsc_IC hsc_env
853 ; case maybe_type of {
854 Just ty -> tcRnType hsc_env icontext ty ;
855 Nothing -> return Nothing } }
861 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
862 hscParseStmt = hscParseThing parseStmt
864 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
865 hscParseType = hscParseThing parseType
868 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
869 hscParseIdentifier = hscParseThing parseIdentifier
871 hscParseThing :: Outputable thing
873 -> DynFlags -> String
875 -- Nothing => Parse error (message already printed)
877 hscParseThing parser dflags str
878 = showPass dflags "Parser" >>
879 {-# SCC "Parser" #-} do
881 buf <- stringToStringBuffer str
883 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
885 case unP parser (mkPState buf loc dflags) of {
887 PFailed span err -> do { printError span err;
892 --ToDo: can't free the string buffer until we've finished this
893 -- compilation sweep and all the identifiers have gone away.
894 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
899 %************************************************************************
901 Desugar, simplify, convert to bytecode, and link an expression
903 %************************************************************************
907 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
909 compileExpr hsc_env srcspan ds_expr
910 = do { let { dflags = hsc_dflags hsc_env ;
911 lint_on = dopt Opt_DoCoreLinting dflags }
914 ; flat_expr <- flattenExpr hsc_env ds_expr
917 ; simpl_expr <- simplifyExpr dflags flat_expr
919 -- Tidy it (temporary, until coreSat does cloning)
920 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
922 -- Prepare for codegen
923 ; prepd_expr <- corePrepExpr dflags tidy_expr
926 -- ToDo: improve SrcLoc
928 case lintUnfolding noSrcLoc [] prepd_expr of
929 Just err -> pprPanic "compileExpr" err
935 ; bcos <- coreExprToBCOs dflags prepd_expr
938 ; hval <- linkExpr hsc_env srcspan bcos
946 %************************************************************************
948 Statistics on reading interfaces
950 %************************************************************************
953 dumpIfaceStats :: HscEnv -> IO ()
954 dumpIfaceStats hsc_env
955 = do { eps <- readIORef (hsc_EPS hsc_env)
956 ; dumpIfSet (dump_if_trace || dump_rn_stats)
957 "Interface statistics"
960 dflags = hsc_dflags hsc_env
961 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
962 dump_if_trace = dopt Opt_D_dump_if_trace dflags
965 %************************************************************************
967 Progress Messages: Module i of n
969 %************************************************************************
972 showModuleIndex Nothing = ""
973 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
977 padded = replicate (length n_str - length i_str) ' ' ++ i_str