2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
9 ( newHscEnv, hscCmmFile
13 , hscNormalIface, hscWriteIface, hscOneShot
16 , hscStmt, hscTcExpr, hscKcType
19 , hscCompileOneShot -- :: Compiler HscStatus
20 , hscCompileBatch -- :: Compiler (HscStatus, ModIface, ModDetails)
21 , hscCompileNothing -- :: Compiler (HscStatus, ModIface, ModDetails)
22 , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
24 , InteractiveStatus (..)
29 , typecheckRenameModule
36 import CodeOutput ( outputForeignStubs )
37 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
38 import Linker ( HValue, linkExpr )
39 import CoreTidy ( tidyExpr )
40 import CorePrep ( corePrepExpr )
41 import Desugar ( deSugarExpr )
42 import SimplCore ( simplifyExpr )
43 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
45 import PrelNames ( iNTERACTIVE )
46 import {- Kind parts of -} Type ( Kind )
47 import CoreLint ( lintUnfolding )
48 import DsMeta ( templateHaskellNames )
49 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan )
51 import VarEnv ( emptyTidyEnv )
55 import Module ( emptyModuleEnv, ModLocation(..), Module )
59 import SrcLoc ( Located(..) )
63 import SrcLoc ( mkSrcLoc )
64 import TcRnDriver ( tcRnModule )
65 import TcIface ( typecheckIface )
66 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
67 import IfaceEnv ( initNameCache )
68 import LoadIface ( ifaceStats, initExternalPackageState )
69 import PrelInfo ( wiredInThings, basicKnownKeyNames )
71 import Desugar ( deSugar )
72 import SimplCore ( core2core )
74 import CorePrep ( corePrepPgm )
75 import CoreToStg ( coreToStg )
78 import TyCon ( isDataTyCon )
79 import Name ( Name, NamedThing(..) )
80 import SimplStg ( stg2stg )
81 import CodeGen ( codeGen )
83 import CmmParse ( parseCmmFile )
87 import OptimizationFuel ( initOptFuelState )
91 import CodeOutput ( codeOutput )
92 import NameEnv ( emptyNameEnv )
96 import UniqSupply ( mkSplitUniqSupply )
99 import HscStats ( ppSourceStats )
101 import MkExternalCore ( emitExternalCore )
103 import LazyUniqFM ( 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 ; optFuel <- initOptFuelState
129 ; return (HscEnv { hsc_dflags = dflags,
132 hsc_IC = emptyInteractiveContext,
133 hsc_HPT = emptyHomePackageTable,
138 hsc_OptFuel = optFuel,
139 hsc_global_rdr_env = emptyGlobalRdrEnv,
140 hsc_global_type_env = emptyNameEnv } ) }
143 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
144 -- where templateHaskellNames are defined
145 knownKeyNames = map getName wiredInThings
146 ++ basicKnownKeyNames
148 ++ templateHaskellNames
154 -- | parse a file, returning the abstract syntax
155 parseFile :: HscEnv -> ModSummary -> IO (Maybe (Located (HsModule RdrName)))
156 parseFile hsc_env mod_summary
158 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
161 -> do printBagOfErrors dflags (unitBag err)
164 -> return (Just rdr_module)
166 dflags = hsc_dflags hsc_env
167 hspp_file = ms_hspp_file mod_summary
168 hspp_buf = ms_hspp_buf mod_summary
170 -- | Rename and typecheck a module
171 typecheckModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
172 -> IO (Maybe TcGblEnv)
173 typecheckModule hsc_env mod_summary rdr_module
175 (tc_msgs, maybe_tc_result)
176 <- {-# SCC "Typecheck-Rename" #-}
177 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
178 printErrorsAndWarnings dflags tc_msgs
179 return maybe_tc_result
181 dflags = hsc_dflags hsc_env
184 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
185 Maybe (HsDoc Name), HaddockModInfo Name))
187 -- | Rename and typecheck a module, additinoally returning the renamed syntax
188 typecheckRenameModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
189 -> IO (Maybe (TcGblEnv, RenamedStuff))
190 typecheckRenameModule hsc_env mod_summary rdr_module
192 (tc_msgs, maybe_tc_result)
193 <- {-# SCC "Typecheck-Rename" #-}
194 tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
195 printErrorsAndWarnings dflags tc_msgs
196 case maybe_tc_result of
197 Nothing -> return Nothing
199 let rn_info = do decl <- tcg_rn_decls tc_result
200 imports <- tcg_rn_imports tc_result
201 let exports = tcg_rn_exports tc_result
202 let doc = tcg_doc tc_result
203 let hmi = tcg_hmi tc_result
204 return (decl,imports,exports,doc,hmi)
205 return (Just (tc_result, rn_info))
207 dflags = hsc_dflags hsc_env
209 -- | Convert a typechecked module to Core
210 deSugarModule :: HscEnv -> ModSummary -> TcGblEnv -> IO (Maybe ModGuts)
211 deSugarModule hsc_env mod_summary tc_result
212 = deSugar hsc_env (ms_location mod_summary) tc_result
214 -- | Make a 'ModIface' from the results of typechecking. Used when
215 -- not optimising, and the interface doesn't need to contain any
216 -- unfoldings or other cross-module optimisation info.
217 -- ToDo: the old interface is only needed to get the version numbers,
218 -- we should use fingerprint versions instead.
219 makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
220 -> IO (ModIface,Bool)
221 makeSimpleIface hsc_env maybe_old_iface tc_result details = do
222 mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
224 -- | Make a 'ModDetails' from the results of typechecking. Used when
225 -- typechecking only, as opposed to full compilation.
226 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
227 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
229 -- deSugarModule :: HscEnv -> TcGblEnv -> IO Core
232 %************************************************************************
234 The main compiler pipeline
236 %************************************************************************
238 --------------------------------
239 The compilation proper
240 --------------------------------
243 It's the task of the compilation proper to compile Haskell, hs-boot and
244 core files to either byte-code, hard-code (C, asm, Java, ect) or to
245 nothing at all (the module is still parsed and type-checked. This
246 feature is mostly used by IDE's and the likes).
247 Compilation can happen in either 'one-shot', 'batch', 'nothing',
248 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
249 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
251 The modes are kept separate because of their different types and meanings.
252 In 'one-shot' mode, we're only compiling a single file and can therefore
253 discard the new ModIface and ModDetails. This is also the reason it only
254 targets hard-code; compiling to byte-code or nothing doesn't make sense
255 when we discard the result.
256 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
257 and ModDetails. 'Batch' mode doesn't target byte-code since that require
258 us to return the newly compiled byte-code.
259 'Nothing' mode has exactly the same type as 'batch' mode but they're still
260 kept separate. This is because compiling to nothing is fairly special: We
261 don't output any interface files, we don't run the simplifier and we don't
263 'Interactive' mode is similar to 'batch' mode except that we return the
264 compiled byte-code together with the ModIface and ModDetails.
266 Trying to compile a hs-boot file to byte-code will result in a run-time
267 error. This is the only thing that isn't caught by the type-system.
271 -- Status of a compilation to hard-code or nothing.
274 | HscRecomp Bool -- Has stub files.
275 -- This is a hack. We can't compile C files here
276 -- since it's done in DriverPipeline. For now we
277 -- just return True if we want the caller to compile
280 -- Status of a compilation to byte-code.
281 data InteractiveStatus
282 = InteractiveNoRecomp
283 | InteractiveRecomp Bool -- Same as HscStatus
288 -- I want Control.Monad.State! --Lemmih 03/07/2006
289 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
291 instance Monad Comp where
292 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
293 return a = Comp $ \s -> return (a,s)
296 evalComp :: Comp a -> CompState -> IO a
297 evalComp comp st = do (val,_st') <- runComp comp st
302 { compHscEnv :: HscEnv
303 , compModSummary :: ModSummary
304 , compOldIface :: Maybe ModIface
307 get :: Comp CompState
308 get = Comp $ \s -> return (s,s)
310 modify :: (CompState -> CompState) -> Comp ()
311 modify f = Comp $ \s -> return ((), f s)
313 gets :: (CompState -> a) -> Comp a
314 gets getter = do st <- get
317 liftIO :: IO a -> Comp a
318 liftIO ioA = Comp $ \s -> do a <- ioA
321 type NoRecomp result = ModIface -> Comp result
323 -- FIXME: The old interface and module index are only using in 'batch' and
324 -- 'interactive' mode. They should be removed from 'oneshot' mode.
325 type Compiler result = HscEnv
327 -> Bool -- True <=> source unchanged
328 -> Maybe ModIface -- Old interface, if available
329 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
332 --------------------------------------------------------------
334 --------------------------------------------------------------
336 -- Compile Haskell, boot and extCore in OneShot mode.
337 hscCompileOneShot :: Compiler HscStatus
339 = hscCompiler norecompOneShot oneShotMsg (genComp backend boot_backend)
341 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscOneShot
342 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >> return (Just (HscRecomp False))
344 -- Compile Haskell, boot and extCore in batch mode.
345 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
347 = hscCompiler norecompBatch batchMsg (genComp backend boot_backend)
349 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscBatch
350 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
352 -- Compile Haskell, extCore to bytecode.
353 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
354 hscCompileInteractive
355 = hscCompiler norecompInteractive batchMsg (genComp backend boot_backend)
357 backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
358 boot_backend _ = panic "hscCompileInteractive: HsBootFile"
360 -- Type-check Haskell and .hs-boot only (no external core)
361 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
363 = hscCompiler norecompBatch batchMsg comp
365 backend tc = hscSimpleIface tc >>= hscIgnoreIface >>= hscNothing
367 comp = do -- genComp doesn't fit here, because we want to omit
368 -- desugaring and for the backend to take a TcGblEnv
369 mod_summary <- gets compModSummary
370 case ms_hsc_src mod_summary of
371 ExtCoreFile -> panic "hscCompileNothing: cannot do external core"
373 mb_tc <- hscFileFrontEnd
375 Nothing -> return Nothing
376 Just tc_result -> backend tc_result
379 :: NoRecomp result -- No recomp necessary
380 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
381 -> Comp (Maybe result)
383 hscCompiler norecomp messenger recomp hsc_env mod_summary
384 source_unchanged mbOldIface mbModIndex
385 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
386 do (recomp_reqd, mbCheckedIface)
387 <- {-# SCC "checkOldIface" #-}
388 liftIO $ checkOldIface hsc_env mod_summary
389 source_unchanged mbOldIface
390 -- save the interface that comes back from checkOldIface.
391 -- In one-shot mode we don't have the old iface until this
392 -- point, when checkOldIface reads it from the disk.
393 modify (\s -> s{ compOldIface = mbCheckedIface })
394 case mbCheckedIface of
395 Just iface | not recomp_reqd
396 -> do messenger mbModIndex False
397 result <- norecomp iface
400 -> do messenger mbModIndex True
403 -- the usual way to build the Comp (Maybe result) to pass to hscCompiler
404 genComp :: (ModGuts -> Comp (Maybe a))
405 -> (TcGblEnv -> Comp (Maybe a))
407 genComp backend boot_backend = do
408 mod_summary <- gets compModSummary
409 case ms_hsc_src mod_summary of
411 panic "GHC does not currently support reading External Core files"
413 mb_tc <- hscFileFrontEnd
415 Nothing -> return Nothing
417 case ms_hsc_src mod_summary of
418 HsBootFile -> boot_backend tc_result
420 mb_guts <- hscDesugar tc_result
422 Nothing -> return Nothing
423 Just guts -> backend guts
425 --------------------------------------------------------------
427 --------------------------------------------------------------
429 norecompOneShot :: NoRecomp HscStatus
430 norecompOneShot _old_iface
431 = do hsc_env <- gets compHscEnv
433 dumpIfaceStats hsc_env
436 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
437 norecompBatch = norecompWorker HscNoRecomp False
439 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
440 norecompInteractive = norecompWorker InteractiveNoRecomp True
442 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
443 norecompWorker a _isInterp old_iface
444 = do hsc_env <- gets compHscEnv
446 new_details <- {-# SCC "tcRnIface" #-}
447 initIfaceCheck hsc_env $
448 typecheckIface old_iface
449 dumpIfaceStats hsc_env
450 return (a, old_iface, new_details)
452 --------------------------------------------------------------
453 -- Progress displayers.
454 --------------------------------------------------------------
456 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
457 oneShotMsg _mb_mod_index recomp
458 = do hsc_env <- gets compHscEnv
462 else compilationProgressMsg (hsc_dflags hsc_env) $
463 "compilation IS NOT required"
465 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
466 batchMsg mb_mod_index recomp
467 = do hsc_env <- gets compHscEnv
468 mod_summary <- gets compModSummary
469 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
470 (showModuleIndex mb_mod_index ++
471 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
474 then showMsg "Compiling "
475 else if verbosity (hsc_dflags hsc_env) >= 2
476 then showMsg "Skipping "
479 --------------------------------------------------------------
481 --------------------------------------------------------------
482 hscFileFrontEnd :: Comp (Maybe TcGblEnv)
484 do hsc_env <- gets compHscEnv
485 mod_summary <- gets compModSummary
490 let dflags = hsc_dflags hsc_env
491 hspp_file = ms_hspp_file mod_summary
492 hspp_buf = ms_hspp_buf mod_summary
493 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
496 -> do printBagOfErrors dflags (unitBag err)
500 -- RENAME and TYPECHECK
502 -> do (tc_msgs, maybe_tc_result)
503 <- {-# SCC "Typecheck-Rename" #-}
504 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
505 printErrorsAndWarnings dflags tc_msgs
506 return maybe_tc_result
508 --------------------------------------------------------------
510 --------------------------------------------------------------
512 hscDesugar :: TcGblEnv -> Comp (Maybe ModGuts)
514 = do mod_summary <- gets compModSummary
515 hsc_env <- gets compHscEnv
520 ds_result <- {-# SCC "DeSugar" #-}
521 deSugar hsc_env (ms_location mod_summary) tc_result
524 --------------------------------------------------------------
526 --------------------------------------------------------------
528 hscSimplify :: ModGuts -> Comp ModGuts
529 hscSimplify ds_result
530 = do hsc_env <- gets compHscEnv
535 simpl_result <- {-# SCC "Core2Core" #-}
536 core2core hsc_env ds_result
539 --------------------------------------------------------------
540 -- Interface generators
541 --------------------------------------------------------------
543 -- HACK: we return ModGuts even though we know it's not gonna be used.
544 -- We do this because the type signature needs to be identical
545 -- in structure to the type of 'hscNormalIface'.
546 hscSimpleIface :: TcGblEnv -> Comp (ModIface, Bool, ModDetails, TcGblEnv)
547 hscSimpleIface tc_result
548 = do hsc_env <- gets compHscEnv
549 maybe_old_iface <- gets compOldIface
551 details <- mkBootModDetailsTc hsc_env tc_result
552 (new_iface, no_change)
553 <- {-# SCC "MkFinalIface" #-}
554 mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
555 -- And the answer is ...
556 dumpIfaceStats hsc_env
557 return (new_iface, no_change, details, tc_result)
559 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
560 hscNormalIface simpl_result
561 = do hsc_env <- gets compHscEnv
562 _mod_summary <- gets compModSummary
563 maybe_old_iface <- gets compOldIface
568 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
569 tidyProgram hsc_env simpl_result
572 -- BUILD THE NEW ModIface and ModDetails
573 -- and emit external core if necessary
574 -- This has to happen *after* code gen so that the back-end
575 -- info has been set. Not yet clear if it matters waiting
576 -- until after code output
577 (new_iface, no_change)
578 <- {-# SCC "MkFinalIface" #-}
579 mkIface hsc_env (fmap mi_iface_hash maybe_old_iface)
581 -- Emit external core
582 -- This should definitely be here and not after CorePrep,
583 -- because CorePrep produces unqualified constructor wrapper declarations,
584 -- so its output isn't valid External Core (without some preprocessing).
585 emitExternalCore (hsc_dflags hsc_env) cg_guts
586 dumpIfaceStats hsc_env
589 -- Return the prepared code.
590 return (new_iface, no_change, details, cg_guts)
592 --------------------------------------------------------------
593 -- BackEnd combinators
594 --------------------------------------------------------------
596 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
597 hscWriteIface (iface, no_change, details, a)
598 = do mod_summary <- gets compModSummary
599 hsc_env <- gets compHscEnv
600 let dflags = hsc_dflags hsc_env
603 $ writeIfaceFile dflags (ms_location mod_summary) iface
604 return (iface, details, a)
606 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
607 hscIgnoreIface (iface, _no_change, details, a)
608 = return (iface, details, a)
610 -- Don't output any code.
611 hscNothing :: (ModIface, ModDetails, a) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
612 hscNothing (iface, details, _)
613 = return (Just (HscRecomp False, iface, details))
615 -- Generate code and return both the new ModIface and the ModDetails.
616 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
617 hscBatch (iface, details, cgguts)
618 = do hasStub <- hscCompile cgguts
619 return (Just (HscRecomp hasStub, iface, details))
621 -- Here we don't need the ModIface and ModDetails anymore.
622 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe HscStatus)
623 hscOneShot (_, _, cgguts)
624 = do hasStub <- hscCompile cgguts
625 return (Just (HscRecomp hasStub))
627 -- Compile to hard-code.
628 hscCompile :: CgGuts -> Comp Bool
630 = do hsc_env <- gets compHscEnv
631 mod_summary <- gets compModSummary
633 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
634 -- From now on, we just use the bits we need.
635 cg_module = this_mod,
636 cg_binds = core_binds,
638 cg_dir_imps = dir_imps,
639 cg_foreign = foreign_stubs,
640 cg_dep_pkgs = dependencies,
641 cg_hpc_info = hpc_info } = cgguts
642 dflags = hsc_dflags hsc_env
643 location = ms_location mod_summary
644 data_tycons = filter isDataTyCon tycons
645 -- cg_tycons includes newtypes, for the benefit of External Core,
646 -- but we don't generate any code for newtypes
649 -- PREPARE FOR CODE GENERATION
650 -- Do saturation and convert to A-normal form
651 prepd_binds <- {-# SCC "CorePrep" #-}
652 corePrepPgm dflags core_binds data_tycons ;
653 ----------------- Convert to STG ------------------
654 (stg_binds, cost_centre_info)
655 <- {-# SCC "CoreToStg" #-}
656 myCoreToStg dflags this_mod prepd_binds
657 ------------------ Code generation ------------------
658 cmms <- {-# SCC "CodeGen" #-}
659 codeGen dflags this_mod data_tycons
660 dir_imps cost_centre_info
662 --- Optionally run experimental Cmm transformations ---
663 cmms <- optionallyConvertAndOrCPS hsc_env cmms
664 -- ^ unless certain dflags are on, the identity function
665 ------------------ Code output -----------------------
666 rawcmms <- cmmToRawCmm cmms
667 (_stub_h_exists, stub_c_exists)
668 <- codeOutput dflags this_mod location foreign_stubs
672 hscInteractive :: (ModIface, ModDetails, CgGuts)
673 -> Comp (Maybe (InteractiveStatus, ModIface, ModDetails))
675 hscInteractive (iface, details, cgguts)
676 = do hsc_env <- gets compHscEnv
677 mod_summary <- gets compModSummary
679 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
680 -- From now on, we just use the bits we need.
681 cg_module = this_mod,
682 cg_binds = core_binds,
684 cg_foreign = foreign_stubs,
685 cg_modBreaks = mod_breaks } = cgguts
686 dflags = hsc_dflags hsc_env
687 location = ms_location mod_summary
688 data_tycons = filter isDataTyCon tycons
689 -- cg_tycons includes newtypes, for the benefit of External Core,
690 -- but we don't generate any code for newtypes
693 -- PREPARE FOR CODE GENERATION
694 -- Do saturation and convert to A-normal form
695 prepd_binds <- {-# SCC "CorePrep" #-}
696 corePrepPgm dflags core_binds data_tycons ;
697 ----------------- Generate byte code ------------------
698 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
699 ------------------ Create f-x-dynamic C-side stuff ---
700 (_istub_h_exists, istub_c_exists)
701 <- outputForeignStubs dflags this_mod location foreign_stubs
702 return (Just (InteractiveRecomp istub_c_exists comp_bc mod_breaks, iface, details))
704 hscInteractive _ = panic "GHC not compiled with interpreter"
707 ------------------------------
709 hscCmmFile :: HscEnv -> FilePath -> IO Bool
710 hscCmmFile hsc_env filename = do
711 dflags <- return $ hsc_dflags hsc_env
712 maybe_cmm <- parseCmmFile dflags filename
714 Nothing -> return False
716 cmms <- optionallyConvertAndOrCPS hsc_env [cmm]
717 rawCmms <- cmmToRawCmm cmms
718 codeOutput dflags no_mod no_loc NoStubs [] rawCmms
721 no_mod = panic "hscCmmFile: no_mod"
722 no_loc = ModLocation{ ml_hs_file = Just filename,
723 ml_hi_file = panic "hscCmmFile: no hi file",
724 ml_obj_file = panic "hscCmmFile: no obj file" }
726 optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
727 optionallyConvertAndOrCPS hsc_env cmms =
728 do let dflags = hsc_dflags hsc_env
729 -------- Optionally convert to and from zipper ------
730 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
731 then mapM (testCmmConversion hsc_env) cmms
733 --------- Optionally convert to CPS (MDA) -----------
734 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
735 dopt Opt_RunCPSZ dflags
736 then cmmCPS dflags cmms
741 testCmmConversion :: HscEnv -> Cmm -> IO Cmm
742 testCmmConversion hsc_env cmm =
743 do let dflags = hsc_dflags hsc_env
744 showPass dflags "CmmToCmm"
745 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
746 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
747 us <- mkSplitUniqSupply 'C'
748 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
749 let cvtm = do g <- cmmToZgraph cmm
751 let zgraph = initUs_ us cvtm
752 cps_zgraph <- protoCmmCPSZ hsc_env zgraph
753 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
754 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
755 showPass dflags "Convert from Z back to Cmm"
756 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
757 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
759 -- return cmm -- don't use the conversion
761 myParseModule :: DynFlags -> FilePath -> Maybe StringBuffer
762 -> IO (Either ErrMsg (Located (HsModule RdrName)))
763 myParseModule dflags src_filename maybe_src_buf
764 = -------------------------- Parser ----------------
765 showPass dflags "Parser" >>
766 {-# SCC "Parser" #-} do
768 -- sometimes we already have the buffer in memory, perhaps
769 -- because we needed to parse the imports out of it, or get the
771 buf <- case maybe_src_buf of
773 Nothing -> hGetStringBuffer src_filename
775 let loc = mkSrcLoc (mkFastString src_filename) 1 0
777 case unP parseModule (mkPState buf loc dflags) of {
779 PFailed span err -> return (Left (mkPlainErrMsg span err));
781 POk pst rdr_module -> do {
783 let {ms = getMessages pst};
784 printErrorsAndWarnings dflags ms;
785 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
787 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
789 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
790 (ppSourceStats False rdr_module) ;
792 return (Right rdr_module)
793 -- ToDo: free the string buffer later.
797 myCoreToStg :: DynFlags -> Module -> [CoreBind]
798 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
799 , CollectedCCs) -- cost centre info (declared and used)
801 myCoreToStg dflags this_mod prepd_binds
803 stg_binds <- {-# SCC "Core2Stg" #-}
804 coreToStg (thisPackage dflags) prepd_binds
806 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
807 stg2stg dflags this_mod stg_binds
809 return (stg_binds2, cost_centre_info)
813 %************************************************************************
815 \subsection{Compiling a do-statement}
817 %************************************************************************
819 When the UnlinkedBCOExpr is linked you get an HValue of type
821 When you run it you get a list of HValues that should be
822 the same length as the list of names; add them to the ClosureEnv.
824 A naked expression returns a singleton Name [it].
826 What you type The IO [HValue] that hscStmt returns
827 ------------- ------------------------------------
828 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
831 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
834 expr (of IO type) ==> expr >>= \ v -> return [v]
835 [NB: result not printed] bindings: [it]
838 expr (of non-IO type,
839 result showable) ==> let v = expr in print v >> return [v]
842 expr (of non-IO type,
843 result not showable) ==> error
847 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
849 -> String -- The statement
850 -> IO (Maybe ([Id], HValue))
853 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
854 ; case maybe_stmt of {
855 Nothing -> return Nothing ; -- Parse error
856 Just Nothing -> return Nothing ; -- Empty line
857 Just (Just parsed_stmt) -> do { -- The real stuff
859 -- Rename and typecheck it
860 let icontext = hsc_IC hsc_env
861 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
863 ; case maybe_tc_result of {
864 Nothing -> return Nothing ;
865 Just (ids, tc_expr) -> do {
868 ; let rdr_env = ic_rn_gbl_env icontext
869 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
870 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
872 ; case mb_ds_expr of {
873 Nothing -> return Nothing ;
876 -- Then desugar, code gen, and link it
877 ; let src_span = srcLocSpan interactiveSrcLoc
878 ; hval <- compileExpr hsc_env src_span ds_expr
880 ; return (Just (ids, hval))
883 hscTcExpr -- Typecheck an expression (but don't run it)
885 -> String -- The expression
888 hscTcExpr hsc_env expr
889 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
890 ; let icontext = hsc_IC hsc_env
891 ; case maybe_stmt of {
892 Nothing -> return Nothing ; -- Parse error
893 Just (Just (L _ (ExprStmt expr _ _)))
894 -> tcRnExpr hsc_env icontext expr ;
895 Just _ -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
899 hscKcType -- Find the kind of a type
901 -> String -- The type
904 hscKcType hsc_env str
905 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
906 ; let icontext = hsc_IC hsc_env
907 ; case maybe_type of {
908 Just ty -> tcRnType hsc_env icontext ty ;
909 Nothing -> return Nothing } }
915 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
916 hscParseStmt = hscParseThing parseStmt
918 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
919 hscParseType = hscParseThing parseType
922 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
923 hscParseIdentifier = hscParseThing parseIdentifier
925 hscParseThing :: Outputable thing
927 -> DynFlags -> String
929 -- Nothing => Parse error (message already printed)
931 hscParseThing parser dflags str
932 = showPass dflags "Parser" >>
933 {-# SCC "Parser" #-} do
935 buf <- stringToStringBuffer str
937 let loc = mkSrcLoc (fsLit "<interactive>") 1 0
939 case unP parser (mkPState buf loc dflags) of {
941 PFailed span err -> do { printError span err;
944 POk pst thing -> do {
946 let {ms = getMessages pst};
947 printErrorsAndWarnings dflags ms;
948 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
950 --ToDo: can't free the string buffer until we've finished this
951 -- compilation sweep and all the identifiers have gone away.
952 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
957 %************************************************************************
959 Desugar, simplify, convert to bytecode, and link an expression
961 %************************************************************************
965 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
967 compileExpr hsc_env srcspan ds_expr
968 = do { let { dflags = hsc_dflags hsc_env ;
969 lint_on = dopt Opt_DoCoreLinting dflags }
972 ; simpl_expr <- simplifyExpr dflags ds_expr
974 -- Tidy it (temporary, until coreSat does cloning)
975 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
977 -- Prepare for codegen
978 ; prepd_expr <- corePrepExpr dflags tidy_expr
981 -- ToDo: improve SrcLoc
983 let ictxt = hsc_IC hsc_env
984 tyvars = varSetElems (ic_tyvars ictxt)
986 case lintUnfolding noSrcLoc tyvars prepd_expr of
987 Just err -> pprPanic "compileExpr" err
993 ; bcos <- coreExprToBCOs dflags prepd_expr
996 ; hval <- linkExpr hsc_env srcspan bcos
1004 %************************************************************************
1006 Statistics on reading interfaces
1008 %************************************************************************
1011 dumpIfaceStats :: HscEnv -> IO ()
1012 dumpIfaceStats hsc_env
1013 = do { eps <- readIORef (hsc_EPS hsc_env)
1014 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1015 "Interface statistics"
1018 dflags = hsc_dflags hsc_env
1019 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1020 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1023 %************************************************************************
1025 Progress Messages: Module i of n
1027 %************************************************************************
1030 showModuleIndex :: Maybe (Int, Int) -> String
1031 showModuleIndex Nothing = ""
1032 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1036 padded = replicate (length n_str - length i_str) ' ' ++ i_str