2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 ( newHscEnv, hscCmmFile
12 , hscStmt, hscTcExpr, hscKcType
15 , hscCompileOneShot -- :: Compiler HscStatus
16 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
17 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
18 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
20 , InteractiveStatus (..)
25 , typecheckRenameModule
31 #include "HsVersions.h"
34 import CodeOutput ( outputForeignStubs )
35 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
36 import Linker ( HValue, linkExpr )
37 import CoreTidy ( tidyExpr )
38 import CorePrep ( corePrepExpr )
39 import Flattening ( flattenExpr )
40 import Desugar ( deSugarExpr )
41 import SimplCore ( simplifyExpr )
42 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
44 import PrelNames ( iNTERACTIVE )
45 import {- Kind parts of -} Type ( Kind )
46 import CoreLint ( lintUnfolding )
47 import DsMeta ( templateHaskellNames )
48 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan )
50 import VarEnv ( emptyTidyEnv )
54 import Module ( emptyModuleEnv, ModLocation(..), Module )
58 import SrcLoc ( Located(..) )
62 import SrcLoc ( mkSrcLoc )
63 import TcRnDriver ( tcRnModule, tcRnExtCore )
64 import TcIface ( typecheckIface )
65 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
66 import IfaceEnv ( initNameCache )
67 import LoadIface ( ifaceStats, initExternalPackageState )
68 import PrelInfo ( wiredInThings, basicKnownKeyNames )
70 import Desugar ( deSugar )
71 import SimplCore ( core2core )
73 import CorePrep ( corePrepPgm )
74 import CoreToStg ( coreToStg )
77 import TyCon ( isDataTyCon )
78 import Name ( Name, NamedThing(..) )
79 import SimplStg ( stg2stg )
80 import CodeGen ( codeGen )
82 import CmmParse ( parseCmmFile )
89 import CodeOutput ( codeOutput )
90 import NameEnv ( emptyNameEnv )
94 import UniqSupply ( mkSplitUniqSupply )
97 import HscStats ( ppSourceStats )
99 import MkExternalCore ( emitExternalCore )
101 import ParserCoreUtils
103 import UniqFM ( emptyUFM )
104 import UniqSupply ( initUs_ )
105 import Bag ( unitBag )
114 %************************************************************************
118 %************************************************************************
121 newHscEnv :: DynFlags -> IO HscEnv
123 = do { eps_var <- newIORef initExternalPackageState
124 ; us <- mkSplitUniqSupply 'r'
125 ; nc_var <- newIORef (initNameCache us knownKeyNames)
126 ; fc_var <- newIORef emptyUFM
127 ; mlc_var <- newIORef emptyModuleEnv
128 ; return (HscEnv { hsc_dflags = dflags,
131 hsc_IC = emptyInteractiveContext,
132 hsc_HPT = emptyHomePackageTable,
137 hsc_global_rdr_env = emptyGlobalRdrEnv,
138 hsc_global_type_env = emptyNameEnv } ) }
141 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
142 -- where templateHaskellNames are defined
143 knownKeyNames = map getName wiredInThings
144 ++ basicKnownKeyNames
146 ++ templateHaskellNames
152 -- | parse a file, returning the abstract syntax
153 parseFile :: HscEnv -> ModSummary -> IO (Maybe (Located (HsModule RdrName)))
154 parseFile hsc_env mod_summary
156 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
159 -> do printBagOfErrors dflags (unitBag err)
162 -> return (Just rdr_module)
164 dflags = hsc_dflags hsc_env
165 hspp_file = ms_hspp_file mod_summary
166 hspp_buf = ms_hspp_buf mod_summary
168 -- | Rename and typecheck a module
169 typecheckModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
170 -> IO (Maybe TcGblEnv)
171 typecheckModule hsc_env mod_summary rdr_module
173 (tc_msgs, maybe_tc_result)
174 <- {-# SCC "Typecheck-Rename" #-}
175 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
176 printErrorsAndWarnings dflags tc_msgs
177 return maybe_tc_result
179 dflags = hsc_dflags hsc_env
182 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
183 Maybe (HsDoc Name), HaddockModInfo Name))
185 -- | Rename and typecheck a module, additinoally returning the renamed syntax
186 typecheckRenameModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
187 -> IO (Maybe (TcGblEnv, RenamedStuff))
188 typecheckRenameModule hsc_env mod_summary rdr_module
190 (tc_msgs, maybe_tc_result)
191 <- {-# SCC "Typecheck-Rename" #-}
192 tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
193 printErrorsAndWarnings dflags tc_msgs
194 case maybe_tc_result of
195 Nothing -> return Nothing
197 let rn_info = do decl <- tcg_rn_decls tc_result
198 imports <- tcg_rn_imports tc_result
199 let exports = tcg_rn_exports tc_result
200 let doc = tcg_doc tc_result
201 let hmi = tcg_hmi tc_result
202 return (decl,imports,exports,doc,hmi)
203 return (Just (tc_result, rn_info))
205 dflags = hsc_dflags hsc_env
207 -- | Convert a typechecked module to Core
208 deSugarModule :: HscEnv -> ModSummary -> TcGblEnv -> IO (Maybe ModGuts)
209 deSugarModule hsc_env mod_summary tc_result
210 = deSugar hsc_env (ms_location mod_summary) tc_result
212 -- | Make a 'ModIface' from the results of typechecking. Used when
213 -- not optimising, and the interface doesn't need to contain any
214 -- unfoldings or other cross-module optimisation info.
215 -- ToDo: the old interface is only needed to get the version numbers,
216 -- we should use fingerprint versions instead.
217 makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
218 -> IO (ModIface,Bool)
219 makeSimpleIface hsc_env maybe_old_iface tc_result details = do
220 mkIfaceTc hsc_env maybe_old_iface details tc_result
222 -- | Make a 'ModDetails' from the results of typechecking. Used when
223 -- typechecking only, as opposed to full compilation.
224 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
225 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
227 -- deSugarModule :: HscEnv -> TcGblEnv -> IO Core
230 %************************************************************************
232 The main compiler pipeline
234 %************************************************************************
236 --------------------------------
237 The compilation proper
238 --------------------------------
241 It's the task of the compilation proper to compile Haskell, hs-boot and
242 core files to either byte-code, hard-code (C, asm, Java, ect) or to
243 nothing at all (the module is still parsed and type-checked. This
244 feature is mostly used by IDE's and the likes).
245 Compilation can happen in either 'one-shot', 'batch', 'nothing',
246 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
247 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
249 The modes are kept separate because of their different types and meanings.
250 In 'one-shot' mode, we're only compiling a single file and can therefore
251 discard the new ModIface and ModDetails. This is also the reason it only
252 targets hard-code; compiling to byte-code or nothing doesn't make sense
253 when we discard the result.
254 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
255 and ModDetails. 'Batch' mode doesn't target byte-code since that require
256 us to return the newly compiled byte-code.
257 'Nothing' mode has exactly the same type as 'batch' mode but they're still
258 kept separate. This is because compiling to nothing is fairly special: We
259 don't output any interface files, we don't run the simplifier and we don't
261 'Interactive' mode is similar to 'batch' mode except that we return the
262 compiled byte-code together with the ModIface and ModDetails.
264 Trying to compile a hs-boot file to byte-code will result in a run-time
265 error. This is the only thing that isn't caught by the type-system.
269 -- Status of a compilation to hard-code or nothing.
272 | HscRecomp Bool -- Has stub files.
273 -- This is a hack. We can't compile C files here
274 -- since it's done in DriverPipeline. For now we
275 -- just return True if we want the caller to compile
278 -- Status of a compilation to byte-code.
279 data InteractiveStatus
280 = InteractiveNoRecomp
281 | InteractiveRecomp Bool -- Same as HscStatus
286 -- I want Control.Monad.State! --Lemmih 03/07/2006
287 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
289 instance Monad Comp where
290 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
291 return a = Comp $ \s -> return (a,s)
294 evalComp :: Comp a -> CompState -> IO a
295 evalComp comp st = do (val,_st') <- runComp comp st
300 { compHscEnv :: HscEnv
301 , compModSummary :: ModSummary
302 , compOldIface :: Maybe ModIface
305 get :: Comp CompState
306 get = Comp $ \s -> return (s,s)
308 modify :: (CompState -> CompState) -> Comp ()
309 modify f = Comp $ \s -> return ((), f s)
311 gets :: (CompState -> a) -> Comp a
312 gets getter = do st <- get
315 liftIO :: IO a -> Comp a
316 liftIO ioA = Comp $ \s -> do a <- ioA
319 type NoRecomp result = ModIface -> Comp result
321 -- FIXME: The old interface and module index are only using in 'batch' and
322 -- 'interactive' mode. They should be removed from 'oneshot' mode.
323 type Compiler result = HscEnv
325 -> Bool -- True <=> source unchanged
326 -> Maybe ModIface -- Old interface, if available
327 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
330 --------------------------------------------------------------
332 --------------------------------------------------------------
334 -- Compile Haskell, boot and extCore in OneShot mode.
335 hscCompileOneShot :: Compiler HscStatus
337 = hscCompiler norecompOneShot oneShotMsg (genComp backend boot_backend)
339 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscOneShot
340 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >> return (Just (HscRecomp False))
342 -- Compile Haskell, boot and extCore in batch mode.
343 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
345 = hscCompiler norecompBatch batchMsg (genComp backend boot_backend)
347 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscBatch
348 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
350 -- Compile Haskell, extCore to bytecode.
351 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
352 hscCompileInteractive
353 = hscCompiler norecompInteractive batchMsg (genComp backend boot_backend)
355 backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
356 boot_backend _ = panic "hscCompileInteractive: HsBootFile"
358 -- Type-check Haskell and .hs-boot only (no external core)
359 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
361 = hscCompiler norecompBatch batchMsg comp
363 backend tc = hscSimpleIface tc >>= hscIgnoreIface >>= hscNothing
365 comp = do -- genComp doesn't fit here, because we want to omit
366 -- desugaring and for the backend to take a TcGblEnv
367 mod_summary <- gets compModSummary
368 case ms_hsc_src mod_summary of
369 ExtCoreFile -> panic "hscCompileNothing: cannot do external core"
371 mb_tc <- hscFileFrontEnd
373 Nothing -> return Nothing
374 Just tc_result -> backend tc_result
377 :: NoRecomp result -- No recomp necessary
378 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
379 -> Comp (Maybe result)
381 hscCompiler norecomp messenger recomp hsc_env mod_summary
382 source_unchanged mbOldIface mbModIndex
383 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
384 do (recomp_reqd, mbCheckedIface)
385 <- {-# SCC "checkOldIface" #-}
386 liftIO $ checkOldIface hsc_env mod_summary
387 source_unchanged mbOldIface
388 -- save the interface that comes back from checkOldIface.
389 -- In one-shot mode we don't have the old iface until this
390 -- point, when checkOldIface reads it from the disk.
391 modify (\s -> s{ compOldIface = mbCheckedIface })
392 case mbCheckedIface of
393 Just iface | not recomp_reqd
394 -> do messenger mbModIndex False
395 result <- norecomp iface
398 -> do messenger mbModIndex True
401 -- the usual way to build the Comp (Maybe result) to pass to hscCompiler
402 genComp :: (ModGuts -> Comp (Maybe a))
403 -> (TcGblEnv -> Comp (Maybe a))
405 genComp backend boot_backend = do
406 mod_summary <- gets compModSummary
407 case ms_hsc_src mod_summary of
409 mb_modguts <- hscCoreFrontEnd
411 Nothing -> return Nothing
412 Just guts -> backend guts
414 mb_tc <- hscFileFrontEnd
416 Nothing -> return Nothing
418 case ms_hsc_src mod_summary of
419 HsBootFile -> boot_backend tc_result
421 mb_guts <- hscDesugar tc_result
423 Nothing -> return Nothing
424 Just guts -> backend guts
426 --------------------------------------------------------------
428 --------------------------------------------------------------
430 norecompOneShot :: NoRecomp HscStatus
431 norecompOneShot _old_iface
432 = do hsc_env <- gets compHscEnv
434 dumpIfaceStats hsc_env
437 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
438 norecompBatch = norecompWorker HscNoRecomp False
440 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
441 norecompInteractive = norecompWorker InteractiveNoRecomp True
443 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
444 norecompWorker a _isInterp old_iface
445 = do hsc_env <- gets compHscEnv
447 new_details <- {-# SCC "tcRnIface" #-}
448 initIfaceCheck hsc_env $
449 typecheckIface old_iface
450 dumpIfaceStats hsc_env
451 return (a, old_iface, new_details)
453 --------------------------------------------------------------
454 -- Progress displayers.
455 --------------------------------------------------------------
457 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
458 oneShotMsg _mb_mod_index recomp
459 = do hsc_env <- gets compHscEnv
463 else compilationProgressMsg (hsc_dflags hsc_env) $
464 "compilation IS NOT required"
466 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
467 batchMsg mb_mod_index recomp
468 = do hsc_env <- gets compHscEnv
469 mod_summary <- gets compModSummary
470 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
471 (showModuleIndex mb_mod_index ++
472 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
475 then showMsg "Compiling "
476 else if verbosity (hsc_dflags hsc_env) >= 2
477 then showMsg "Skipping "
480 --------------------------------------------------------------
482 --------------------------------------------------------------
484 hscCoreFrontEnd :: Comp (Maybe ModGuts)
486 do hsc_env <- gets compHscEnv
487 mod_summary <- gets compModSummary
492 inp <- readFile (ms_hspp_file mod_summary)
493 case parseCore inp 1 of
495 -> do errorMsg (hsc_dflags hsc_env) (text s{-ToDo: wrong-})
499 -- RENAME and TYPECHECK
501 -> do (tc_msgs, maybe_tc_result) <- {-# SCC "TypeCheck" #-}
502 tcRnExtCore hsc_env rdr_module
503 printErrorsAndWarnings (hsc_dflags hsc_env) tc_msgs
504 case maybe_tc_result of
505 Nothing -> return Nothing
506 Just mod_guts -> return (Just mod_guts) -- No desugaring to do!
509 hscFileFrontEnd :: Comp (Maybe TcGblEnv)
511 do hsc_env <- gets compHscEnv
512 mod_summary <- gets compModSummary
517 let dflags = hsc_dflags hsc_env
518 hspp_file = ms_hspp_file mod_summary
519 hspp_buf = ms_hspp_buf mod_summary
520 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
523 -> do printBagOfErrors dflags (unitBag err)
527 -- RENAME and TYPECHECK
529 -> do (tc_msgs, maybe_tc_result)
530 <- {-# SCC "Typecheck-Rename" #-}
531 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
532 printErrorsAndWarnings dflags tc_msgs
533 return maybe_tc_result
535 --------------------------------------------------------------
537 --------------------------------------------------------------
539 hscDesugar :: TcGblEnv -> Comp (Maybe ModGuts)
541 = do mod_summary <- gets compModSummary
542 hsc_env <- gets compHscEnv
547 ds_result <- {-# SCC "DeSugar" #-}
548 deSugar hsc_env (ms_location mod_summary) tc_result
551 --------------------------------------------------------------
553 --------------------------------------------------------------
555 hscSimplify :: ModGuts -> Comp ModGuts
556 hscSimplify ds_result
557 = do hsc_env <- gets compHscEnv
562 simpl_result <- {-# SCC "Core2Core" #-}
563 core2core hsc_env ds_result
566 --------------------------------------------------------------
567 -- Interface generators
568 --------------------------------------------------------------
570 -- HACK: we return ModGuts even though we know it's not gonna be used.
571 -- We do this because the type signature needs to be identical
572 -- in structure to the type of 'hscNormalIface'.
573 hscSimpleIface :: TcGblEnv -> Comp (ModIface, Bool, ModDetails, TcGblEnv)
574 hscSimpleIface tc_result
575 = do hsc_env <- gets compHscEnv
576 maybe_old_iface <- gets compOldIface
578 details <- mkBootModDetailsTc hsc_env tc_result
579 (new_iface, no_change)
580 <- {-# SCC "MkFinalIface" #-}
581 mkIfaceTc hsc_env maybe_old_iface details tc_result
582 -- And the answer is ...
583 dumpIfaceStats hsc_env
584 return (new_iface, no_change, details, tc_result)
586 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
587 hscNormalIface simpl_result
588 = do hsc_env <- gets compHscEnv
589 _mod_summary <- gets compModSummary
590 maybe_old_iface <- gets compOldIface
595 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
596 tidyProgram hsc_env simpl_result
599 -- BUILD THE NEW ModIface and ModDetails
600 -- and emit external core if necessary
601 -- This has to happen *after* code gen so that the back-end
602 -- info has been set. Not yet clear if it matters waiting
603 -- until after code output
604 (new_iface, no_change)
605 <- {-# SCC "MkFinalIface" #-}
606 mkIface hsc_env maybe_old_iface details simpl_result
607 -- Emit external core
608 emitExternalCore (hsc_dflags hsc_env) (availsToNameSet (mg_exports simpl_result)) cg_guts -- Move this? --Lemmih 03/07/2006
609 dumpIfaceStats hsc_env
612 -- Return the prepared code.
613 return (new_iface, no_change, details, cg_guts)
615 --------------------------------------------------------------
616 -- BackEnd combinators
617 --------------------------------------------------------------
619 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
620 hscWriteIface (iface, no_change, details, a)
621 = do mod_summary <- gets compModSummary
622 hsc_env <- gets compHscEnv
623 let dflags = hsc_dflags hsc_env
626 $ writeIfaceFile dflags (ms_location mod_summary) iface
627 return (iface, details, a)
629 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
630 hscIgnoreIface (iface, _no_change, details, a)
631 = return (iface, details, a)
633 -- Don't output any code.
634 hscNothing :: (ModIface, ModDetails, a) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
635 hscNothing (iface, details, _)
636 = return (Just (HscRecomp False, iface, details))
638 -- Generate code and return both the new ModIface and the ModDetails.
639 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
640 hscBatch (iface, details, cgguts)
641 = do hasStub <- hscCompile cgguts
642 return (Just (HscRecomp hasStub, iface, details))
644 -- Here we don't need the ModIface and ModDetails anymore.
645 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe HscStatus)
646 hscOneShot (_, _, cgguts)
647 = do hasStub <- hscCompile cgguts
648 return (Just (HscRecomp hasStub))
650 -- Compile to hard-code.
651 hscCompile :: CgGuts -> Comp Bool
653 = do hsc_env <- gets compHscEnv
654 mod_summary <- gets compModSummary
656 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
657 -- From now on, we just use the bits we need.
658 cg_module = this_mod,
659 cg_binds = core_binds,
661 cg_dir_imps = dir_imps,
662 cg_foreign = foreign_stubs,
663 cg_dep_pkgs = dependencies,
664 cg_hpc_info = hpc_info } = cgguts
665 dflags = hsc_dflags hsc_env
666 location = ms_location mod_summary
667 data_tycons = filter isDataTyCon tycons
668 -- cg_tycons includes newtypes, for the benefit of External Core,
669 -- but we don't generate any code for newtypes
672 -- PREPARE FOR CODE GENERATION
673 -- Do saturation and convert to A-normal form
674 prepd_binds <- {-# SCC "CorePrep" #-}
675 corePrepPgm dflags core_binds data_tycons ;
676 ----------------- Convert to STG ------------------
677 (stg_binds, cost_centre_info)
678 <- {-# SCC "CoreToStg" #-}
679 myCoreToStg dflags this_mod prepd_binds
680 ------------------ Code generation ------------------
681 cmms <- {-# SCC "CodeGen" #-}
682 codeGen dflags this_mod data_tycons
683 dir_imps cost_centre_info
685 --- Optionally run experimental Cmm transformations ---
686 cmms <- optionallyConvertAndOrCPS dflags cmms
687 -- ^ unless certain dflags are on, the identity function
688 ------------------ Code output -----------------------
689 rawcmms <- cmmToRawCmm cmms
690 (_stub_h_exists, stub_c_exists)
691 <- codeOutput dflags this_mod location foreign_stubs
695 hscInteractive :: (ModIface, ModDetails, CgGuts)
696 -> Comp (Maybe (InteractiveStatus, ModIface, ModDetails))
698 hscInteractive (iface, details, cgguts)
699 = do hsc_env <- gets compHscEnv
700 mod_summary <- gets compModSummary
702 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
703 -- From now on, we just use the bits we need.
704 cg_module = this_mod,
705 cg_binds = core_binds,
707 cg_foreign = foreign_stubs,
708 cg_modBreaks = mod_breaks } = cgguts
709 dflags = hsc_dflags hsc_env
710 location = ms_location mod_summary
711 data_tycons = filter isDataTyCon tycons
712 -- cg_tycons includes newtypes, for the benefit of External Core,
713 -- but we don't generate any code for newtypes
716 -- PREPARE FOR CODE GENERATION
717 -- Do saturation and convert to A-normal form
718 prepd_binds <- {-# SCC "CorePrep" #-}
719 corePrepPgm dflags core_binds data_tycons ;
720 ----------------- Generate byte code ------------------
721 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
722 ------------------ Create f-x-dynamic C-side stuff ---
723 (_istub_h_exists, istub_c_exists)
724 <- outputForeignStubs dflags this_mod location foreign_stubs
725 return (Just (InteractiveRecomp istub_c_exists comp_bc mod_breaks, iface, details))
727 hscInteractive _ = panic "GHC not compiled with interpreter"
730 ------------------------------
732 hscCmmFile :: DynFlags -> FilePath -> IO Bool
733 hscCmmFile dflags filename = do
734 maybe_cmm <- parseCmmFile dflags filename
736 Nothing -> return False
738 cmms <- optionallyConvertAndOrCPS dflags [cmm]
739 rawCmms <- cmmToRawCmm cmms
740 codeOutput dflags no_mod no_loc NoStubs [] rawCmms
743 no_mod = panic "hscCmmFile: no_mod"
744 no_loc = ModLocation{ ml_hs_file = Just filename,
745 ml_hi_file = panic "hscCmmFile: no hi file",
746 ml_obj_file = panic "hscCmmFile: no obj file" }
748 optionallyConvertAndOrCPS :: DynFlags -> [Cmm] -> IO [Cmm]
749 optionallyConvertAndOrCPS dflags cmms =
750 do -------- Optionally convert to and from zipper ------
751 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
752 then mapM (testCmmConversion dflags) cmms
754 --------- Optionally convert to CPS (MDA) -----------
755 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
756 dopt Opt_RunCPSZ dflags
757 then cmmCPS dflags cmms
762 testCmmConversion :: DynFlags -> Cmm -> IO Cmm
763 testCmmConversion dflags cmm =
764 do showPass dflags "CmmToCmm"
765 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
766 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
767 us <- mkSplitUniqSupply 'C'
768 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
769 let cvtm = do g <- cmmToZgraph cmm
771 let zgraph = initUs_ us cvtm
772 cps_zgraph <- protoCmmCPSZ dflags zgraph
773 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
774 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
775 showPass dflags "Convert from Z back to Cmm"
776 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
777 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
779 -- return cmm -- don't use the conversion
781 myParseModule :: DynFlags -> FilePath -> Maybe StringBuffer
782 -> IO (Either ErrMsg (Located (HsModule RdrName)))
783 myParseModule dflags src_filename maybe_src_buf
784 = -------------------------- Parser ----------------
785 showPass dflags "Parser" >>
786 {-# SCC "Parser" #-} do
788 -- sometimes we already have the buffer in memory, perhaps
789 -- because we needed to parse the imports out of it, or get the
791 buf <- case maybe_src_buf of
793 Nothing -> hGetStringBuffer src_filename
795 let loc = mkSrcLoc (mkFastString src_filename) 1 0
797 case unP parseModule (mkPState buf loc dflags) of {
799 PFailed span err -> return (Left (mkPlainErrMsg span err));
801 POk pst rdr_module -> do {
803 let {ms = getMessages pst};
804 printErrorsAndWarnings dflags ms;
805 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
807 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
809 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
810 (ppSourceStats False rdr_module) ;
812 return (Right rdr_module)
813 -- ToDo: free the string buffer later.
817 myCoreToStg :: DynFlags -> Module -> [CoreBind]
818 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
819 , CollectedCCs) -- cost centre info (declared and used)
821 myCoreToStg dflags this_mod prepd_binds
823 stg_binds <- {-# SCC "Core2Stg" #-}
824 coreToStg (thisPackage dflags) prepd_binds
826 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
827 stg2stg dflags this_mod stg_binds
829 return (stg_binds2, cost_centre_info)
833 %************************************************************************
835 \subsection{Compiling a do-statement}
837 %************************************************************************
839 When the UnlinkedBCOExpr is linked you get an HValue of type
841 When you run it you get a list of HValues that should be
842 the same length as the list of names; add them to the ClosureEnv.
844 A naked expression returns a singleton Name [it].
846 What you type The IO [HValue] that hscStmt returns
847 ------------- ------------------------------------
848 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
851 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
854 expr (of IO type) ==> expr >>= \ v -> return [v]
855 [NB: result not printed] bindings: [it]
858 expr (of non-IO type,
859 result showable) ==> let v = expr in print v >> return [v]
862 expr (of non-IO type,
863 result not showable) ==> error
867 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
869 -> String -- The statement
870 -> IO (Maybe ([Id], HValue))
873 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
874 ; case maybe_stmt of {
875 Nothing -> return Nothing ; -- Parse error
876 Just Nothing -> return Nothing ; -- Empty line
877 Just (Just parsed_stmt) -> do { -- The real stuff
879 -- Rename and typecheck it
880 let icontext = hsc_IC hsc_env
881 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
883 ; case maybe_tc_result of {
884 Nothing -> return Nothing ;
885 Just (ids, tc_expr) -> do {
888 ; let rdr_env = ic_rn_gbl_env icontext
889 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
890 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
892 ; case mb_ds_expr of {
893 Nothing -> return Nothing ;
896 -- Then desugar, code gen, and link it
897 ; let src_span = srcLocSpan interactiveSrcLoc
898 ; hval <- compileExpr hsc_env src_span ds_expr
900 ; return (Just (ids, hval))
903 hscTcExpr -- Typecheck an expression (but don't run it)
905 -> String -- The expression
908 hscTcExpr hsc_env expr
909 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
910 ; let icontext = hsc_IC hsc_env
911 ; case maybe_stmt of {
912 Nothing -> return Nothing ; -- Parse error
913 Just (Just (L _ (ExprStmt expr _ _)))
914 -> tcRnExpr hsc_env icontext expr ;
915 Just _ -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
919 hscKcType -- Find the kind of a type
921 -> String -- The type
924 hscKcType hsc_env str
925 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
926 ; let icontext = hsc_IC hsc_env
927 ; case maybe_type of {
928 Just ty -> tcRnType hsc_env icontext ty ;
929 Nothing -> return Nothing } }
935 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
936 hscParseStmt = hscParseThing parseStmt
938 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
939 hscParseType = hscParseThing parseType
942 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
943 hscParseIdentifier = hscParseThing parseIdentifier
945 hscParseThing :: Outputable thing
947 -> DynFlags -> String
949 -- Nothing => Parse error (message already printed)
951 hscParseThing parser dflags str
952 = showPass dflags "Parser" >>
953 {-# SCC "Parser" #-} do
955 buf <- stringToStringBuffer str
957 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
959 case unP parser (mkPState buf loc dflags) of {
961 PFailed span err -> do { printError span err;
964 POk pst thing -> do {
966 let {ms = getMessages pst};
967 printErrorsAndWarnings dflags ms;
968 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
970 --ToDo: can't free the string buffer until we've finished this
971 -- compilation sweep and all the identifiers have gone away.
972 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
977 %************************************************************************
979 Desugar, simplify, convert to bytecode, and link an expression
981 %************************************************************************
985 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
987 compileExpr hsc_env srcspan ds_expr
988 = do { let { dflags = hsc_dflags hsc_env ;
989 lint_on = dopt Opt_DoCoreLinting dflags }
992 ; flat_expr <- flattenExpr hsc_env ds_expr
995 ; simpl_expr <- simplifyExpr dflags flat_expr
997 -- Tidy it (temporary, until coreSat does cloning)
998 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
1000 -- Prepare for codegen
1001 ; prepd_expr <- corePrepExpr dflags tidy_expr
1003 -- Lint if necessary
1004 -- ToDo: improve SrcLoc
1006 let ictxt = hsc_IC hsc_env
1007 tyvars = varSetElems (ic_tyvars ictxt)
1009 case lintUnfolding noSrcLoc tyvars prepd_expr of
1010 Just err -> pprPanic "compileExpr" err
1011 Nothing -> return ()
1016 ; bcos <- coreExprToBCOs dflags prepd_expr
1019 ; hval <- linkExpr hsc_env srcspan bcos
1027 %************************************************************************
1029 Statistics on reading interfaces
1031 %************************************************************************
1034 dumpIfaceStats :: HscEnv -> IO ()
1035 dumpIfaceStats hsc_env
1036 = do { eps <- readIORef (hsc_EPS hsc_env)
1037 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1038 "Interface statistics"
1041 dflags = hsc_dflags hsc_env
1042 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1043 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1046 %************************************************************************
1048 Progress Messages: Module i of n
1050 %************************************************************************
1053 showModuleIndex :: Maybe (Int, Int) -> String
1054 showModuleIndex Nothing = ""
1055 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1059 padded = replicate (length n_str - length i_str) ' ' ++ i_str