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 )
90 import CodeOutput ( codeOutput )
91 import NameEnv ( emptyNameEnv )
95 import UniqSupply ( mkSplitUniqSupply )
98 import HscStats ( ppSourceStats )
100 import MkExternalCore ( emitExternalCore )
102 import LazyUniqFM ( emptyUFM )
103 import UniqSupply ( initUs_ )
104 import Bag ( unitBag )
113 %************************************************************************
117 %************************************************************************
120 newHscEnv :: DynFlags -> IO HscEnv
122 = do { eps_var <- newIORef initExternalPackageState
123 ; us <- mkSplitUniqSupply 'r'
124 ; nc_var <- newIORef (initNameCache us knownKeyNames)
125 ; fc_var <- newIORef emptyUFM
126 ; mlc_var <- newIORef emptyModuleEnv
127 ; return (HscEnv { hsc_dflags = dflags,
130 hsc_IC = emptyInteractiveContext,
131 hsc_HPT = emptyHomePackageTable,
136 hsc_global_rdr_env = emptyGlobalRdrEnv,
137 hsc_global_type_env = emptyNameEnv } ) }
140 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
141 -- where templateHaskellNames are defined
142 knownKeyNames = map getName wiredInThings
143 ++ basicKnownKeyNames
145 ++ templateHaskellNames
151 -- | parse a file, returning the abstract syntax
152 parseFile :: HscEnv -> ModSummary -> IO (Maybe (Located (HsModule RdrName)))
153 parseFile hsc_env mod_summary
155 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
158 -> do printBagOfErrors dflags (unitBag err)
161 -> return (Just rdr_module)
163 dflags = hsc_dflags hsc_env
164 hspp_file = ms_hspp_file mod_summary
165 hspp_buf = ms_hspp_buf mod_summary
167 -- | Rename and typecheck a module
168 typecheckModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
169 -> IO (Maybe TcGblEnv)
170 typecheckModule hsc_env mod_summary rdr_module
172 (tc_msgs, maybe_tc_result)
173 <- {-# SCC "Typecheck-Rename" #-}
174 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
175 printErrorsAndWarnings dflags tc_msgs
176 return maybe_tc_result
178 dflags = hsc_dflags hsc_env
181 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
182 Maybe (HsDoc Name), HaddockModInfo Name))
184 -- | Rename and typecheck a module, additinoally returning the renamed syntax
185 typecheckRenameModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
186 -> IO (Maybe (TcGblEnv, RenamedStuff))
187 typecheckRenameModule hsc_env mod_summary rdr_module
189 (tc_msgs, maybe_tc_result)
190 <- {-# SCC "Typecheck-Rename" #-}
191 tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
192 printErrorsAndWarnings dflags tc_msgs
193 case maybe_tc_result of
194 Nothing -> return Nothing
196 let rn_info = do decl <- tcg_rn_decls tc_result
197 imports <- tcg_rn_imports tc_result
198 let exports = tcg_rn_exports tc_result
199 let doc = tcg_doc tc_result
200 let hmi = tcg_hmi tc_result
201 return (decl,imports,exports,doc,hmi)
202 return (Just (tc_result, rn_info))
204 dflags = hsc_dflags hsc_env
206 -- | Convert a typechecked module to Core
207 deSugarModule :: HscEnv -> ModSummary -> TcGblEnv -> IO (Maybe ModGuts)
208 deSugarModule hsc_env mod_summary tc_result
209 = deSugar hsc_env (ms_location mod_summary) tc_result
211 -- | Make a 'ModIface' from the results of typechecking. Used when
212 -- not optimising, and the interface doesn't need to contain any
213 -- unfoldings or other cross-module optimisation info.
214 -- ToDo: the old interface is only needed to get the version numbers,
215 -- we should use fingerprint versions instead.
216 makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
217 -> IO (ModIface,Bool)
218 makeSimpleIface hsc_env maybe_old_iface tc_result details = do
219 mkIfaceTc hsc_env maybe_old_iface details tc_result
221 -- | Make a 'ModDetails' from the results of typechecking. Used when
222 -- typechecking only, as opposed to full compilation.
223 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
224 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
226 -- deSugarModule :: HscEnv -> TcGblEnv -> IO Core
229 %************************************************************************
231 The main compiler pipeline
233 %************************************************************************
235 --------------------------------
236 The compilation proper
237 --------------------------------
240 It's the task of the compilation proper to compile Haskell, hs-boot and
241 core files to either byte-code, hard-code (C, asm, Java, ect) or to
242 nothing at all (the module is still parsed and type-checked. This
243 feature is mostly used by IDE's and the likes).
244 Compilation can happen in either 'one-shot', 'batch', 'nothing',
245 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
246 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
248 The modes are kept separate because of their different types and meanings.
249 In 'one-shot' mode, we're only compiling a single file and can therefore
250 discard the new ModIface and ModDetails. This is also the reason it only
251 targets hard-code; compiling to byte-code or nothing doesn't make sense
252 when we discard the result.
253 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
254 and ModDetails. 'Batch' mode doesn't target byte-code since that require
255 us to return the newly compiled byte-code.
256 'Nothing' mode has exactly the same type as 'batch' mode but they're still
257 kept separate. This is because compiling to nothing is fairly special: We
258 don't output any interface files, we don't run the simplifier and we don't
260 'Interactive' mode is similar to 'batch' mode except that we return the
261 compiled byte-code together with the ModIface and ModDetails.
263 Trying to compile a hs-boot file to byte-code will result in a run-time
264 error. This is the only thing that isn't caught by the type-system.
268 -- Status of a compilation to hard-code or nothing.
271 | HscRecomp Bool -- Has stub files.
272 -- This is a hack. We can't compile C files here
273 -- since it's done in DriverPipeline. For now we
274 -- just return True if we want the caller to compile
277 -- Status of a compilation to byte-code.
278 data InteractiveStatus
279 = InteractiveNoRecomp
280 | InteractiveRecomp Bool -- Same as HscStatus
285 -- I want Control.Monad.State! --Lemmih 03/07/2006
286 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
288 instance Monad Comp where
289 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
290 return a = Comp $ \s -> return (a,s)
293 evalComp :: Comp a -> CompState -> IO a
294 evalComp comp st = do (val,_st') <- runComp comp st
299 { compHscEnv :: HscEnv
300 , compModSummary :: ModSummary
301 , compOldIface :: Maybe ModIface
304 get :: Comp CompState
305 get = Comp $ \s -> return (s,s)
307 modify :: (CompState -> CompState) -> Comp ()
308 modify f = Comp $ \s -> return ((), f s)
310 gets :: (CompState -> a) -> Comp a
311 gets getter = do st <- get
314 liftIO :: IO a -> Comp a
315 liftIO ioA = Comp $ \s -> do a <- ioA
318 type NoRecomp result = ModIface -> Comp result
320 -- FIXME: The old interface and module index are only using in 'batch' and
321 -- 'interactive' mode. They should be removed from 'oneshot' mode.
322 type Compiler result = HscEnv
324 -> Bool -- True <=> source unchanged
325 -> Maybe ModIface -- Old interface, if available
326 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
329 --------------------------------------------------------------
331 --------------------------------------------------------------
333 -- Compile Haskell, boot and extCore in OneShot mode.
334 hscCompileOneShot :: Compiler HscStatus
336 = hscCompiler norecompOneShot oneShotMsg (genComp backend boot_backend)
338 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscOneShot
339 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >> return (Just (HscRecomp False))
341 -- Compile Haskell, boot and extCore in batch mode.
342 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
344 = hscCompiler norecompBatch batchMsg (genComp backend boot_backend)
346 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscBatch
347 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
349 -- Compile Haskell, extCore to bytecode.
350 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
351 hscCompileInteractive
352 = hscCompiler norecompInteractive batchMsg (genComp backend boot_backend)
354 backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
355 boot_backend _ = panic "hscCompileInteractive: HsBootFile"
357 -- Type-check Haskell and .hs-boot only (no external core)
358 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
360 = hscCompiler norecompBatch batchMsg comp
362 backend tc = hscSimpleIface tc >>= hscIgnoreIface >>= hscNothing
364 comp = do -- genComp doesn't fit here, because we want to omit
365 -- desugaring and for the backend to take a TcGblEnv
366 mod_summary <- gets compModSummary
367 case ms_hsc_src mod_summary of
368 ExtCoreFile -> panic "hscCompileNothing: cannot do external core"
370 mb_tc <- hscFileFrontEnd
372 Nothing -> return Nothing
373 Just tc_result -> backend tc_result
376 :: NoRecomp result -- No recomp necessary
377 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
378 -> Comp (Maybe result)
380 hscCompiler norecomp messenger recomp hsc_env mod_summary
381 source_unchanged mbOldIface mbModIndex
382 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
383 do (recomp_reqd, mbCheckedIface)
384 <- {-# SCC "checkOldIface" #-}
385 liftIO $ checkOldIface hsc_env mod_summary
386 source_unchanged mbOldIface
387 -- save the interface that comes back from checkOldIface.
388 -- In one-shot mode we don't have the old iface until this
389 -- point, when checkOldIface reads it from the disk.
390 modify (\s -> s{ compOldIface = mbCheckedIface })
391 case mbCheckedIface of
392 Just iface | not recomp_reqd
393 -> do messenger mbModIndex False
394 result <- norecomp iface
397 -> do messenger mbModIndex True
400 -- the usual way to build the Comp (Maybe result) to pass to hscCompiler
401 genComp :: (ModGuts -> Comp (Maybe a))
402 -> (TcGblEnv -> Comp (Maybe a))
404 genComp backend boot_backend = do
405 mod_summary <- gets compModSummary
406 case ms_hsc_src mod_summary of
408 panic "GHC does not currently support reading External Core files"
410 mb_tc <- hscFileFrontEnd
412 Nothing -> return Nothing
414 case ms_hsc_src mod_summary of
415 HsBootFile -> boot_backend tc_result
417 mb_guts <- hscDesugar tc_result
419 Nothing -> return Nothing
420 Just guts -> backend guts
422 --------------------------------------------------------------
424 --------------------------------------------------------------
426 norecompOneShot :: NoRecomp HscStatus
427 norecompOneShot _old_iface
428 = do hsc_env <- gets compHscEnv
430 dumpIfaceStats hsc_env
433 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
434 norecompBatch = norecompWorker HscNoRecomp False
436 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
437 norecompInteractive = norecompWorker InteractiveNoRecomp True
439 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
440 norecompWorker a _isInterp old_iface
441 = do hsc_env <- gets compHscEnv
443 new_details <- {-# SCC "tcRnIface" #-}
444 initIfaceCheck hsc_env $
445 typecheckIface old_iface
446 dumpIfaceStats hsc_env
447 return (a, old_iface, new_details)
449 --------------------------------------------------------------
450 -- Progress displayers.
451 --------------------------------------------------------------
453 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
454 oneShotMsg _mb_mod_index recomp
455 = do hsc_env <- gets compHscEnv
459 else compilationProgressMsg (hsc_dflags hsc_env) $
460 "compilation IS NOT required"
462 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
463 batchMsg mb_mod_index recomp
464 = do hsc_env <- gets compHscEnv
465 mod_summary <- gets compModSummary
466 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
467 (showModuleIndex mb_mod_index ++
468 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
471 then showMsg "Compiling "
472 else if verbosity (hsc_dflags hsc_env) >= 2
473 then showMsg "Skipping "
476 --------------------------------------------------------------
478 --------------------------------------------------------------
479 hscFileFrontEnd :: Comp (Maybe TcGblEnv)
481 do hsc_env <- gets compHscEnv
482 mod_summary <- gets compModSummary
487 let dflags = hsc_dflags hsc_env
488 hspp_file = ms_hspp_file mod_summary
489 hspp_buf = ms_hspp_buf mod_summary
490 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
493 -> do printBagOfErrors dflags (unitBag err)
497 -- RENAME and TYPECHECK
499 -> do (tc_msgs, maybe_tc_result)
500 <- {-# SCC "Typecheck-Rename" #-}
501 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
502 printErrorsAndWarnings dflags tc_msgs
503 return maybe_tc_result
505 --------------------------------------------------------------
507 --------------------------------------------------------------
509 hscDesugar :: TcGblEnv -> Comp (Maybe ModGuts)
511 = do mod_summary <- gets compModSummary
512 hsc_env <- gets compHscEnv
517 ds_result <- {-# SCC "DeSugar" #-}
518 deSugar hsc_env (ms_location mod_summary) tc_result
521 --------------------------------------------------------------
523 --------------------------------------------------------------
525 hscSimplify :: ModGuts -> Comp ModGuts
526 hscSimplify ds_result
527 = do hsc_env <- gets compHscEnv
532 simpl_result <- {-# SCC "Core2Core" #-}
533 core2core hsc_env ds_result
536 --------------------------------------------------------------
537 -- Interface generators
538 --------------------------------------------------------------
540 -- HACK: we return ModGuts even though we know it's not gonna be used.
541 -- We do this because the type signature needs to be identical
542 -- in structure to the type of 'hscNormalIface'.
543 hscSimpleIface :: TcGblEnv -> Comp (ModIface, Bool, ModDetails, TcGblEnv)
544 hscSimpleIface tc_result
545 = do hsc_env <- gets compHscEnv
546 maybe_old_iface <- gets compOldIface
548 details <- mkBootModDetailsTc hsc_env tc_result
549 (new_iface, no_change)
550 <- {-# SCC "MkFinalIface" #-}
551 mkIfaceTc hsc_env maybe_old_iface details tc_result
552 -- And the answer is ...
553 dumpIfaceStats hsc_env
554 return (new_iface, no_change, details, tc_result)
556 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
557 hscNormalIface simpl_result
558 = do hsc_env <- gets compHscEnv
559 _mod_summary <- gets compModSummary
560 maybe_old_iface <- gets compOldIface
565 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
566 tidyProgram hsc_env simpl_result
569 -- BUILD THE NEW ModIface and ModDetails
570 -- and emit external core if necessary
571 -- This has to happen *after* code gen so that the back-end
572 -- info has been set. Not yet clear if it matters waiting
573 -- until after code output
574 (new_iface, no_change)
575 <- {-# SCC "MkFinalIface" #-}
576 mkIface hsc_env maybe_old_iface details simpl_result
577 -- Emit external core
578 -- This should definitely be here and not after CorePrep,
579 -- because CorePrep produces unqualified constructor wrapper declarations,
580 -- so its output isn't valid External Core (without some preprocessing).
581 emitExternalCore (hsc_dflags hsc_env) cg_guts
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 ; simpl_expr <- simplifyExpr dflags ds_expr
967 -- Tidy it (temporary, until coreSat does cloning)
968 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
970 -- Prepare for codegen
971 ; prepd_expr <- corePrepExpr dflags tidy_expr
974 -- ToDo: improve SrcLoc
976 let ictxt = hsc_IC hsc_env
977 tyvars = varSetElems (ic_tyvars ictxt)
979 case lintUnfolding noSrcLoc tyvars prepd_expr of
980 Just err -> pprPanic "compileExpr" err
986 ; bcos <- coreExprToBCOs dflags prepd_expr
989 ; hval <- linkExpr hsc_env srcspan bcos
997 %************************************************************************
999 Statistics on reading interfaces
1001 %************************************************************************
1004 dumpIfaceStats :: HscEnv -> IO ()
1005 dumpIfaceStats hsc_env
1006 = do { eps <- readIORef (hsc_EPS hsc_env)
1007 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1008 "Interface statistics"
1011 dflags = hsc_dflags hsc_env
1012 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1013 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1016 %************************************************************************
1018 Progress Messages: Module i of n
1020 %************************************************************************
1023 showModuleIndex :: Maybe (Int, Int) -> String
1024 showModuleIndex Nothing = ""
1025 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1029 padded = replicate (length n_str - length i_str) ' ' ++ i_str