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 Desugar ( deSugarExpr )
44 import SimplCore ( simplifyExpr )
45 import TcRnDriver ( tcRnStmt, tcRnExpr, tcRnType )
47 import PrelNames ( iNTERACTIVE )
48 import {- Kind parts of -} Type ( Kind )
49 import CoreLint ( lintUnfolding )
50 import DsMeta ( templateHaskellNames )
51 import SrcLoc ( SrcSpan, noSrcLoc, interactiveSrcLoc, srcLocSpan )
53 import VarEnv ( emptyTidyEnv )
57 import Module ( emptyModuleEnv, ModLocation(..), Module )
61 import SrcLoc ( Located(..) )
65 import SrcLoc ( mkSrcLoc )
66 import TcRnDriver ( tcRnModule )
67 import TcIface ( typecheckIface )
68 import TcRnMonad ( initIfaceCheck, TcGblEnv(..) )
69 import IfaceEnv ( initNameCache )
70 import LoadIface ( ifaceStats, initExternalPackageState )
71 import PrelInfo ( wiredInThings, basicKnownKeyNames )
73 import Desugar ( deSugar )
74 import SimplCore ( core2core )
76 import CorePrep ( corePrepPgm )
77 import CoreToStg ( coreToStg )
80 import TyCon ( isDataTyCon )
81 import Name ( Name, NamedThing(..) )
82 import SimplStg ( stg2stg )
83 import CodeGen ( codeGen )
85 import CmmParse ( parseCmmFile )
92 import CodeOutput ( codeOutput )
93 import NameEnv ( emptyNameEnv )
97 import UniqSupply ( mkSplitUniqSupply )
100 import HscStats ( ppSourceStats )
102 import MkExternalCore ( emitExternalCore )
104 import LazyUniqFM ( emptyUFM )
105 import UniqSupply ( initUs_ )
106 import Bag ( unitBag )
115 %************************************************************************
119 %************************************************************************
122 newHscEnv :: DynFlags -> IO HscEnv
124 = do { eps_var <- newIORef initExternalPackageState
125 ; us <- mkSplitUniqSupply 'r'
126 ; nc_var <- newIORef (initNameCache us knownKeyNames)
127 ; fc_var <- newIORef emptyUFM
128 ; mlc_var <- newIORef emptyModuleEnv
129 ; return (HscEnv { hsc_dflags = dflags,
132 hsc_IC = emptyInteractiveContext,
133 hsc_HPT = emptyHomePackageTable,
138 hsc_global_rdr_env = emptyGlobalRdrEnv,
139 hsc_global_type_env = emptyNameEnv } ) }
142 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
143 -- where templateHaskellNames are defined
144 knownKeyNames = map getName wiredInThings
145 ++ basicKnownKeyNames
147 ++ templateHaskellNames
153 -- | parse a file, returning the abstract syntax
154 parseFile :: HscEnv -> ModSummary -> IO (Maybe (Located (HsModule RdrName)))
155 parseFile hsc_env mod_summary
157 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
160 -> do printBagOfErrors dflags (unitBag err)
163 -> return (Just rdr_module)
165 dflags = hsc_dflags hsc_env
166 hspp_file = ms_hspp_file mod_summary
167 hspp_buf = ms_hspp_buf mod_summary
169 -- | Rename and typecheck a module
170 typecheckModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
171 -> IO (Maybe TcGblEnv)
172 typecheckModule hsc_env mod_summary rdr_module
174 (tc_msgs, maybe_tc_result)
175 <- {-# SCC "Typecheck-Rename" #-}
176 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
177 printErrorsAndWarnings dflags tc_msgs
178 return maybe_tc_result
180 dflags = hsc_dflags hsc_env
183 (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
184 Maybe (HsDoc Name), HaddockModInfo Name))
186 -- | Rename and typecheck a module, additinoally returning the renamed syntax
187 typecheckRenameModule :: HscEnv -> ModSummary -> Located (HsModule RdrName)
188 -> IO (Maybe (TcGblEnv, RenamedStuff))
189 typecheckRenameModule hsc_env mod_summary rdr_module
191 (tc_msgs, maybe_tc_result)
192 <- {-# SCC "Typecheck-Rename" #-}
193 tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
194 printErrorsAndWarnings dflags tc_msgs
195 case maybe_tc_result of
196 Nothing -> return Nothing
198 let rn_info = do decl <- tcg_rn_decls tc_result
199 imports <- tcg_rn_imports tc_result
200 let exports = tcg_rn_exports tc_result
201 let doc = tcg_doc tc_result
202 let hmi = tcg_hmi tc_result
203 return (decl,imports,exports,doc,hmi)
204 return (Just (tc_result, rn_info))
206 dflags = hsc_dflags hsc_env
208 -- | Convert a typechecked module to Core
209 deSugarModule :: HscEnv -> ModSummary -> TcGblEnv -> IO (Maybe ModGuts)
210 deSugarModule hsc_env mod_summary tc_result
211 = deSugar hsc_env (ms_location mod_summary) tc_result
213 -- | Make a 'ModIface' from the results of typechecking. Used when
214 -- not optimising, and the interface doesn't need to contain any
215 -- unfoldings or other cross-module optimisation info.
216 -- ToDo: the old interface is only needed to get the version numbers,
217 -- we should use fingerprint versions instead.
218 makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
219 -> IO (ModIface,Bool)
220 makeSimpleIface hsc_env maybe_old_iface tc_result details = do
221 mkIfaceTc hsc_env maybe_old_iface details tc_result
223 -- | Make a 'ModDetails' from the results of typechecking. Used when
224 -- typechecking only, as opposed to full compilation.
225 makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
226 makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
228 -- deSugarModule :: HscEnv -> TcGblEnv -> IO Core
231 %************************************************************************
233 The main compiler pipeline
235 %************************************************************************
237 --------------------------------
238 The compilation proper
239 --------------------------------
242 It's the task of the compilation proper to compile Haskell, hs-boot and
243 core files to either byte-code, hard-code (C, asm, Java, ect) or to
244 nothing at all (the module is still parsed and type-checked. This
245 feature is mostly used by IDE's and the likes).
246 Compilation can happen in either 'one-shot', 'batch', 'nothing',
247 or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
248 targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
250 The modes are kept separate because of their different types and meanings.
251 In 'one-shot' mode, we're only compiling a single file and can therefore
252 discard the new ModIface and ModDetails. This is also the reason it only
253 targets hard-code; compiling to byte-code or nothing doesn't make sense
254 when we discard the result.
255 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
256 and ModDetails. 'Batch' mode doesn't target byte-code since that require
257 us to return the newly compiled byte-code.
258 'Nothing' mode has exactly the same type as 'batch' mode but they're still
259 kept separate. This is because compiling to nothing is fairly special: We
260 don't output any interface files, we don't run the simplifier and we don't
262 'Interactive' mode is similar to 'batch' mode except that we return the
263 compiled byte-code together with the ModIface and ModDetails.
265 Trying to compile a hs-boot file to byte-code will result in a run-time
266 error. This is the only thing that isn't caught by the type-system.
270 -- Status of a compilation to hard-code or nothing.
273 | HscRecomp Bool -- Has stub files.
274 -- This is a hack. We can't compile C files here
275 -- since it's done in DriverPipeline. For now we
276 -- just return True if we want the caller to compile
279 -- Status of a compilation to byte-code.
280 data InteractiveStatus
281 = InteractiveNoRecomp
282 | InteractiveRecomp Bool -- Same as HscStatus
287 -- I want Control.Monad.State! --Lemmih 03/07/2006
288 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
290 instance Monad Comp where
291 g >>= fn = Comp $ \s -> runComp g s >>= \(a,s') -> runComp (fn a) s'
292 return a = Comp $ \s -> return (a,s)
295 evalComp :: Comp a -> CompState -> IO a
296 evalComp comp st = do (val,_st') <- runComp comp st
301 { compHscEnv :: HscEnv
302 , compModSummary :: ModSummary
303 , compOldIface :: Maybe ModIface
306 get :: Comp CompState
307 get = Comp $ \s -> return (s,s)
309 modify :: (CompState -> CompState) -> Comp ()
310 modify f = Comp $ \s -> return ((), f s)
312 gets :: (CompState -> a) -> Comp a
313 gets getter = do st <- get
316 liftIO :: IO a -> Comp a
317 liftIO ioA = Comp $ \s -> do a <- ioA
320 type NoRecomp result = ModIface -> Comp result
322 -- FIXME: The old interface and module index are only using in 'batch' and
323 -- 'interactive' mode. They should be removed from 'oneshot' mode.
324 type Compiler result = HscEnv
326 -> Bool -- True <=> source unchanged
327 -> Maybe ModIface -- Old interface, if available
328 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
331 --------------------------------------------------------------
333 --------------------------------------------------------------
335 -- Compile Haskell, boot and extCore in OneShot mode.
336 hscCompileOneShot :: Compiler HscStatus
338 = hscCompiler norecompOneShot oneShotMsg (genComp backend boot_backend)
340 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscOneShot
341 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >> return (Just (HscRecomp False))
343 -- Compile Haskell, boot and extCore in batch mode.
344 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
346 = hscCompiler norecompBatch batchMsg (genComp backend boot_backend)
348 backend inp = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscBatch
349 boot_backend inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
351 -- Compile Haskell, extCore to bytecode.
352 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
353 hscCompileInteractive
354 = hscCompiler norecompInteractive batchMsg (genComp backend boot_backend)
356 backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
357 boot_backend _ = panic "hscCompileInteractive: HsBootFile"
359 -- Type-check Haskell and .hs-boot only (no external core)
360 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
362 = hscCompiler norecompBatch batchMsg comp
364 backend tc = hscSimpleIface tc >>= hscIgnoreIface >>= hscNothing
366 comp = do -- genComp doesn't fit here, because we want to omit
367 -- desugaring and for the backend to take a TcGblEnv
368 mod_summary <- gets compModSummary
369 case ms_hsc_src mod_summary of
370 ExtCoreFile -> panic "hscCompileNothing: cannot do external core"
372 mb_tc <- hscFileFrontEnd
374 Nothing -> return Nothing
375 Just tc_result -> backend tc_result
378 :: NoRecomp result -- No recomp necessary
379 -> (Maybe (Int,Int) -> Bool -> Comp ()) -- Message callback
380 -> Comp (Maybe result)
382 hscCompiler norecomp messenger recomp hsc_env mod_summary
383 source_unchanged mbOldIface mbModIndex
384 = flip evalComp (CompState hsc_env mod_summary mbOldIface) $
385 do (recomp_reqd, mbCheckedIface)
386 <- {-# SCC "checkOldIface" #-}
387 liftIO $ checkOldIface hsc_env mod_summary
388 source_unchanged mbOldIface
389 -- save the interface that comes back from checkOldIface.
390 -- In one-shot mode we don't have the old iface until this
391 -- point, when checkOldIface reads it from the disk.
392 modify (\s -> s{ compOldIface = mbCheckedIface })
393 case mbCheckedIface of
394 Just iface | not recomp_reqd
395 -> do messenger mbModIndex False
396 result <- norecomp iface
399 -> do messenger mbModIndex True
402 -- the usual way to build the Comp (Maybe result) to pass to hscCompiler
403 genComp :: (ModGuts -> Comp (Maybe a))
404 -> (TcGblEnv -> Comp (Maybe a))
406 genComp backend boot_backend = do
407 mod_summary <- gets compModSummary
408 case ms_hsc_src mod_summary of
410 panic "GHC does not currently support reading External Core files"
412 mb_tc <- hscFileFrontEnd
414 Nothing -> return Nothing
416 case ms_hsc_src mod_summary of
417 HsBootFile -> boot_backend tc_result
419 mb_guts <- hscDesugar tc_result
421 Nothing -> return Nothing
422 Just guts -> backend guts
424 --------------------------------------------------------------
426 --------------------------------------------------------------
428 norecompOneShot :: NoRecomp HscStatus
429 norecompOneShot _old_iface
430 = do hsc_env <- gets compHscEnv
432 dumpIfaceStats hsc_env
435 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
436 norecompBatch = norecompWorker HscNoRecomp False
438 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
439 norecompInteractive = norecompWorker InteractiveNoRecomp True
441 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
442 norecompWorker a _isInterp old_iface
443 = do hsc_env <- gets compHscEnv
445 new_details <- {-# SCC "tcRnIface" #-}
446 initIfaceCheck hsc_env $
447 typecheckIface old_iface
448 dumpIfaceStats hsc_env
449 return (a, old_iface, new_details)
451 --------------------------------------------------------------
452 -- Progress displayers.
453 --------------------------------------------------------------
455 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
456 oneShotMsg _mb_mod_index recomp
457 = do hsc_env <- gets compHscEnv
461 else compilationProgressMsg (hsc_dflags hsc_env) $
462 "compilation IS NOT required"
464 batchMsg :: Maybe (Int,Int) -> Bool -> Comp ()
465 batchMsg mb_mod_index recomp
466 = do hsc_env <- gets compHscEnv
467 mod_summary <- gets compModSummary
468 let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
469 (showModuleIndex mb_mod_index ++
470 msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
473 then showMsg "Compiling "
474 else if verbosity (hsc_dflags hsc_env) >= 2
475 then showMsg "Skipping "
478 --------------------------------------------------------------
480 --------------------------------------------------------------
481 hscFileFrontEnd :: Comp (Maybe TcGblEnv)
483 do hsc_env <- gets compHscEnv
484 mod_summary <- gets compModSummary
489 let dflags = hsc_dflags hsc_env
490 hspp_file = ms_hspp_file mod_summary
491 hspp_buf = ms_hspp_buf mod_summary
492 maybe_parsed <- myParseModule dflags hspp_file hspp_buf
495 -> do printBagOfErrors dflags (unitBag err)
499 -- RENAME and TYPECHECK
501 -> do (tc_msgs, maybe_tc_result)
502 <- {-# SCC "Typecheck-Rename" #-}
503 tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
504 printErrorsAndWarnings dflags tc_msgs
505 return maybe_tc_result
507 --------------------------------------------------------------
509 --------------------------------------------------------------
511 hscDesugar :: TcGblEnv -> Comp (Maybe ModGuts)
513 = do mod_summary <- gets compModSummary
514 hsc_env <- gets compHscEnv
519 ds_result <- {-# SCC "DeSugar" #-}
520 deSugar hsc_env (ms_location mod_summary) tc_result
523 --------------------------------------------------------------
525 --------------------------------------------------------------
527 hscSimplify :: ModGuts -> Comp ModGuts
528 hscSimplify ds_result
529 = do hsc_env <- gets compHscEnv
534 simpl_result <- {-# SCC "Core2Core" #-}
535 core2core hsc_env ds_result
538 --------------------------------------------------------------
539 -- Interface generators
540 --------------------------------------------------------------
542 -- HACK: we return ModGuts even though we know it's not gonna be used.
543 -- We do this because the type signature needs to be identical
544 -- in structure to the type of 'hscNormalIface'.
545 hscSimpleIface :: TcGblEnv -> Comp (ModIface, Bool, ModDetails, TcGblEnv)
546 hscSimpleIface tc_result
547 = do hsc_env <- gets compHscEnv
548 maybe_old_iface <- gets compOldIface
550 details <- mkBootModDetailsTc hsc_env tc_result
551 (new_iface, no_change)
552 <- {-# SCC "MkFinalIface" #-}
553 mkIfaceTc hsc_env maybe_old_iface details tc_result
554 -- And the answer is ...
555 dumpIfaceStats hsc_env
556 return (new_iface, no_change, details, tc_result)
558 hscNormalIface :: ModGuts -> Comp (ModIface, Bool, ModDetails, CgGuts)
559 hscNormalIface simpl_result
560 = do hsc_env <- gets compHscEnv
561 _mod_summary <- gets compModSummary
562 maybe_old_iface <- gets compOldIface
567 (cg_guts, details) <- {-# SCC "CoreTidy" #-}
568 tidyProgram hsc_env simpl_result
571 -- BUILD THE NEW ModIface and ModDetails
572 -- and emit external core if necessary
573 -- This has to happen *after* code gen so that the back-end
574 -- info has been set. Not yet clear if it matters waiting
575 -- until after code output
576 (new_iface, no_change)
577 <- {-# SCC "MkFinalIface" #-}
578 mkIface hsc_env maybe_old_iface details simpl_result
579 -- Emit external core
580 -- This should definitely be here and not after CorePrep,
581 -- because CorePrep produces unqualified constructor wrapper declarations,
582 -- so its output isn't valid External Core (without some preprocessing).
583 emitExternalCore (hsc_dflags hsc_env) cg_guts
584 dumpIfaceStats hsc_env
587 -- Return the prepared code.
588 return (new_iface, no_change, details, cg_guts)
590 --------------------------------------------------------------
591 -- BackEnd combinators
592 --------------------------------------------------------------
594 hscWriteIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
595 hscWriteIface (iface, no_change, details, a)
596 = do mod_summary <- gets compModSummary
597 hsc_env <- gets compHscEnv
598 let dflags = hsc_dflags hsc_env
601 $ writeIfaceFile dflags (ms_location mod_summary) iface
602 return (iface, details, a)
604 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
605 hscIgnoreIface (iface, _no_change, details, a)
606 = return (iface, details, a)
608 -- Don't output any code.
609 hscNothing :: (ModIface, ModDetails, a) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
610 hscNothing (iface, details, _)
611 = return (Just (HscRecomp False, iface, details))
613 -- Generate code and return both the new ModIface and the ModDetails.
614 hscBatch :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe (HscStatus, ModIface, ModDetails))
615 hscBatch (iface, details, cgguts)
616 = do hasStub <- hscCompile cgguts
617 return (Just (HscRecomp hasStub, iface, details))
619 -- Here we don't need the ModIface and ModDetails anymore.
620 hscOneShot :: (ModIface, ModDetails, CgGuts) -> Comp (Maybe HscStatus)
621 hscOneShot (_, _, cgguts)
622 = do hasStub <- hscCompile cgguts
623 return (Just (HscRecomp hasStub))
625 -- Compile to hard-code.
626 hscCompile :: CgGuts -> Comp Bool
628 = do hsc_env <- gets compHscEnv
629 mod_summary <- gets compModSummary
631 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
632 -- From now on, we just use the bits we need.
633 cg_module = this_mod,
634 cg_binds = core_binds,
636 cg_dir_imps = dir_imps,
637 cg_foreign = foreign_stubs,
638 cg_dep_pkgs = dependencies,
639 cg_hpc_info = hpc_info } = cgguts
640 dflags = hsc_dflags hsc_env
641 location = ms_location mod_summary
642 data_tycons = filter isDataTyCon tycons
643 -- cg_tycons includes newtypes, for the benefit of External Core,
644 -- but we don't generate any code for newtypes
647 -- PREPARE FOR CODE GENERATION
648 -- Do saturation and convert to A-normal form
649 prepd_binds <- {-# SCC "CorePrep" #-}
650 corePrepPgm dflags core_binds data_tycons ;
651 ----------------- Convert to STG ------------------
652 (stg_binds, cost_centre_info)
653 <- {-# SCC "CoreToStg" #-}
654 myCoreToStg dflags this_mod prepd_binds
655 ------------------ Code generation ------------------
656 cmms <- {-# SCC "CodeGen" #-}
657 codeGen dflags this_mod data_tycons
658 dir_imps cost_centre_info
660 --- Optionally run experimental Cmm transformations ---
661 cmms <- optionallyConvertAndOrCPS dflags cmms
662 -- ^ unless certain dflags are on, the identity function
663 ------------------ Code output -----------------------
664 rawcmms <- cmmToRawCmm cmms
665 (_stub_h_exists, stub_c_exists)
666 <- codeOutput dflags this_mod location foreign_stubs
670 hscInteractive :: (ModIface, ModDetails, CgGuts)
671 -> Comp (Maybe (InteractiveStatus, ModIface, ModDetails))
673 hscInteractive (iface, details, cgguts)
674 = do hsc_env <- gets compHscEnv
675 mod_summary <- gets compModSummary
677 let CgGuts{ -- This is the last use of the ModGuts in a compilation.
678 -- From now on, we just use the bits we need.
679 cg_module = this_mod,
680 cg_binds = core_binds,
682 cg_foreign = foreign_stubs,
683 cg_modBreaks = mod_breaks } = cgguts
684 dflags = hsc_dflags hsc_env
685 location = ms_location mod_summary
686 data_tycons = filter isDataTyCon tycons
687 -- cg_tycons includes newtypes, for the benefit of External Core,
688 -- but we don't generate any code for newtypes
691 -- PREPARE FOR CODE GENERATION
692 -- Do saturation and convert to A-normal form
693 prepd_binds <- {-# SCC "CorePrep" #-}
694 corePrepPgm dflags core_binds data_tycons ;
695 ----------------- Generate byte code ------------------
696 comp_bc <- byteCodeGen dflags prepd_binds data_tycons mod_breaks
697 ------------------ Create f-x-dynamic C-side stuff ---
698 (_istub_h_exists, istub_c_exists)
699 <- outputForeignStubs dflags this_mod location foreign_stubs
700 return (Just (InteractiveRecomp istub_c_exists comp_bc mod_breaks, iface, details))
702 hscInteractive _ = panic "GHC not compiled with interpreter"
705 ------------------------------
707 hscCmmFile :: DynFlags -> FilePath -> IO Bool
708 hscCmmFile dflags filename = do
709 maybe_cmm <- parseCmmFile dflags filename
711 Nothing -> return False
713 cmms <- optionallyConvertAndOrCPS dflags [cmm]
714 rawCmms <- cmmToRawCmm cmms
715 codeOutput dflags no_mod no_loc NoStubs [] rawCmms
718 no_mod = panic "hscCmmFile: no_mod"
719 no_loc = ModLocation{ ml_hs_file = Just filename,
720 ml_hi_file = panic "hscCmmFile: no hi file",
721 ml_obj_file = panic "hscCmmFile: no obj file" }
723 optionallyConvertAndOrCPS :: DynFlags -> [Cmm] -> IO [Cmm]
724 optionallyConvertAndOrCPS dflags cmms =
725 do -------- Optionally convert to and from zipper ------
726 cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
727 then mapM (testCmmConversion dflags) cmms
729 --------- Optionally convert to CPS (MDA) -----------
730 cmms <- if not (dopt Opt_ConvertToZipCfgAndBack dflags) &&
731 dopt Opt_RunCPSZ dflags
732 then cmmCPS dflags cmms
737 testCmmConversion :: DynFlags -> Cmm -> IO Cmm
738 testCmmConversion dflags cmm =
739 do showPass dflags "CmmToCmm"
740 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
741 --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
742 us <- mkSplitUniqSupply 'C'
743 let cfopts = runTx $ runCmmOpts cmmCfgOptsZ
744 let cvtm = do g <- cmmToZgraph cmm
746 let zgraph = initUs_ us cvtm
747 cps_zgraph <- protoCmmCPSZ dflags zgraph
748 let chosen_graph = if dopt Opt_RunCPSZ dflags then cps_zgraph else zgraph
749 dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
750 showPass dflags "Convert from Z back to Cmm"
751 let cvt = cmmOfZgraph $ cfopts $ chosen_graph
752 dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
754 -- return cmm -- don't use the conversion
756 myParseModule :: DynFlags -> FilePath -> Maybe StringBuffer
757 -> IO (Either ErrMsg (Located (HsModule RdrName)))
758 myParseModule dflags src_filename maybe_src_buf
759 = -------------------------- Parser ----------------
760 showPass dflags "Parser" >>
761 {-# SCC "Parser" #-} do
763 -- sometimes we already have the buffer in memory, perhaps
764 -- because we needed to parse the imports out of it, or get the
766 buf <- case maybe_src_buf of
768 Nothing -> hGetStringBuffer src_filename
770 let loc = mkSrcLoc (mkFastString src_filename) 1 0
772 case unP parseModule (mkPState buf loc dflags) of {
774 PFailed span err -> return (Left (mkPlainErrMsg span err));
776 POk pst rdr_module -> do {
778 let {ms = getMessages pst};
779 printErrorsAndWarnings dflags ms;
780 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
782 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
784 dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
785 (ppSourceStats False rdr_module) ;
787 return (Right rdr_module)
788 -- ToDo: free the string buffer later.
792 myCoreToStg :: DynFlags -> Module -> [CoreBind]
793 -> IO ( [(StgBinding,[(Id,[Id])])] -- output program
794 , CollectedCCs) -- cost centre info (declared and used)
796 myCoreToStg dflags this_mod prepd_binds
798 stg_binds <- {-# SCC "Core2Stg" #-}
799 coreToStg (thisPackage dflags) prepd_binds
801 (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
802 stg2stg dflags this_mod stg_binds
804 return (stg_binds2, cost_centre_info)
808 %************************************************************************
810 \subsection{Compiling a do-statement}
812 %************************************************************************
814 When the UnlinkedBCOExpr is linked you get an HValue of type
816 When you run it you get a list of HValues that should be
817 the same length as the list of names; add them to the ClosureEnv.
819 A naked expression returns a singleton Name [it].
821 What you type The IO [HValue] that hscStmt returns
822 ------------- ------------------------------------
823 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
826 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
829 expr (of IO type) ==> expr >>= \ v -> return [v]
830 [NB: result not printed] bindings: [it]
833 expr (of non-IO type,
834 result showable) ==> let v = expr in print v >> return [v]
837 expr (of non-IO type,
838 result not showable) ==> error
842 hscStmt -- Compile a stmt all the way to an HValue, but don't run it
844 -> String -- The statement
845 -> IO (Maybe ([Id], HValue))
848 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) stmt
849 ; case maybe_stmt of {
850 Nothing -> return Nothing ; -- Parse error
851 Just Nothing -> return Nothing ; -- Empty line
852 Just (Just parsed_stmt) -> do { -- The real stuff
854 -- Rename and typecheck it
855 let icontext = hsc_IC hsc_env
856 ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
858 ; case maybe_tc_result of {
859 Nothing -> return Nothing ;
860 Just (ids, tc_expr) -> do {
863 ; let rdr_env = ic_rn_gbl_env icontext
864 type_env = mkTypeEnv (map AnId (ic_tmp_ids icontext))
865 ; mb_ds_expr <- deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
867 ; case mb_ds_expr of {
868 Nothing -> return Nothing ;
871 -- Then desugar, code gen, and link it
872 ; let src_span = srcLocSpan interactiveSrcLoc
873 ; hval <- compileExpr hsc_env src_span ds_expr
875 ; return (Just (ids, hval))
878 hscTcExpr -- Typecheck an expression (but don't run it)
880 -> String -- The expression
883 hscTcExpr hsc_env expr
884 = do { maybe_stmt <- hscParseStmt (hsc_dflags hsc_env) expr
885 ; let icontext = hsc_IC hsc_env
886 ; case maybe_stmt of {
887 Nothing -> return Nothing ; -- Parse error
888 Just (Just (L _ (ExprStmt expr _ _)))
889 -> tcRnExpr hsc_env icontext expr ;
890 Just _ -> do { errorMsg (hsc_dflags hsc_env) (text "not an expression:" <+> quotes (text expr)) ;
894 hscKcType -- Find the kind of a type
896 -> String -- The type
899 hscKcType hsc_env str
900 = do { maybe_type <- hscParseType (hsc_dflags hsc_env) str
901 ; let icontext = hsc_IC hsc_env
902 ; case maybe_type of {
903 Just ty -> tcRnType hsc_env icontext ty ;
904 Nothing -> return Nothing } }
910 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
911 hscParseStmt = hscParseThing parseStmt
913 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
914 hscParseType = hscParseThing parseType
917 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
918 hscParseIdentifier = hscParseThing parseIdentifier
920 hscParseThing :: Outputable thing
922 -> DynFlags -> String
924 -- Nothing => Parse error (message already printed)
926 hscParseThing parser dflags str
927 = showPass dflags "Parser" >>
928 {-# SCC "Parser" #-} do
930 buf <- stringToStringBuffer str
932 let loc = mkSrcLoc FSLIT("<interactive>") 1 0
934 case unP parser (mkPState buf loc dflags) of {
936 PFailed span err -> do { printError span err;
939 POk pst thing -> do {
941 let {ms = getMessages pst};
942 printErrorsAndWarnings dflags ms;
943 when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
945 --ToDo: can't free the string buffer until we've finished this
946 -- compilation sweep and all the identifiers have gone away.
947 dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing);
952 %************************************************************************
954 Desugar, simplify, convert to bytecode, and link an expression
956 %************************************************************************
960 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
962 compileExpr hsc_env srcspan ds_expr
963 = do { let { dflags = hsc_dflags hsc_env ;
964 lint_on = dopt Opt_DoCoreLinting dflags }
967 ; simpl_expr <- simplifyExpr dflags ds_expr
969 -- Tidy it (temporary, until coreSat does cloning)
970 ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
972 -- Prepare for codegen
973 ; prepd_expr <- corePrepExpr dflags tidy_expr
976 -- ToDo: improve SrcLoc
978 let ictxt = hsc_IC hsc_env
979 tyvars = varSetElems (ic_tyvars ictxt)
981 case lintUnfolding noSrcLoc tyvars prepd_expr of
982 Just err -> pprPanic "compileExpr" err
988 ; bcos <- coreExprToBCOs dflags prepd_expr
991 ; hval <- linkExpr hsc_env srcspan bcos
999 %************************************************************************
1001 Statistics on reading interfaces
1003 %************************************************************************
1006 dumpIfaceStats :: HscEnv -> IO ()
1007 dumpIfaceStats hsc_env
1008 = do { eps <- readIORef (hsc_EPS hsc_env)
1009 ; dumpIfSet (dump_if_trace || dump_rn_stats)
1010 "Interface statistics"
1013 dflags = hsc_dflags hsc_env
1014 dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
1015 dump_if_trace = dopt Opt_D_dump_if_trace dflags
1018 %************************************************************************
1020 Progress Messages: Module i of n
1022 %************************************************************************
1025 showModuleIndex :: Maybe (Int, Int) -> String
1026 showModuleIndex Nothing = ""
1027 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1031 padded = replicate (length n_str - length i_str) ' ' ++ i_str