f686f34931f2712feecd23e1709a5329930c1e0c
[ghc-hetmet.git] / compiler / main / HscMain.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 %
4
5 \section[GHC_Main]{Main driver for Glasgow Haskell compiler}
6
7 \begin{code}
8 module HscMain
9     ( newHscEnv, hscCmmFile
10     , hscParseIdentifier
11     , hscSimplify
12     , evalComp
13     , hscNormalIface, hscWriteIface, hscOneShot
14     , CompState (..)
15 #ifdef GHCI
16     , hscStmt, hscTcExpr, hscKcType
17     , compileExpr
18 #endif
19     , hscCompileOneShot     -- :: Compiler HscStatus
20     , hscCompileBatch       -- :: Compiler (HscStatus, ModIface, ModDetails)
21     , hscCompileNothing     -- :: Compiler (HscStatus, ModIface, ModDetails)
22     , hscCompileInteractive -- :: Compiler (InteractiveStatus, ModIface, ModDetails)
23     , HscStatus (..)
24     , InteractiveStatus (..)
25
26     -- The new interface
27     , parseFile
28     , typecheckModule
29     , typecheckRenameModule
30     , deSugarModule
31     , makeSimpleIface
32     , makeSimpleDetails
33     ) where
34
35 #ifdef GHCI
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 ) 
44 import Type             ( Type )
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 )
50 import VarSet
51 import VarEnv           ( emptyTidyEnv )
52 #endif
53
54 import Var              ( Id )
55 import Module           ( emptyModuleEnv, ModLocation(..), Module )
56 import RdrName
57 import HsSyn
58 import CoreSyn
59 import SrcLoc           ( Located(..) )
60 import StringBuffer
61 import Parser
62 import Lexer
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 )
70 import MkIface
71 import Desugar          ( deSugar )
72 import SimplCore        ( core2core )
73 import TidyPgm
74 import CorePrep         ( corePrepPgm )
75 import CoreToStg        ( coreToStg )
76 import StgSyn
77 import CostCentre
78 import TyCon            ( isDataTyCon )
79 import Name             ( Name, NamedThing(..) )
80 import SimplStg         ( stg2stg )
81 import CodeGen          ( codeGen )
82 import Cmm              ( Cmm )
83 import CmmParse         ( parseCmmFile )
84 import CmmCPS
85 import CmmCPSZ
86 import CmmInfo
87 import CmmCvt
88 import CmmTx
89 import CmmContFlowOpt
90 import CodeOutput       ( codeOutput )
91 import NameEnv          ( emptyNameEnv )
92
93 import DynFlags
94 import ErrUtils
95 import UniqSupply       ( mkSplitUniqSupply )
96
97 import Outputable
98 import HscStats         ( ppSourceStats )
99 import HscTypes
100 import MkExternalCore   ( emitExternalCore )
101 import FastString
102 import LazyUniqFM               ( emptyUFM )
103 import UniqSupply       ( initUs_ )
104 import Bag              ( unitBag )
105
106 import Control.Monad
107 import System.Exit
108 import System.IO
109 import Data.IORef
110 \end{code}
111
112
113 %************************************************************************
114 %*                                                                      *
115                 Initialisation
116 %*                                                                      *
117 %************************************************************************
118
119 \begin{code}
120 newHscEnv :: DynFlags -> IO HscEnv
121 newHscEnv dflags
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,
128                            hsc_targets = [],
129                            hsc_mod_graph = [],
130                            hsc_IC     = emptyInteractiveContext,
131                            hsc_HPT    = emptyHomePackageTable,
132                            hsc_EPS    = eps_var,
133                            hsc_NC     = nc_var,
134                            hsc_FC     = fc_var,
135                            hsc_MLC    = mlc_var,
136                            hsc_global_rdr_env = emptyGlobalRdrEnv,
137                            hsc_global_type_env = emptyNameEnv } ) }
138                         
139
140 knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
141                         -- where templateHaskellNames are defined
142 knownKeyNames = map getName wiredInThings 
143               ++ basicKnownKeyNames
144 #ifdef GHCI
145               ++ templateHaskellNames
146 #endif
147 \end{code}
148
149
150 \begin{code}
151 -- | parse a file, returning the abstract syntax
152 parseFile :: HscEnv -> ModSummary -> IO (Maybe (Located (HsModule RdrName)))
153 parseFile hsc_env mod_summary
154  = do 
155        maybe_parsed <- myParseModule dflags hspp_file hspp_buf
156        case maybe_parsed of
157          Left err
158              -> do printBagOfErrors dflags (unitBag err)
159                    return Nothing
160          Right rdr_module
161              -> return (Just rdr_module)
162   where
163            dflags    = hsc_dflags hsc_env
164            hspp_file = ms_hspp_file mod_summary
165            hspp_buf  = ms_hspp_buf  mod_summary
166
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
171  = do 
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
177   where
178         dflags = hsc_dflags hsc_env
179
180 type RenamedStuff = 
181         (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
182                 Maybe (HsDoc Name), HaddockModInfo Name))
183
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
188  = do 
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
195            Just tc_result -> do
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))
203   where
204         dflags = hsc_dflags hsc_env
205
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
210
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
220
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
225
226 -- deSugarModule :: HscEnv -> TcGblEnv -> IO Core
227 \end{code}
228
229 %************************************************************************
230 %*                                                                      *
231                 The main compiler pipeline
232 %*                                                                      *
233 %************************************************************************
234
235                    --------------------------------
236                         The compilation proper
237                    --------------------------------
238
239
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
247 targets byte-code.
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
259 generate any code.
260 'Interactive' mode is similar to 'batch' mode except that we return the
261 compiled byte-code together with the ModIface and ModDetails.
262
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.
265
266 \begin{code}
267
268 -- Status of a compilation to hard-code or nothing.
269 data HscStatus
270     = HscNoRecomp
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
275                       -- them for us.
276
277 -- Status of a compilation to byte-code.
278 data InteractiveStatus
279     = InteractiveNoRecomp
280     | InteractiveRecomp Bool     -- Same as HscStatus
281                         CompiledByteCode
282                         ModBreaks
283
284
285 -- I want Control.Monad.State! --Lemmih 03/07/2006
286 newtype Comp a = Comp {runComp :: CompState -> IO (a, CompState)}
287
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)
291     fail = error
292
293 evalComp :: Comp a -> CompState -> IO a
294 evalComp comp st = do (val,_st') <- runComp comp st
295                       return val
296
297 data CompState
298     = CompState
299     { compHscEnv     :: HscEnv
300     , compModSummary :: ModSummary
301     , compOldIface   :: Maybe ModIface
302     }
303
304 get :: Comp CompState
305 get = Comp $ \s -> return (s,s)
306
307 modify :: (CompState -> CompState) -> Comp ()
308 modify f = Comp $ \s -> return ((), f s)
309
310 gets :: (CompState -> a) -> Comp a
311 gets getter = do st <- get
312                  return (getter st)
313
314 liftIO :: IO a -> Comp a
315 liftIO ioA = Comp $ \s -> do a <- ioA
316                              return (a,s)
317
318 type NoRecomp result = ModIface -> Comp result
319
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
323                      -> ModSummary
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)
327                      -> IO (Maybe result)
328
329 --------------------------------------------------------------
330 -- Compilers
331 --------------------------------------------------------------
332
333 -- Compile Haskell, boot and extCore in OneShot mode.
334 hscCompileOneShot :: Compiler HscStatus
335 hscCompileOneShot
336    = hscCompiler norecompOneShot oneShotMsg (genComp backend boot_backend)
337    where
338      backend inp  = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscOneShot
339      boot_backend inp = hscSimpleIface inp >>= hscWriteIface >> return (Just (HscRecomp False))
340
341 -- Compile Haskell, boot and extCore in batch mode.
342 hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
343 hscCompileBatch
344    = hscCompiler norecompBatch batchMsg (genComp backend boot_backend)
345    where
346      backend inp  = hscSimplify inp >>= hscNormalIface >>= hscWriteIface >>= hscBatch
347      boot_backend inp = hscSimpleIface inp >>= hscWriteIface >>= hscNothing
348
349 -- Compile Haskell, extCore to bytecode.
350 hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
351 hscCompileInteractive
352    = hscCompiler norecompInteractive batchMsg (genComp backend boot_backend)
353    where
354      backend inp = hscSimplify inp >>= hscNormalIface >>= hscIgnoreIface >>= hscInteractive
355      boot_backend _ = panic "hscCompileInteractive: HsBootFile"
356
357 -- Type-check Haskell and .hs-boot only (no external core)
358 hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
359 hscCompileNothing
360    = hscCompiler norecompBatch batchMsg comp
361    where
362      backend tc = hscSimpleIface tc >>= hscIgnoreIface >>= hscNothing
363
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"
369            _other -> do
370                 mb_tc <- hscFileFrontEnd
371                 case mb_tc of
372                   Nothing -> return Nothing
373                   Just tc_result -> backend tc_result
374         
375 hscCompiler
376         :: NoRecomp result                       -- No recomp necessary
377         -> (Maybe (Int,Int) -> Bool -> Comp ())  -- Message callback
378         -> Comp (Maybe result)
379         -> Compiler 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
395                      return (Just result)
396            _otherwise
397                -> do messenger mbModIndex True
398                      recomp
399
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))
403         -> Comp (Maybe a)
404 genComp backend boot_backend = do
405     mod_summary <- gets compModSummary
406     case ms_hsc_src mod_summary of
407        ExtCoreFile -> do
408           panic "GHC does not currently support reading External Core files"
409        _not_core -> do
410           mb_tc <- hscFileFrontEnd
411           case mb_tc of
412             Nothing -> return Nothing
413             Just tc_result -> 
414               case ms_hsc_src mod_summary of
415                 HsBootFile -> boot_backend tc_result
416                 _other     -> do
417                   mb_guts <- hscDesugar tc_result
418                   case mb_guts of
419                     Nothing -> return Nothing
420                     Just guts -> backend guts
421
422 --------------------------------------------------------------
423 -- NoRecomp handlers
424 --------------------------------------------------------------
425
426 norecompOneShot :: NoRecomp HscStatus
427 norecompOneShot _old_iface
428     = do hsc_env <- gets compHscEnv
429          liftIO $ do
430          dumpIfaceStats hsc_env
431          return HscNoRecomp
432
433 norecompBatch :: NoRecomp (HscStatus, ModIface, ModDetails)
434 norecompBatch = norecompWorker HscNoRecomp False
435
436 norecompInteractive :: NoRecomp (InteractiveStatus, ModIface, ModDetails)
437 norecompInteractive = norecompWorker InteractiveNoRecomp True
438
439 norecompWorker :: a -> Bool -> NoRecomp (a, ModIface, ModDetails)
440 norecompWorker a _isInterp old_iface
441     = do hsc_env <- gets compHscEnv
442          liftIO $ do
443          new_details <- {-# SCC "tcRnIface" #-}
444                         initIfaceCheck hsc_env $
445                         typecheckIface old_iface
446          dumpIfaceStats hsc_env
447          return (a, old_iface, new_details)
448
449 --------------------------------------------------------------
450 -- Progress displayers.
451 --------------------------------------------------------------
452
453 oneShotMsg :: Maybe (Int,Int) -> Bool -> Comp ()
454 oneShotMsg _mb_mod_index recomp
455     = do hsc_env <- gets compHscEnv
456          liftIO $ do
457          if recomp
458             then return ()
459             else compilationProgressMsg (hsc_dflags hsc_env) $
460                      "compilation IS NOT required"
461
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)
469          liftIO $ do
470          if recomp
471             then showMsg "Compiling "
472             else if verbosity (hsc_dflags hsc_env) >= 2
473                     then showMsg "Skipping  "
474                     else return ()
475
476 --------------------------------------------------------------
477 -- FrontEnds
478 --------------------------------------------------------------
479 hscFileFrontEnd :: Comp (Maybe TcGblEnv)
480 hscFileFrontEnd =
481     do hsc_env <- gets compHscEnv
482        mod_summary <- gets compModSummary
483        liftIO $ do
484              -------------------
485              -- PARSE
486              -------------------
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
491        case maybe_parsed of
492          Left err
493              -> do printBagOfErrors dflags (unitBag err)
494                    return Nothing
495          Right rdr_module
496              -------------------
497              -- RENAME and TYPECHECK
498              -------------------
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
504
505 --------------------------------------------------------------
506 -- Desugaring
507 --------------------------------------------------------------
508
509 hscDesugar :: TcGblEnv -> Comp (Maybe ModGuts)
510 hscDesugar tc_result
511   = do mod_summary <- gets compModSummary
512        hsc_env <- gets compHscEnv
513        liftIO $ do
514           -------------------
515           -- DESUGAR
516           -------------------
517        ds_result   <- {-# SCC "DeSugar" #-} 
518                       deSugar hsc_env (ms_location mod_summary) tc_result
519        return ds_result
520
521 --------------------------------------------------------------
522 -- Simplifiers
523 --------------------------------------------------------------
524
525 hscSimplify :: ModGuts -> Comp ModGuts
526 hscSimplify ds_result
527   = do hsc_env <- gets compHscEnv
528        liftIO $ do
529            -------------------
530            -- SIMPLIFY
531            -------------------
532        simpl_result <- {-# SCC "Core2Core" #-}
533                        core2core hsc_env ds_result
534        return simpl_result
535
536 --------------------------------------------------------------
537 -- Interface generators
538 --------------------------------------------------------------
539
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
547        liftIO $ do
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)
555
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
561        liftIO $ do
562             -------------------
563             -- TIDY
564             -------------------
565        (cg_guts, details) <- {-# SCC "CoreTidy" #-}
566                              tidyProgram hsc_env simpl_result
567
568             -------------------
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
583
584             -------------------
585             -- Return the prepared code.
586        return (new_iface, no_change, details, cg_guts)
587
588 --------------------------------------------------------------
589 -- BackEnd combinators
590 --------------------------------------------------------------
591
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
597          liftIO $ do
598          unless no_change
599            $ writeIfaceFile dflags (ms_location mod_summary) iface
600          return (iface, details, a)
601
602 hscIgnoreIface :: (ModIface, Bool, ModDetails, a) -> Comp (ModIface, ModDetails, a)
603 hscIgnoreIface (iface, _no_change, details, a)
604     = return (iface, details, a)
605
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))
610
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))
616
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))
622
623 -- Compile to hard-code.
624 hscCompile :: CgGuts -> Comp Bool
625 hscCompile cgguts
626     = do hsc_env <- gets compHscEnv
627          mod_summary <- gets compModSummary
628          liftIO $ do
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,
633                      cg_tycons   = tycons,
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
643
644          -------------------
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
657                               stg_binds hpc_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 
665                 dependencies rawcmms
666          return stub_c_exists
667
668 hscInteractive :: (ModIface, ModDetails, CgGuts)
669                -> Comp (Maybe (InteractiveStatus, ModIface, ModDetails))
670 #ifdef GHCI
671 hscInteractive (iface, details, cgguts)
672     = do hsc_env <- gets compHscEnv
673          mod_summary <- gets compModSummary
674          liftIO $ do
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,
679                      cg_tycons   = tycons,
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
687
688          -------------------
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))
699 #else
700 hscInteractive _ = panic "GHC not compiled with interpreter"
701 #endif
702
703 ------------------------------
704
705 hscCmmFile :: DynFlags -> FilePath -> IO Bool
706 hscCmmFile dflags filename = do
707   maybe_cmm <- parseCmmFile dflags filename
708   case maybe_cmm of
709     Nothing -> return False
710     Just cmm -> do
711         cmms <- optionallyConvertAndOrCPS dflags [cmm]
712         rawCmms <- cmmToRawCmm cmms
713         codeOutput dflags no_mod no_loc NoStubs [] rawCmms
714         return True
715   where
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" }
720
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
726                else return 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
731                else return cmms
732        return cmms
733
734
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
743                      return $ cfopts g
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)
751        return cvt
752        -- return cmm -- don't use the conversion
753
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
760
761         -- sometimes we already have the buffer in memory, perhaps
762         -- because we needed to parse the imports out of it, or get the 
763         -- module name.
764       buf <- case maybe_src_buf of
765                 Just b  -> return b
766                 Nothing -> hGetStringBuffer src_filename
767
768       let loc  = mkSrcLoc (mkFastString src_filename) 1 0
769
770       case unP parseModule (mkPState buf loc dflags) of {
771
772         PFailed span err -> return (Left (mkPlainErrMsg span err));
773
774         POk pst rdr_module -> do {
775
776       let {ms = getMessages pst};
777       printErrorsAndWarnings dflags ms;
778       when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
779       
780       dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
781       
782       dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
783                            (ppSourceStats False rdr_module) ;
784       
785       return (Right rdr_module)
786         -- ToDo: free the string buffer later.
787       }}
788
789
790 myCoreToStg :: DynFlags -> Module -> [CoreBind]
791             -> IO ( [(StgBinding,[(Id,[Id])])]  -- output program
792                   , CollectedCCs) -- cost centre info (declared and used)
793
794 myCoreToStg dflags this_mod prepd_binds
795  = do 
796       stg_binds <- {-# SCC "Core2Stg" #-}
797              coreToStg (thisPackage dflags) prepd_binds
798
799       (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
800              stg2stg dflags this_mod stg_binds
801
802       return (stg_binds2, cost_centre_info)
803 \end{code}
804
805
806 %************************************************************************
807 %*                                                                      *
808 \subsection{Compiling a do-statement}
809 %*                                                                      *
810 %************************************************************************
811
812 When the UnlinkedBCOExpr is linked you get an HValue of type
813         IO [HValue]
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.
816
817 A naked expression returns a singleton Name [it].
818
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, ...]
822                                         bindings: [x,y,...]
823
824         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
825                                         bindings: [x,y,...]
826
827         expr (of IO type)       ==>     expr >>= \ v -> return [v]
828           [NB: result not printed]      bindings: [it]
829           
830
831         expr (of non-IO type, 
832           result showable)      ==>     let v = expr in print v >> return [v]
833                                         bindings: [it]
834
835         expr (of non-IO type, 
836           result not showable)  ==>     error
837
838 \begin{code}
839 #ifdef GHCI
840 hscStmt         -- Compile a stmt all the way to an HValue, but don't run it
841   :: HscEnv
842   -> String                     -- The statement
843   -> IO (Maybe ([Id], HValue))
844
845 hscStmt hsc_env stmt
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
851
852                 -- Rename and typecheck it
853           let icontext = hsc_IC hsc_env
854         ; maybe_tc_result <- tcRnStmt hsc_env icontext parsed_stmt
855
856         ; case maybe_tc_result of {
857                 Nothing -> return Nothing ;
858                 Just (ids, tc_expr) -> do {
859
860                 -- Desugar it
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
864         
865         ; case mb_ds_expr of {
866                 Nothing -> return Nothing ;
867                 Just ds_expr -> do {
868
869                 -- Then desugar, code gen, and link it
870         ; let src_span = srcLocSpan interactiveSrcLoc
871         ; hval <- compileExpr hsc_env src_span ds_expr
872
873         ; return (Just (ids, hval))
874         }}}}}}}
875
876 hscTcExpr       -- Typecheck an expression (but don't run it)
877   :: HscEnv
878   -> String                     -- The expression
879   -> IO (Maybe Type)
880
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)) ;
889                                 return Nothing } ;
890              } }
891
892 hscKcType       -- Find the kind of a type
893   :: HscEnv
894   -> String                     -- The type
895   -> IO (Maybe Kind)
896
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 } }
903 #endif
904 \end{code}
905
906 \begin{code}
907 #ifdef GHCI
908 hscParseStmt :: DynFlags -> String -> IO (Maybe (Maybe (LStmt RdrName)))
909 hscParseStmt = hscParseThing parseStmt
910
911 hscParseType :: DynFlags -> String -> IO (Maybe (LHsType RdrName))
912 hscParseType = hscParseThing parseType
913 #endif
914
915 hscParseIdentifier :: DynFlags -> String -> IO (Maybe (Located RdrName))
916 hscParseIdentifier = hscParseThing parseIdentifier
917
918 hscParseThing :: Outputable thing
919               => Lexer.P thing
920               -> DynFlags -> String
921               -> IO (Maybe thing)
922         -- Nothing => Parse error (message already printed)
923         -- Just x  => success
924 hscParseThing parser dflags str
925  = showPass dflags "Parser" >>
926       {-# SCC "Parser" #-} do
927
928       buf <- stringToStringBuffer str
929
930       let loc  = mkSrcLoc (fsLit "<interactive>") 1 0
931
932       case unP parser (mkPState buf loc dflags) of {
933
934         PFailed span err -> do { printError span err;
935                                  return Nothing };
936
937         POk pst thing -> do {
938
939       let {ms = getMessages pst};
940       printErrorsAndWarnings dflags ms;
941       when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
942
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);
946       return (Just thing)
947       }}
948 \end{code}
949
950 %************************************************************************
951 %*                                                                      *
952         Desugar, simplify, convert to bytecode, and link an expression
953 %*                                                                      *
954 %************************************************************************
955
956 \begin{code}
957 #ifdef GHCI
958 compileExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
959
960 compileExpr hsc_env srcspan ds_expr
961   = do  { let { dflags  = hsc_dflags hsc_env ;
962                 lint_on = dopt Opt_DoCoreLinting dflags }
963               
964                 -- Simplify it
965         ; simpl_expr <- simplifyExpr dflags ds_expr
966
967                 -- Tidy it (temporary, until coreSat does cloning)
968         ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
969
970                 -- Prepare for codegen
971         ; prepd_expr <- corePrepExpr dflags tidy_expr
972
973                 -- Lint if necessary
974                 -- ToDo: improve SrcLoc
975         ; if lint_on then 
976                 let ictxt = hsc_IC hsc_env
977                     tyvars = varSetElems (ic_tyvars ictxt)
978                 in
979                 case lintUnfolding noSrcLoc tyvars prepd_expr of
980                    Just err -> pprPanic "compileExpr" err
981                    Nothing  -> return ()
982           else
983                 return ()
984
985                 -- Convert to BCOs
986         ; bcos <- coreExprToBCOs dflags prepd_expr
987
988                 -- link it
989         ; hval <- linkExpr hsc_env srcspan bcos
990
991         ; return hval
992      }
993 #endif
994 \end{code}
995
996
997 %************************************************************************
998 %*                                                                      *
999         Statistics on reading interfaces
1000 %*                                                                      *
1001 %************************************************************************
1002
1003 \begin{code}
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"
1009                     (ifaceStats eps) }
1010   where
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
1014 \end{code}
1015
1016 %************************************************************************
1017 %*                                                                      *
1018         Progress Messages: Module i of n
1019 %*                                                                      *
1020 %************************************************************************
1021
1022 \begin{code}
1023 showModuleIndex :: Maybe (Int, Int) -> String
1024 showModuleIndex Nothing = ""
1025 showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] "
1026     where
1027         n_str = show n
1028         i_str = show i
1029         padded = replicate (length n_str - length i_str) ' ' ++ i_str
1030 \end{code}
1031