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
35 #include "HsVersions.h"
38 import CodeOutput ( outputForeignStubs )
39 import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
40 import Linker ( HValue, linkExpr )
41 import CoreTidy ( tidyExpr )
42 import CorePrep ( corePrepExpr )
43 import Flattening ( flattenExpr )
44 import Desugar ( deSugarExpr )
45 import SimplCore ( simplifyExpr )
46 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
48 import PrelNames ( iNTERACTIVE )
49 import {- Kind parts of -} Type ( Kind )
50 import CoreLint ( lintUnfolding )
51 import DsMeta ( templateHaskellNames )
52 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan )
54 import VarEnv ( emptyTidyEnv )
58 import Module ( emptyModuleEnv, ModLocation(..), Module )
62 import SrcLoc ( Located(..) )
66 import SrcLoc ( mkSrcLoc )
67 import TcRnDriver ( tcRnModule )
68 import TcIface ( typecheckIface )
69 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
70 import IfaceEnv ( initNameCache )
71 import LoadIface ( ifaceStats, initExternalPackageState )
72 import PrelInfo ( wiredInThings, basicKnownKeyNames )
74 import Desugar ( deSugar )
75 import SimplCore ( core2core )
77 import CorePrep ( corePrepPgm )
78 import CoreToStg ( coreToStg )
81 import TyCon ( isDataTyCon )
82 import Name ( Name, NamedThing(..) )
83 import SimplStg ( stg2stg )
84 import CodeGen ( codeGen )
86 import CmmParse ( parseCmmFile )
93 import CodeOutput ( codeOutput )
94 import NameEnv ( emptyNameEnv )
98 import UniqSupply ( mkSplitUniqSupply )
101 import HscStats ( ppSourceStats )
103 import MkExternalCore ( emitExternalCore )
105 import LazyUniqFM ( emptyUFM )
106 import UniqSupply ( initUs_ )
107 import Bag ( unitBag )
116 %************************************************************************
120 %************************************************************************
123 newHscEnv :: DynFlags -> IO HscEnv
125 = do { eps_var <- newIORef initExternalPackageState
126 ; us <- mkSplitUniqSupply 'r'
127 ; nc_var <- newIORef (initNameCache us knownKeyNames)
128 ; fc_var <- newIORef emptyUFM
129 ; mlc_var <- newIORef emptyModuleEnv
130 ; return (HscEnv { hsc_dflags = dflags,
133 hsc_IC = emptyInteractiveContext,
134 hsc_HPT = emptyHomePackageTable,
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 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 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 maybe_old_iface details simpl_result
580 -- Emit external core
581 emitExternalCore (hsc_dflags hsc_env) (availsToNameSet (mg_exports simpl_result)) cg_guts -- Move this? --Lemmih 03/07/2006
582 dumpIfaceStats hsc_env
585 -- Return the prepared code.
586 return (new_iface, no_change, details, cg_guts)
588 --------------------------------------------------------------
589 -- BackEnd combinators
590 --------------------------------------------------------------
592 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
593 hscWriteIface (iface, no_change, details, a)
594 = do mod_summary <- gets compModSummary
595 hsc_env <- gets compHscEnv
596 let dflags = hsc_dflags hsc_env
599 $ writeIfaceFile dflags (ms_location mod_summary) iface
600 return (iface, details, a)
602 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
603 hscIgnoreIface (iface, _no_change, details, a)
604 = return (iface, details, a)
606 -- Don't output any code.
607 hscNothing :: (ModIface, ModDetails, a) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
608 hscNothing (iface, details, _)
609 = return (Just (HscRecomp False, iface, details))
611 -- Generate code and return both the new ModIface and the ModDetails.
612 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
613 hscBatch (iface, details, cgguts)
614 = do hasStub <- hscCompile cgguts
615 return (Just (HscRecomp hasStub, iface, details))
617 -- Here we don't need the ModIface and ModDetails anymore.
618 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe HscStatus)
619 hscOneShot (_, _, cgguts)
620 = do hasStub <- hscCompile cgguts
621 return (Just (HscRecomp hasStub))
623 -- Compile to hard-code.
624 hscCompile :: CgGuts -> Comp Bool
626 = do hsc_env <- gets compHscEnv
627 mod_summary <- gets compModSummary
629 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
630 -- From now on, we just use the bits we need.
631 cg_module = this_mod,
632 cg_binds = core_binds,
634 cg_dir_imps = dir_imps,
635 cg_foreign = foreign_stubs,
636 cg_dep_pkgs = dependencies,
637 cg_hpc_info = hpc_info } = cgguts
638 dflags = hsc_dflags hsc_env
639 location = ms_location mod_summary
640 data_tycons = filter isDataTyCon tycons
641 -- cg_tycons includes newtypes, for the benefit of External Core,
642 -- but we don't generate any code for newtypes
645 -- PREPARE FOR CODE GENERATION
646 -- Do saturation and convert to A-normal form
647 prepd_binds <- {-# SCC "CorePrep" #-}
648 corePrepPgm dflags core_binds data_tycons ;
649 ----------------- Convert to STG ------------------
650 (stg_binds, cost_centre_info)
651 <- {-# SCC "CoreToStg" #-}
652 myCoreToStg dflags this_mod prepd_binds
653 ------------------ Code generation ------------------
654 cmms <- {-# SCC "CodeGen" #-}
655 codeGen dflags this_mod data_tycons
656 dir_imps cost_centre_info
658 --- Optionally run experimental Cmm transformations ---
659 cmms <- optionallyConvertAndOrCPS dflags cmms
660 -- ^ unless certain dflags are on, the identity function
661 ------------------ Code output -----------------------
662 rawcmms <- cmmToRawCmm cmms
663 (_stub_h_exists, stub_c_exists)
664 <- codeOutput dflags this_mod location foreign_stubs
668 hscInteractive :: (ModIface, ModDetails, CgGuts)
669 -> Comp (Maybe (InteractiveStatus, ModIface, ModDetails))
671 hscInteractive (iface, details, cgguts)
672 = do hsc_env <- gets compHscEnv
673 mod_summary <- gets compModSummary
675 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
676 -- From now on, we just use the bits we need.
677 cg_module = this_mod,
678 cg_binds = core_binds,
680 cg_foreign = foreign_stubs,
681 cg_modBreaks = mod_breaks } = cgguts
682 dflags = hsc_dflags hsc_env
683 location = ms_location mod_summary
684 data_tycons = filter isDataTyCon tycons
685 -- cg_tycons includes newtypes, for the benefit of External Core,
686 -- but we don't generate any code for newtypes
689 -- PREPARE FOR CODE GENERATION
690 -- Do saturation and convert to A-normal form
691 prepd_binds <- {-# SCC "CorePrep" #-}
692 corePrepPgm dflags core_binds data_tycons ;
693 ----------------- Generate byte code ------------------
694 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
695 ------------------ Create f-x-dynamic C-side stuff ---
696 (_istub_h_exists, istub_c_exists)
697 <- outputForeignStubs dflags this_mod location foreign_stubs
698 return (Just (InteractiveRecomp istub_c_exists comp_bc mod_breaks, iface, details))
700 hscInteractive _ = panic "GHC not compiled with interpreter"
703 ------------------------------
705 hscCmmFile :: DynFlags -> FilePath -> IO Bool
706 hscCmmFile dflags filename = do
707 maybe_cmm <- parseCmmFile dflags filename
709 Nothing -> return False
711 cmms <- optionallyConvertAndOrCPS dflags [cmm]
712 rawCmms <- cmmToRawCmm cmms
713 codeOutput dflags no_mod no_loc NoStubs [] rawCmms
716 no_mod = panic "hscCmmFile: no_mod"
717 no_loc = ModLocation{ ml_hs_file = Just filename,
718 ml_hi_file = panic "hscCmmFile: no hi file",
719 ml_obj_file = panic "hscCmmFile: no obj file" }
721 optionallyConvertAndOrCPS :: DynFlags -> [Cmm] -> IO [Cmm]
722 optionallyConvertAndOrCPS dflags cmms =
723 do -------- Optionally convert to and from zipper ------
724 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
725 then mapM (testCmmConversion dflags) cmms
727 --------- Optionally convert to CPS (MDA) -----------
728 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
729 dopt Opt_RunCPSZ dflags
730 then cmmCPS dflags cmms
735 testCmmConversion :: DynFlags -> Cmm -> IO Cmm
736 testCmmConversion dflags cmm =
737 do showPass dflags "CmmToCmm"
738 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
739 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
740 us <- mkSplitUniqSupply 'C'
741 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
742 let cvtm = do g <- cmmToZgraph cmm
744 let zgraph = initUs_ us cvtm
745 cps_zgraph <- protoCmmCPSZ dflags zgraph
746 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
747 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
748 showPass dflags "Convert from Z back to Cmm"
749 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
750 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
752 -- return cmm -- don't use the conversion
754 myParseModule :: DynFlags -> FilePath -> Maybe StringBuffer
755 -> IO (Either ErrMsg (Located (HsModule RdrName)))
756 myParseModule dflags src_filename maybe_src_buf
757 = -------------------------- Parser ----------------
758 showPass dflags "Parser" >>
759 {-# SCC "Parser" #-} do
761 -- sometimes we already have the buffer in memory, perhaps
762 -- because we needed to parse the imports out of it, or get the
764 buf <- case maybe_src_buf of
766 Nothing -> hGetStringBuffer src_filename
768 let loc = mkSrcLoc (mkFastString src_filename) 1 0
770 case unP parseModule (mkPState buf loc dflags) of {
772 PFailed span err -> return (Left (mkPlainErrMsg span err));
774 POk pst rdr_module -> do {
776 let {ms = getMessages pst};
777 printErrorsAndWarnings dflags ms;
778 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
780 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
782 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
783 (ppSourceStats False rdr_module) ;
785 return (Right rdr_module)
786 -- ToDo: free the string buffer later.
790 myCoreToStg :: DynFlags -> Module -> [CoreBind]
791 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
792 , CollectedCCs) -- cost centre info (declared and used)
794 myCoreToStg dflags this_mod prepd_binds
796 stg_binds <- {-# SCC "Core2Stg" #-}
797 coreToStg (thisPackage dflags) prepd_binds
799 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
800 stg2stg dflags this_mod stg_binds
802 return (stg_binds2, cost_centre_info)
806 %************************************************************************
808 \subsection{Compiling a do-statement}
810 %************************************************************************
812 When the UnlinkedBCOExpr is linked you get an HValue of type
814 When you run it you get a list of HValues that should be
815 the same length as the list of names; add them to the ClosureEnv.
817 A naked expression returns a singleton Name [it].
819 What you type The IO [HValue] that hscStmt returns
820 ------------- ------------------------------------
821 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
824 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
827 expr (of IO type) ==> expr >>= \ v -> return [v]
828 [NB: result not printed] bindings: [it]
831 expr (of non-IO type,
832 result showable) ==> let v = expr in print v >> return [v]
835 expr (of non-IO type,
836 result not showable) ==> error
840 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
842 -> String -- The statement
843 -> IO (Maybe ([Id], HValue))
846 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
847 ; case maybe_stmt of {
848 Nothing -> return Nothing ; -- Parse error
849 Just Nothing -> return Nothing ; -- Empty line
850 Just (Just parsed_stmt) -> do { -- The real stuff
852 -- Rename and typecheck it
853 let icontext = hsc_IC hsc_env
854 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
856 ; case maybe_tc_result of {
857 Nothing -> return Nothing ;
858 Just (ids, tc_expr) -> do {
861 ; let rdr_env = ic_rn_gbl_env icontext
862 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
863 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
865 ; case mb_ds_expr of {
866 Nothing -> return Nothing ;
869 -- Then desugar, code gen, and link it
870 ; let src_span = srcLocSpan interactiveSrcLoc
871 ; hval <- compileExpr hsc_env src_span ds_expr
873 ; return (Just (ids, hval))
876 hscTcExpr -- Typecheck an expression (but don't run it)
878 -> String -- The expression
881 hscTcExpr hsc_env expr
882 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
883 ; let icontext = hsc_IC hsc_env
884 ; case maybe_stmt of {
885 Nothing -> return Nothing ; -- Parse error
886 Just (Just (L _ (ExprStmt expr _ _)))
887 -> tcRnExpr hsc_env icontext expr ;
888 Just _ -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
892 hscKcType -- Find the kind of a type
894 -> String -- The type
897 hscKcType hsc_env str
898 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
899 ; let icontext = hsc_IC hsc_env
900 ; case maybe_type of {
901 Just ty -> tcRnType hsc_env icontext ty ;
902 Nothing -> return Nothing } }
908 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
909 hscParseStmt = hscParseThing parseStmt
911 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
912 hscParseType = hscParseThing parseType
915 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
916 hscParseIdentifier = hscParseThing parseIdentifier
918 hscParseThing :: Outputable thing
920 -> DynFlags -> String
922 -- Nothing => Parse error (message already printed)
924 hscParseThing parser dflags str
925 = showPass dflags "Parser" >>
926 {-# SCC "Parser" #-} do
928 buf <- stringToStringBuffer str
930 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
932 case unP parser (mkPState buf loc dflags) of {
934 PFailed span err -> do { printError span err;
937 POk pst thing -> do {
939 let {ms = getMessages pst};
940 printErrorsAndWarnings dflags ms;
941 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
943 --ToDo: can't free the string buffer until we've finished this
944 -- compilation sweep and all the identifiers have gone away.
945 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
950 %************************************************************************
952 Desugar, simplify, convert to bytecode, and link an expression
954 %************************************************************************
958 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
960 compileExpr hsc_env srcspan ds_expr
961 = do { let { dflags = hsc_dflags hsc_env ;
962 lint_on = dopt Opt_DoCoreLinting dflags }
965 ; flat_expr <- flattenExpr hsc_env ds_expr
968 ; simpl_expr <- simplifyExpr dflags flat_expr
970 -- Tidy it (temporary, until coreSat does cloning)
971 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
973 -- Prepare for codegen
974 ; prepd_expr <- corePrepExpr dflags tidy_expr
977 -- ToDo: improve SrcLoc
979 let ictxt = hsc_IC hsc_env
980 tyvars = varSetElems (ic_tyvars ictxt)
982 case lintUnfolding noSrcLoc tyvars prepd_expr of
983 Just err -> pprPanic "compileExpr" err
989 ; bcos <- coreExprToBCOs dflags prepd_expr
992 ; hval <- linkExpr hsc_env srcspan bcos
1000 %************************************************************************
1002 Statistics on reading interfaces
1004 %************************************************************************
1007 dumpIfaceStats :: HscEnv -> IO ()
1008 dumpIfaceStats hsc_env
1009 = do { eps <- readIORef (hsc_EPS hsc_env)
1010 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1011 "Interface statistics"
1014 dflags = hsc_dflags hsc_env
1015 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1016 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1019 %************************************************************************
1021 Progress Messages: Module i of n
1023 %************************************************************************
1026 showModuleIndex :: Maybe (Int, Int) -> String
1027 showModuleIndex Nothing = ""
1028 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1032 padded = replicate (length n_str - length i_str) ' ' ++ i_str