HscMain.lhs 51.8 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 4
%
\begin{code}
5
-- | Main API for compiling plain Haskell source code.
6
--
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
-- This module implements compilation of a Haskell source.  It is
-- /not/ concerned with preprocessing of source files; this is handled
-- in "DriverPipeline".
--
-- There are various entry points depending on what mode we're in:
-- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
-- "interactive" mode (GHCi).  There are also entry points for
-- individual passes: parsing, typechecking/renaming, desugaring, and
-- simplification.
--
-- All the functions here take an 'HscEnv' as a parameter, but none of
-- them return a new one: 'HscEnv' is treated as an immutable value
-- from here on in (although it has mutable components, for the
-- caches).
--
-- Warning messages are dealt with consistently throughout this API:
-- during compilation warnings are collected, and before any function
-- in @HscMain@ returns, the warnings are either printed, or turned
-- into a real compialtion error if the @-Werror@ flag is enabled.
26
--
27
module HscMain
28 29 30 31 32 33
    ( 
    -- * Making an HscEnv
      newHscEnv

    -- * Compiling complete source files
    , Compiler
34
    , HscStatus' (..)
35
    , InteractiveStatus, HscStatus
36 37 38 39 40 41 42 43
    , hscCompileOneShot
    , hscCompileBatch
    , hscCompileNothing
    , hscCompileInteractive
    , hscCompileCmmFile
    , hscCompileCore

    -- * Running passes separately
44 45 46
    , hscParse
    , hscTypecheckRename
    , hscDesugar
47 48
    , makeSimpleIface
    , makeSimpleDetails
49 50 51 52 53 54 55 56 57 58 59 60 61
    , hscSimplify -- ToDo, shouldn't really export this

    -- ** Backends
    , hscOneShotBackendOnly
    , hscBatchBackendOnly
    , hscNothingBackendOnly
    , hscInteractiveBackendOnly

    -- * Support for interactive evaluation
    , hscParseIdentifier
    , hscTcRcLookupName
    , hscTcRnGetInfo
#ifdef GHCI
62
    , hscRnImportDecls
63 64
    , hscGetModuleExports
    , hscTcRnLookupRdrName
vivian's avatar
vivian committed
65 66
    , hscStmt, hscStmtWithLocation
    , hscTcExpr, hscImport, hscKcType
67 68 69
    , hscCompileCoreExpr
#endif

70
    ) where
71

72
#ifdef GHCI
73 74
import ByteCodeGen	( byteCodeGen, coreExprToBCOs )
import Linker		( HValue, linkExpr )
75
import CoreTidy		( tidyExpr )
76 77
import Type		( Type )
import TcType           ( tyVarsOfTypes )
78
import PrelNames	( iNTERACTIVE )
79
import {- Kind parts of -} Type		( Kind )
80
import Id      	     	( idType )
81
import CoreLint		( lintUnfolding )
82
import DsMeta		( templateHaskellNames )
83
import VarSet
84
import VarEnv		( emptyTidyEnv )
85
import Panic
86 87
#endif

88
import Id		( Id )
89 90
import Module
import Packages
91 92
import RdrName
import HsSyn
93
import CoreSyn
Ian Lynagh's avatar
Ian Lynagh committed
94
import StringBuffer
95
import Parser
96 97 98
import Lexer hiding (getDynFlags)
import SrcLoc
import TcRnDriver
99
import TcIface		( typecheckIface )
100
import TcRnMonad
101 102 103
import IfaceEnv		( initNameCache )
import LoadIface	( ifaceStats, initExternalPackageState )
import PrelInfo		( wiredInThings, basicKnownKeyNames )
104
import MkIface
105 106
import Desugar
import SimplCore
107
import TidyPgm
108
import CorePrep
109
import CoreToStg	( coreToStg )
110
import qualified StgCmm	( codeGen )
111 112
import StgSyn
import CostCentre
113 114
import ProfInit
import TyCon            ( TyCon, isDataTyCon )
115
import Name		( Name, NamedThing(..) )
116 117
import SimplStg		( stg2stg )
import CodeGen		( codeGen )
118
import OldCmm           ( Cmm )
119
import PprCmm		( pprCmms )
120
import CmmParse		( parseCmmFile )
121
import CmmBuildInfoTables
122
import CmmPipeline
123
import CmmInfo
124
import OptimizationFuel ( initOptFuelState )
125
import CmmCvt
126
import CmmContFlowOpt   ( runCmmContFlowOpts )
127
import CodeOutput
128
import NameEnv          ( emptyNameEnv )
129 130 131
import NameSet          ( emptyNameSet )
import InstEnv
import FamInstEnv       ( emptyFamInstEnv )
132
import Fingerprint      ( Fingerprint )
133

134
import DynFlags
135
import ErrUtils
136
import UniqSupply	( mkSplitUniqSupply )
137

138
import Outputable
139
import HscStats		( ppSourceStats )
140
import HscTypes
141
import MkExternalCore	( emitExternalCore )
142
import FastString
143
import UniqFM		( emptyUFM )
144
import UniqSupply       ( initUs_ )
145
import Bag
146
import Exception
147
-- import MonadUtils
Simon Marlow's avatar
Simon Marlow committed
148 149

import Control.Monad
150
-- import System.IO
Simon Marlow's avatar
Simon Marlow committed
151
import Data.IORef
152
\end{code}
153
#include "HsVersions.h"
154

155 156 157

%************************************************************************
%*									*
158 159 160 161 162
		Initialisation
%*									*
%************************************************************************

\begin{code}
163 164
newHscEnv :: DynFlags -> IO HscEnv
newHscEnv dflags
165
  = do 	{ eps_var <- newIORef initExternalPackageState
166 167 168
        ; us      <- mkSplitUniqSupply 'r'
        ; nc_var  <- newIORef (initNameCache us knownKeyNames)
        ; fc_var  <- newIORef emptyUFM
169 170
	; mlc_var <- newIORef emptyModuleEnv
        ; optFuel <- initOptFuelState
171
	; return (HscEnv { hsc_dflags = dflags,
172 173
			   hsc_targets = [],
			   hsc_mod_graph = [],
174 175 176 177 178 179 180
			   hsc_IC      = emptyInteractiveContext,
			   hsc_HPT     = emptyHomePackageTable,
			   hsc_EPS     = eps_var,
			   hsc_NC      = nc_var,
			   hsc_FC      = fc_var,
			   hsc_MLC     = mlc_var,
			   hsc_OptFuel = optFuel,
181
                           hsc_type_env_var = Nothing } ) }
182

183

184 185 186 187 188
knownKeyNames :: [Name]      -- Put here to avoid loops involving DsMeta,
                             -- where templateHaskellNames are defined
knownKeyNames
  = map getName wiredInThings 
    ++ basicKnownKeyNames
189
#ifdef GHCI
190
    ++ templateHaskellNames
191 192
#endif

193 194
-- -----------------------------------------------------------------------------
-- The Hsc monad: collecting warnings
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))

instance Monad Hsc where
  return a = Hsc $ \_ w -> return (a, w)
  Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
                                 case k a of
                                    Hsc k' -> k' e w1

instance MonadIO Hsc where
  liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)

runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env (Hsc hsc) = do
  (a, w) <- hsc hsc_env emptyBag
  printOrThrowWarnings (hsc_dflags hsc_env) w
  return a

getWarnings :: Hsc WarningMessages
getWarnings = Hsc $ \_ w -> return (w, w)

clearWarnings :: Hsc ()
clearWarnings = Hsc $ \_ _w -> return ((), emptyBag)

logWarnings :: WarningMessages -> Hsc ()
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)

getHscEnv :: Hsc HscEnv
getHscEnv = Hsc $ \e w -> return (e, w)

getDynFlags :: Hsc DynFlags
getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)

handleWarnings :: Hsc ()
handleWarnings = do
  dflags <- getDynFlags
  w <- getWarnings
  liftIO $ printOrThrowWarnings dflags w
  clearWarnings

-- | log warning in the monad, and if there are errors then
-- throw a SourceError exception.
logWarningsReportErrors :: Messages -> Hsc ()
logWarningsReportErrors (warns,errs) = do
  logWarnings warns
  when (not (isEmptyBag errs)) $ do
    liftIO $ throwIO $ mkSrcErr errs

-- | Deal with errors and warnings returned by a compilation step
--
-- In order to reduce dependencies to other parts of the compiler, functions
-- outside the "main" parts of GHC return warnings and errors as a parameter
-- and signal success via by wrapping the result in a 'Maybe' type.  This
-- function logs the returned warnings and propagates errors as exceptions
-- (of type 'SourceError').
--
-- This function assumes the following invariants:
--
--  1. If the second result indicates success (is of the form 'Just x'),
--     there must be no error messages in the first result.
--
--  2. If there are no error messages, but the second result indicates failure
--     there should be warnings in the first result.  That is, if the action
--     failed, it must have been due to the warnings (i.e., @-Werror@).
ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
ioMsgMaybe ioA = do
  ((warns,errs), mb_r) <- liftIO $ ioA
  logWarnings warns
  case mb_r of
    Nothing -> liftIO $ throwIO (mkSrcErr errs)
    Just r  -> ASSERT( isEmptyBag errs ) return r

-- | like ioMsgMaybe, except that we ignore error messages and return
-- 'Nothing' instead.
ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
ioMsgMaybe' ioA = do
  ((warns,_errs), mb_r) <- liftIO $ ioA
  logWarnings warns
  return mb_r

-- -----------------------------------------------------------------------------
-- | Lookup things in the compiler's environment

#ifdef GHCI
hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
hscTcRnLookupRdrName hsc_env rdr_name = 
  runHsc hsc_env $ ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
#endif

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
hscTcRcLookupName hsc_env name = 
  runHsc hsc_env $ ioMsgMaybe' $ tcRnLookupName hsc_env name
    -- ignore errors: the only error we're likely to get is
    -- "name not found", and the Maybe in the return type
    -- is used to indicate that.

hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [Instance]))
hscTcRnGetInfo hsc_env name =
  runHsc hsc_env $ ioMsgMaybe' $ tcRnGetInfo hsc_env name

#ifdef GHCI
hscGetModuleExports :: HscEnv -> Module -> IO (Maybe [AvailInfo])
hscGetModuleExports hsc_env mdl =
  runHsc hsc_env $ ioMsgMaybe' $ getModuleExports hsc_env mdl

-- -----------------------------------------------------------------------------
-- | Rename some import declarations

hscRnImportDecls
        :: HscEnv
        -> Module
        -> [LImportDecl RdrName]
        -> IO GlobalRdrEnv

309 310 311 312 313 314
-- It is important that we use tcRnImports instead of calling rnImports directly
-- because tcRnImports will force-load any orphan modules necessary, making extra
-- instances/family instances visible (GHC #4832)
hscRnImportDecls hsc_env this_mod import_decls
  = runHsc hsc_env $ ioMsgMaybe $ initTc hsc_env HsSrcFile False this_mod $
          fmap tcg_rdr_env $ tcRnImports hsc_env this_mod import_decls
315

316 317
#endif

318
-- -----------------------------------------------------------------------------
319
-- | parse a file, returning the abstract syntax
320 321 322 323 324 325 326 327 328 329

hscParse :: HscEnv -> ModSummary -> IO (Located (HsModule RdrName))
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
hscParse' :: ModSummary -> Hsc (Located (HsModule RdrName))
hscParse' mod_summary
 = do
   dflags <- getDynFlags
   let 
330 331
       src_filename  = ms_hspp_file mod_summary
       maybe_src_buf = ms_hspp_buf  mod_summary
332

333 334 335 336 337 338 339 340 341 342 343
   --------------------------  Parser  ----------------
   liftIO $ showPass dflags "Parser"
   {-# SCC "Parser" #-} do

	-- sometimes we already have the buffer in memory, perhaps
	-- because we needed to parse the imports out of it, or get the
	-- module name.
   buf <- case maybe_src_buf of
            Just b  -> return b
            Nothing -> liftIO $ hGetStringBuffer src_filename

Ian Lynagh's avatar
Ian Lynagh committed
344
   let loc  = mkRealSrcLoc (mkFastString src_filename) 1 1
345

346
   case unP parseModule (mkPState dflags buf loc) of
347
     PFailed span err ->
348
         liftIO $ throwOneError (mkPlainErrMsg span err)
349 350

     POk pst rdr_module -> do
351 352 353 354 355 356
         logWarningsReportErrors (getMessages pst)
         liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
                                ppr rdr_module
         liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
                                ppSourceStats False rdr_module
         return rdr_module
357
          -- ToDo: free the string buffer later.
358

359 360 361
-- XXX: should this really be a Maybe X?  Check under which circumstances this
-- can become a Nothing and decide whether this should instead throw an
-- exception/signal an error.
362 363
type RenamedStuff = 
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
364
                Maybe LHsDocString))
365

366
-- | Rename and typecheck a module, additionally returning the renamed syntax
367 368 369 370 371
hscTypecheckRename :: HscEnv -> ModSummary -> Located (HsModule RdrName)
                   -> IO (TcGblEnv, RenamedStuff)
hscTypecheckRename hsc_env mod_summary rdr_module
  = runHsc hsc_env $ do
      tc_result
372
          <- {-# SCC "Typecheck-Rename" #-}
373 374
              ioMsgMaybe $ 
                  tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
375

376 377 378
      let -- This 'do' is in the Maybe monad!
          rn_info = do decl <- tcg_rn_decls tc_result
                       let imports = tcg_rn_imports tc_result
379
                           exports = tcg_rn_exports tc_result
380
                           doc_hdr  = tcg_doc_hdr tc_result
381
                       return (decl,imports,exports,doc_hdr)
382

383
      return (tc_result, rn_info)
384 385

-- | Convert a typechecked module to Core
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
hscDesugar hsc_env mod_summary tc_result
  = runHsc hsc_env $ hscDesugar' mod_summary tc_result

hscDesugar' :: ModSummary -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_summary tc_result
 = do
      hsc_env <- getHscEnv
      r <- ioMsgMaybe $ 
             deSugar hsc_env (ms_location mod_summary) tc_result

      handleWarnings
                -- always check -Werror after desugaring, this is 
                -- the last opportunity for warnings to arise before
                -- the backend.
      return r
402 403 404 405 406 407

-- | Make a 'ModIface' from the results of typechecking.  Used when
-- not optimising, and the interface doesn't need to contain any
-- unfoldings or other cross-module optimisation info.
-- ToDo: the old interface is only needed to get the version numbers,
-- we should use fingerprint versions instead.
408
makeSimpleIface :: HscEnv -> 
409
                   Maybe ModIface -> TcGblEnv -> ModDetails
410 411 412 413 414
                -> IO (ModIface,Bool)
makeSimpleIface hsc_env maybe_old_iface tc_result details
  = runHsc hsc_env $
     ioMsgMaybe $ 
       mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
415 416 417

-- | Make a 'ModDetails' from the results of typechecking.  Used when
-- typechecking only, as opposed to full compilation.
418 419
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
420 421
\end{code}

422 423 424
%************************************************************************
%*									*
		The main compiler pipeline
425 426 427
%*									*
%************************************************************************

428 429 430 431 432 433
                   --------------------------------
                        The compilation proper
                   --------------------------------


It's the task of the compilation proper to compile Haskell, hs-boot and
dterei's avatar
dterei committed
434
core files to either byte-code, hard-code (C, asm, LLVM, ect) or to
435 436
nothing at all (the module is still parsed and type-checked. This
feature is mostly used by IDE's and the likes).
437 438 439 440 441
Compilation can happen in either 'one-shot', 'batch', 'nothing',
or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode
targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
targets byte-code.
The modes are kept separate because of their different types and meanings.
442 443 444
In 'one-shot' mode, we're only compiling a single file and can therefore
discard the new ModIface and ModDetails. This is also the reason it only
targets hard-code; compiling to byte-code or nothing doesn't make sense
445 446 447 448 449 450 451 452 453 454 455
when we discard the result.
'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
and ModDetails. 'Batch' mode doesn't target byte-code since that require
us to return the newly compiled byte-code.
'Nothing' mode has exactly the same type as 'batch' mode but they're still
kept separate. This is because compiling to nothing is fairly special: We
don't output any interface files, we don't run the simplifier and we don't
generate any code.
'Interactive' mode is similar to 'batch' mode except that we return the
compiled byte-code together with the ModIface and ModDetails.

456 457 458
Trying to compile a hs-boot file to byte-code will result in a run-time
error. This is the only thing that isn't caught by the type-system.

459
\begin{code}
460

461
-- Status of a compilation to hard-code or nothing.
462
data HscStatus' a
463
    = HscNoRecomp
464
    | HscRecomp
465 466
       (Maybe FilePath)
            -- Has stub files.  This is a hack. We can't compile C files here
467 468 469 470 471 472 473 474
            -- since it's done in DriverPipeline. For now we just return True
            -- if we want the caller to compile them for us.
       a

-- This is a bit ugly.  Since we use a typeclass below and would like to avoid
-- functional dependencies, we have to parameterise the typeclass over the
-- result type.  Therefore we need to artificially distinguish some types.  We
-- do this by adding type tags which will simply be ignored by the caller.
475
type HscStatus         = HscStatus' ()
476 477
type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
    -- INVARIANT: result is @Nothing@ <=> input was a boot file
478

479 480 481
type OneShotResult     = HscStatus
type BatchResult       = (HscStatus, ModIface, ModDetails)
type NothingResult     = (HscStatus, ModIface, ModDetails)
482
type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
483 484

-- FIXME: The old interface and module index are only using in 'batch' and
David Himmelstrup's avatar
David Himmelstrup committed
485
--        'interactive' mode. They should be removed from 'oneshot' mode.
486
type Compiler result =  HscEnv
487 488 489 490
                     -> ModSummary
                     -> Bool                -- True <=> source unchanged
                     -> Maybe ModIface      -- Old interface, if available
                     -> Maybe (Int,Int)     -- Just (i,n) <=> module i of n (for msgs)
491
                     -> IO result
492

493 494 495
data HsCompiler a
  = HsCompiler {
    -- | Called when no recompilation is necessary.
496 497
    hscNoRecomp :: ModIface
                -> Hsc a,
498 499

    -- | Called to recompile the module.
500 501
    hscRecompile :: ModSummary -> Maybe Fingerprint
                 -> Hsc a,
502

503 504
    hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
               -> Hsc a,
505

506
    -- | Code generation for Boot modules.
507 508
    hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
                     -> Hsc a,
509 510

    -- | Code generation for normal modules.
511 512
    hscGenOutput :: ModGuts  -> ModSummary -> Maybe Fingerprint
                 -> Hsc a
513 514
  }

515 516
genericHscCompile :: HsCompiler a
                  -> (HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ())
517 518
                  -> HscEnv -> ModSummary -> Bool
                  -> Maybe ModIface -> Maybe (Int, Int)
519 520 521 522 523
                  -> IO a
genericHscCompile compiler hscMessage hsc_env
                  mod_summary source_unchanged
                  mb_old_iface0 mb_mod_index
 = do
524 525
     (recomp_reqd, mb_checked_iface)
         <- {-# SCC "checkOldIface" #-}
526 527
            checkOldIface hsc_env mod_summary 
                          source_unchanged mb_old_iface0
528 529 530 531 532 533
     -- save the interface that comes back from checkOldIface.
     -- In one-shot mode we don't have the old iface until this
     -- point, when checkOldIface reads it from the disk.
     let mb_old_hash = fmap mi_iface_hash mb_checked_iface
     case mb_checked_iface of
       Just iface | not recomp_reqd
534 535
           -> do hscMessage hsc_env mb_mod_index False mod_summary
                 runHsc hsc_env $ hscNoRecomp compiler iface
536
       _otherwise
537 538
           -> do hscMessage hsc_env mb_mod_index True mod_summary
                 runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash
539

540 541
hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
hscCheckRecompBackend compiler tc_result 
542 543
                   hsc_env mod_summary source_unchanged mb_old_iface _m_of_n
  = do
544 545
     (recomp_reqd, mb_checked_iface)
         <- {-# SCC "checkOldIface" #-}
546 547
            checkOldIface hsc_env mod_summary
                          source_unchanged mb_old_iface
548 549 550 551

     let mb_old_hash = fmap mi_iface_hash mb_checked_iface
     case mb_checked_iface of
       Just iface | not recomp_reqd
552 553 554
           -> runHsc hsc_env $ 
                 hscNoRecomp compiler
                             iface{ mi_globals = Just (tcg_rdr_env tc_result) }
555
       _otherwise
556 557
           -> runHsc hsc_env $
                 hscBackend compiler tc_result mod_summary mb_old_hash
558

559
genericHscRecompile :: HsCompiler a
560
                    -> ModSummary -> Maybe Fingerprint
561
                    -> Hsc a
562
genericHscRecompile compiler mod_summary mb_old_hash
563 564 565 566
  | ExtCoreFile <- ms_hsc_src mod_summary =
      panic "GHC does not currently support reading External Core files"
  | otherwise = do
      tc_result <- hscFileFrontEnd mod_summary
567 568
      hscBackend compiler tc_result mod_summary mb_old_hash

569
genericHscBackend :: HsCompiler a
570
                  -> TcGblEnv -> ModSummary -> Maybe Fingerprint
571
                  -> Hsc a
572 573 574 575
genericHscBackend compiler tc_result mod_summary mb_old_hash
  | HsBootFile <- ms_hsc_src mod_summary =
      hscGenBootOutput compiler tc_result mod_summary mb_old_hash
  | otherwise = do
576
      guts <- hscDesugar' mod_summary tc_result
577
      hscGenOutput compiler guts mod_summary mb_old_hash
578

579 580 581 582 583
compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
  runHsc hsc_env $
    hscBackend comp tcg ms' Nothing

584 585 586 587
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

588 589 590 591
hscOneShotCompiler :: HsCompiler OneShotResult
hscOneShotCompiler =
  HsCompiler {

592
    hscNoRecomp = \_old_iface -> do
593 594
      hsc_env <- getHscEnv
      liftIO $ dumpIfaceStats hsc_env
595 596 597 598
      return HscNoRecomp

  , hscRecompile = genericHscRecompile hscOneShotCompiler

599
  , hscBackend = \ tc_result mod_summary mb_old_hash -> do
600 601
       dflags <- getDynFlags
       case hscTarget dflags of
602
         HscNothing -> return (HscRecomp Nothing ())
603
         _otherw    -> genericHscBackend hscOneShotCompiler
604
                                         tc_result mod_summary mb_old_hash
605

606 607 608
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
       (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
       hscWriteIface iface changed mod_summary
609
       return (HscRecomp Nothing ())
610 611

  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
612 613
       guts <- hscSimplify' guts0
       (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface
614 615 616 617
       hscWriteIface iface changed mod_summary
       hasStub <- hscGenHardCode cgguts mod_summary
       return (HscRecomp hasStub ())
  }
618

619
-- Compile Haskell, boot and extCore in OneShot mode.
620
hscCompileOneShot :: Compiler OneShotResult
621 622
hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  = do
623 624
       -- One-shot mode needs a knot-tying mutable variable for interface
       -- files.  See TcRnTypes.TcGblEnv.tcg_type_env_var.
625
      type_env_var <- newIORef emptyNameEnv
626 627 628 629 630 631 632 633
      let
         mod = ms_mod mod_summary
         hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
      ---
      genericHscCompile hscOneShotCompiler
                        oneShotMsg hsc_env' mod_summary src_changed
                        mb_old_iface mb_i_of_n

634

635 636 637
hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
hscOneShotBackendOnly = compilerBackend hscOneShotCompiler

638 639
--------------------------------------------------------------

640 641 642
hscBatchCompiler :: HsCompiler BatchResult
hscBatchCompiler =
  HsCompiler {
643

644
    hscNoRecomp = \iface -> do
645 646
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
647

648
  , hscRecompile = genericHscRecompile hscBatchCompiler
649

650 651
  , hscBackend = genericHscBackend hscBatchCompiler

652
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
653
       (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
654
       hscWriteIface iface changed mod_summary
655
       return (HscRecomp Nothing (), iface, details)
656

657
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
658 659
       guts <- hscSimplify' guts0
       (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface
660 661 662 663
       hscWriteIface iface changed mod_summary
       hasStub <- hscGenHardCode cgguts mod_summary
       return (HscRecomp hasStub (), iface, details)
  }
664

665
-- Compile Haskell, boot and extCore in batch mode.
666
hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
667
hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
668

669 670 671
hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler

672 673
--------------------------------------------------------------

674 675 676
hscInteractiveCompiler :: HsCompiler InteractiveResult
hscInteractiveCompiler =
  HsCompiler {
677
    hscNoRecomp = \iface -> do
678 679
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
680

681
  , hscRecompile = genericHscRecompile hscInteractiveCompiler
682

683 684 685 686
  , hscBackend = genericHscBackend hscInteractiveCompiler

  , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
       (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
687
       return (HscRecomp Nothing Nothing, iface, details)
688

689
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
690 691
       guts <- hscSimplify' guts0
       (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
692 693
       hscInteractive (iface, details, cgguts) mod_summary
  }
694 695 696

-- Compile Haskell, extCore to bytecode.
hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
697
hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
698

699 700 701
hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler

702 703
--------------------------------------------------------------

704 705 706
hscNothingCompiler :: HsCompiler NothingResult
hscNothingCompiler =
  HsCompiler {
707
    hscNoRecomp = \iface -> do
708 709
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
Simon Marlow's avatar
Simon Marlow committed
710

711
  , hscRecompile = genericHscRecompile hscNothingCompiler
712

713
  , hscBackend = \tc_result _mod_summary mb_old_iface -> do
714
       handleWarnings
715
       (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
716
       return (HscRecomp Nothing (), iface, details)
717

718 719 720
  , hscGenBootOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenBootOutput should not be called"

721 722 723
  , hscGenOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenOutput should not be called"
  }
724

725
-- Type-check Haskell and .hs-boot only (no external core)
726
hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
727
hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
728

729 730 731
hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
hscNothingBackendOnly = compilerBackend hscNothingCompiler

732 733 734 735
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

736 737 738 739
genModDetails :: ModIface -> Hsc ModDetails
genModDetails old_iface
  = do
      hsc_env <- getHscEnv
740
      new_details <- {-# SCC "tcRnIface" #-}
741 742 743
                     liftIO $ initIfaceCheck hsc_env $
                              typecheckIface old_iface
      liftIO $ dumpIfaceStats hsc_env
744
      return new_details
745

746 747 748 749
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

750 751
oneShotMsg :: HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ()
oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
752 753 754 755 756
         if recomp
            then return ()
            else compilationProgressMsg (hsc_dflags hsc_env) $
                     "compilation IS NOT required"

757 758 759
batchMsg :: HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ()
batchMsg hsc_env mb_mod_index recomp mod_summary
  = do
760 761
         let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
                           (showModuleIndex mb_mod_index ++
762
                            msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
763 764
         if recomp
            then showMsg "Compiling "
765
            else if verbosity (hsc_dflags hsc_env) >= 2
766 767
                    then showMsg "Skipping  "
                    else return ()
768

769 770 771
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
772 773

hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
774 775 776
hscFileFrontEnd mod_summary = do
    rdr_module <- hscParse' mod_summary
    hsc_env <- getHscEnv
777 778 779
    tcg_env <-
        {-# SCC "Typecheck-Rename" #-}
        ioMsgMaybe $
780 781
            tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
    dflags <- getDynFlags
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    -- XXX: See Note [SafeHaskell API]
    if safeHaskellOn dflags
        then do
            tcg_env1 <- checkSafeImports dflags hsc_env tcg_env
            if safeLanguageOn dflags
                then do
                    -- we also nuke user written RULES.
                    logWarnings $ warns (tcg_rules tcg_env1)
                    return tcg_env1 { tcg_rules = [] }
                else
                    return tcg_env1

        else
            return tcg_env

    where
        warns rules = listToBag $ map warnRules rules
        warnRules (L loc (HsRule n _ _ _ _ _ _)) =
            mkPlainWarnMsg loc $
                text "Rule \"" <> ftext n <> text "\" ignored" $+$
                text "User defined rules are disabled under SafeHaskell"
803 804 805 806 807 808 809 810 811 812 813

--------------------------------------------------------------
-- SafeHaskell
--------------------------------------------------------------

-- | Validate that safe imported modules are actually safe.
-- For modules in the HomePackage (the package the module we
-- are compiling in resides) this just involves checking its
-- trust type is 'Safe' or 'Trustworthy'. For modules that
-- reside in another package we also must check that the
-- external pacakge is trusted.
814 815 816 817 818 819
--
-- Note [SafeHaskell API]
-- ~~~~~~~~~~~~~~~~~~~~~~
-- XXX: We only call this in hscFileFrontend and don't expose
-- it to the GHC API. External users of GHC can't properly use
-- the GHC API and SafeHaskell.
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
checkSafeImports :: DynFlags -> HscEnv -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags hsc_env tcg_env
    = do
        imps <- mapM condense imports'
        mapM_ checkSafe imps
        return tcg_env
    where
        imp_info = tcg_imports tcg_env     -- ImportAvails
        imports  = imp_mods imp_info       -- ImportedMods
        imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])

        condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
        condense (_, [])   = panic "HscMain.condense: Pattern match failure!"
        condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs
                                return (m, l, s)
        
        -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
        cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
        cond' v1@(m1,_,l1,s1) (_,_,_,s2)
            | s1 /= s2
            = liftIO $ throwIO $ mkSrcErr $ unitBag $ mkPlainErrMsg l1
                    (text "Module" <+> ppr m1 <+> (text $ "is imported"
                        ++ " both as a safe and unsafe import!"))

            | otherwise
            = return v1

        lookup' :: Module -> Hsc (Maybe ModIface)
        lookup' m = do
            hsc_eps <- liftIO $ hscEPS hsc_env
            let pkgIfaceT = eps_PIT hsc_eps
                homePkgT = hsc_HPT hsc_env
                iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
            return iface

        -- | Check the package a module resides in is trusted.
        -- Modules in the home package are trusted but otherwise
        -- we check the packages trust flag.
        packageTrusted :: Module -> Bool
        packageTrusted m
            | thisPackage dflags == modulePackageId m = True
            | otherwise = trusted $ getPackageDetails (pkgState dflags)
                                                      (modulePackageId m)

        -- Is a module a Safe importable? Return Nothing if True, or a String
        -- if it isn't containing the reason it isn't
        isModSafe :: Module -> SrcSpan -> Hsc (Maybe SDoc)
        isModSafe m l = do
            iface <- lookup' m
            case iface of
                -- can't load iface to check trust!
                Nothing -> liftIO $ throwIO $ mkSrcErr $ unitBag $ mkPlainErrMsg l
                            $ text "Can't load the interface file for" <+> ppr m <>
                              text ", to check that it can be safely imported"

                -- got iface, check trust
                Just iface' -> do
                    let trust = getSafeMode $ mi_trust iface'
                        -- check module is trusted
                        safeM = trust `elem` [Sf_Safe, Sf_Trustworthy,
                                            Sf_TrustworthyWithSafeLanguage]
                        -- check package is trusted
                        safeP = packageTrusted m
                    if safeM && safeP
                        then return Nothing
                        else return $ Just $ if safeM
                            then text "The package (" <> ppr (modulePackageId m) <>
                                 text ") the module resides in isn't trusted."
                            else text "The module itself isn't safe."

        checkSafe :: (Module, SrcSpan, IsSafeImport) -> Hsc ()
        checkSafe (_, _, False) = return ()
        checkSafe (m, l, True ) = do
            module_safe <- isModSafe m l
            case module_safe of
                Nothing -> return ()
                Just s  -> liftIO $ throwIO $ mkSrcErr $ unitBag $ mkPlainErrMsg l
                            $ text "Safe import of" <+> ppr m <+> text "can't be met!"
                                <+> s
899

900 901 902
--------------------------------------------------------------
-- Simplifiers
--------------------------------------------------------------
903

904 905 906 907 908 909 910 911
hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts

hscSimplify' :: ModGuts -> Hsc ModGuts
hscSimplify' ds_result
  = do hsc_env <- getHscEnv
       {-# SCC "Core2Core" #-}
         liftIO $ core2core hsc_env ds_result
912 913

--------------------------------------------------------------
914
-- Interface generators
915 916
--------------------------------------------------------------

917
hscSimpleIface :: TcGblEnv
918
               -> Maybe Fingerprint
919
               -> Hsc (ModIface, Bool, ModDetails)
920
hscSimpleIface tc_result mb_old_iface
921 922
  = do 
       hsc_env <- getHscEnv
923
       details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
924
       (new_iface, no_change)
925
           <- {-# SCC "MkFinalIface" #-}
926 927
              ioMsgMaybe $ 
                mkIfaceTc hsc_env mb_old_iface details tc_result
928
       -- And the answer is ...
929 930 931
       liftIO $ dumpIfaceStats hsc_env
       return (new_iface, no_change, details)

932
hscNormalIface :: ModGuts
933
               -> Maybe Fingerprint
934
               -> Hsc (ModIface, Bool, ModDetails, CgGuts)
935
hscNormalIface simpl_result mb_old_iface
936 937
  = do 
       hsc_env <- getHscEnv
938
       (cg_guts, details) <- {-# SCC "CoreTidy" #-}
939
                             liftIO $ tidyProgram hsc_env simpl_result
940 941 942 943 944 945

	    -- BUILD THE NEW ModIface and ModDetails
	    --	and emit external core if necessary
	    -- This has to happen *after* code gen so that the back-end
	    -- info has been set.  Not yet clear if it matters waiting
	    -- until after code output
946
       (new_iface, no_change)
947
	   <- {-# SCC "MkFinalIface" #-}
948 949 950 951
	      ioMsgMaybe $ 
                   mkIface hsc_env mb_old_iface details simpl_result

       -- Emit external core
952 953 954
       -- This should definitely be here and not after CorePrep,
       -- because CorePrep produces unqualified constructor wrapper declarations,
       -- so its output isn't valid External Core (without some preprocessing).
955 956
       liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
       liftIO $ dumpIfaceStats hsc_env
957 958

 	    -- Return the prepared code.
959
       return (new_iface, no_change, details, cg_guts)
960

961
--------------------------------------------------------------
962
-- BackEnd combinators
963 964
--------------------------------------------------------------

965 966
hscWriteIface :: ModIface
              -> Bool
967
              -> ModSummary
968 969
              -> Hsc ()

970
hscWriteIface iface no_change mod_summary
971
    = do dflags <- getDynFlags
972
         unless no_change
973
           $ liftIO $ writeIfaceFile dflags (ms_location mod_summary) iface
974 975

-- | Compile to hard-code.
976
hscGenHardCode :: CgGuts -> ModSummary
977
               -> Hsc (Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
978
hscGenHardCode cgguts mod_summary
979 980 981
  = do
    hsc_env <- getHscEnv
    liftIO $ do
982
         let CgGuts{ -- This is the last use of the ModGuts in a compilation.
983 984 985 986
                     -- From now on, we just use the bits we need.
                     cg_module   = this_mod,
                     cg_binds    = core_binds,
                     cg_tycons   = tycons,
987
                     cg_foreign  = foreign_stubs0,
andy@galois.com's avatar
andy@galois.com committed
988
                     cg_dep_pkgs = dependencies,
989
                     cg_hpc_info = hpc_info } = cgguts
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
             dflags = hsc_dflags hsc_env
             location = ms_location mod_summary
             data_tycons = filter isDataTyCon tycons
             -- cg_tycons includes newtypes, for the benefit of External Core,
             -- but we don't generate any code for newtypes

         -------------------
         -- PREPARE FOR CODE GENERATION
         -- Do saturation and convert to A-normal form
         prepd_binds <- {-# SCC "CorePrep" #-}
                        corePrepPgm dflags core_binds data_tycons ;
         -----------------  Convert to STG ------------------
         (stg_binds, cost_centre_info)
             <- {-# SCC "CoreToStg" #-}
Simon Marlow's avatar
Simon Marlow committed
1004
                myCoreToStg dflags this_mod prepd_binds	
1005

1006 1007 1008
         let prof_init = profilingInitCode this_mod cost_centre_info
             foreign_stubs = foreign_stubs0 `appendStubC` prof_init

1009
         ------------------  Code generation ------------------
1010 1011
         
         cmms <- if dopt Opt_TryNewCodeGen dflags
1012
                 then do cmms <- tryNewCodeGen hsc_env this_mod data_tycons
1013
                                 cost_centre_info
1014
                                 stg_binds hpc_info
1015
                         return cmms
1016 1017
                 else {-# SCC "CodeGen" #-}
                       codeGen dflags this_mod data_tycons
1018
                               cost_centre_info
1019 1020
                               stg_binds hpc_info

1021
         --- Optionally run experimental Cmm transformations ---
1022
         cmms <- optionallyConvertAndOrCPS hsc_env cmms
Thomas Schilling's avatar
Thomas Schilling committed
1023
                 -- unless certain dflags are on, the identity function
1024
         ------------------  Code output -----------------------
1025
         rawcmms <- cmmToRawCmm cmms
1026
         dumpIfSet_dyn dflags Opt_D_dump_raw_cmm "Raw Cmm" (ppr rawcmms)
1027
         (_stub_h_exists, stub_c_exists)
1028
             <- codeOutput dflags this_mod location foreign_stubs 
1029
                dependencies rawcmms
1030 1031
         return stub_c_exists

1032
hscInteractive :: (ModIface, ModDetails, CgGuts)
1033
               -> ModSummary
1034
               -> Hsc (InteractiveStatus, ModIface, ModDetails)
1035
#ifdef GHCI
1036
hscInteractive (iface, details, cgguts) mod_summary
1037 1038
    = do
         dflags <- getDynFlags
1039
         let CgGuts{ -- This is the last use of the ModGuts in a compilation.
1040 1041 1042 1043
                     -- From now on, we just use the bits we need.
                     cg_module   = this_mod,
                     cg_binds    = core_binds,
                     cg_tycons   = tycons,
1044 1045
                     cg_foreign  = foreign_stubs,
                     cg_modBreaks = mod_breaks } = cgguts
1046

1047 1048 1049 1050 1051 1052 1053 1054 1055
             location = ms_location mod_summary
             data_tycons = filter isDataTyCon tycons
             -- cg_tycons includes newtypes, for the benefit of External Core,
             -- but we don't generate any code for newtypes

         -------------------
         -- PREPARE FOR CODE GENERATION
         -- Do saturation and convert to A-normal form
         prepd_binds <- {-# SCC "CorePrep" #-}
1056
                        liftIO $ corePrepPgm dflags core_binds data_tycons ;
1057
         -----------------  Generate byte code ------------------
1058
         comp_bc <- liftIO $ byteCodeGen dflags prepd_binds data_tycons mod_breaks
1059
         ------------------ Create f-x-dynamic C-side stuff ---
1060
         (_istub_h_exists, istub_c_exists) 
1061 1062
             <- liftIO $ outputForeignStubs dflags this_mod
                                            location foreign_stubs
1063 1064
         return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks))
                , iface, details)
1065
#else
1066
hscInteractive _ _ = panic "GHC not compiled with interpreter"
1067 1068
#endif

1069 1070
------------------------------

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
hscCompileCmmFile :: HscEnv -> FilePath -> IO ()
hscCompileCmmFile hsc_env filename
  = runHsc hsc_env $ do
      let dflags = hsc_dflags hsc_env
      cmm <- ioMsgMaybe $ parseCmmFile dflags filename
      liftIO $ do
        cmms <- optionallyConvertAndOrCPS hsc_env [cmm]
        rawCmms <- cmmToRawCmm cmms
        _ <- codeOutput dflags no_mod no_loc NoStubs [] rawCmms
        return ()
1081 1082
  where
	no_mod = panic "hscCmmFile: no_mod"
1083 1084 1085
	no_loc = ModLocation{ ml_hs_file  = Just filename,
                              ml_hi_file  = panic "hscCmmFile: no hi file",
                              ml_obj_file = panic "hscCmmFile: no obj file" }
1086

1087 1088
-------------------- Stuff for new code gen ---------------------

1089
tryNewCodeGen   :: HscEnv -> Module -> [TyCon]
1090 1091 1092 1093
                -> CollectedCCs
                -> [(StgBinding,[(Id,[Id])])]
                -> HpcInfo
                -> IO [Cmm]
1094
tryNewCodeGen hsc_env this_mod data_tycons
1095 1096
              cost_centre_info stg_binds hpc_info =
  do    { let dflags = hsc_dflags hsc_env
1097
        ; prog <- StgCmm.codeGen dflags this_mod data_tycons
1098 1099 1100
                         cost_centre_info stg_binds hpc_info
        ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen" 
                (pprCmms prog)
1101

1102 1103
        -- We are building a single SRT for the entire module, so
        -- we must thread it through all the procedures as we cps-convert them.
1104
        ; us <- mkSplitUniqSupply 'S'
1105 1106
        ; let initTopSRT = initUs_ us emptySRT
        ; (topSRT, prog) <- foldM (cmmPipeline hsc_env) (initTopSRT, []) prog
1107

1108 1109 1110
        ; let prog' = map cmmOfZgraph (srtToData topSRT : prog)
        ; dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" (ppr prog')
        ; return prog' }
1111 1112


1113 1114 1115 1116
optionallyConvertAndOrCPS :: HscEnv -> [Cmm] -> IO [Cmm]
optionallyConvertAndOrCPS hsc_env cmms =
    do let dflags = hsc_dflags hsc_env
        --------  Optionally convert to and from zipper ------
1117
       cmms <- if dopt Opt_ConvertToZipCfgAndBack dflags
1118
               then mapM (testCmmConversion hsc_env) cmms
1119 1120 1121 1122
               else return cmms
       return cmms


1123 1124 1125 1126
testCmmConversion :: HscEnv -> Cmm -> IO Cmm
testCmmConversion hsc_env cmm =
    do let dflags = hsc_dflags hsc_env
       showPass dflags "CmmToCmm"
1127 1128 1129
       dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- pre-conversion" (ppr cmm)
       --continuationC <- cmmCPS dflags abstractC >>= cmmToRawCmm
       us <- mkSplitUniqSupply 'C'
1130 1131 1132 1133 1134 1135 1136 1137
       let zgraph = initUs_ us (cmmToZgraph cmm)
       chosen_graph <-
        if dopt Opt_RunCPSZ dflags
            then do us <- mkSplitUniqSupply 'S'
                    let topSRT = initUs_ us emptySRT
                    (_, [zgraph]) <- cmmPipeline hsc_env (topSRT, []) zgraph
                    return zgraph
            else return (runCmmContFlowOpts zgraph)
1138 1139
       dumpIfSet_dyn dflags Opt_D_dump_cmmz "C-- Zipper Graph" (ppr chosen_graph)
       showPass dflags "Convert from Z back to Cmm"
1140
       let cvt = cmmOfZgraph chosen_graph
1141 1142
       dumpIfSet_dyn dflags Opt_D_dump_cvt_cmm "C-- post-conversion" (ppr cvt)
       return cvt
1143

1144 1145 1146 1147
myCoreToStg :: DynFlags -> Module -> [CoreBind]
            -> IO ( [(StgBinding,[(Id,[Id])])]  -- output program
	          , CollectedCCs) -- cost centre info (declared and used)

Simon Marlow's avatar
Simon Marlow committed
1148
myCoreToStg dflags this_mod prepd_binds
1149
 = do 
1150
      stg_binds <- {-# SCC "Core2Stg" #-}
Simon Marlow's avatar
Simon Marlow committed
1151
	     coreToStg (thisPackage dflags) prepd_binds
1152

1153
      (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-}
Simon Marlow's avatar
Simon Marlow committed
1154
	     stg2stg dflags this_mod stg_binds
1155

1156
      return (stg_binds2, cost_centre_info)
1157 1158
\end{code}

1159

1160 1161
%************************************************************************
%*									*
1162
\subsection{Compiling a do-statement}
1163 1164 1165
%*									*
%************************************************************************

1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
When the UnlinkedBCOExpr is linked you get an HValue of type
	IO [HValue]
When you run it you get a list of HValues that should be 
the same length as the list of names; add them to the ClosureEnv.

A naked expression returns a singleton Name [it].

	What you type			The IO [HValue] that hscStmt returns
	-------------			------------------------------------
	let pat = expr		==> 	let pat = expr in return [coerce HVal x, coerce HVal y, ...]
					bindings: [x,y,...]

	pat <- expr		==> 	expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
					bindings: [x,y,...]

	expr (of IO type)	==>	expr >>= \ v -> return [v]
	  [NB: result not printed]	bindings: [it]
	  

	expr (of non-IO type, 
	  result showable)	==>	let v = expr in print v >> return [v]
	  				bindings: [it]
1188

1189 1190 1191 1192
	expr (of non-IO type, 
	  result not showable)	==>	error

\begin{code}
1193 1194
#ifdef GHCI
hscStmt		-- Compile a stmt all the way to an HValue, but don't run it
1195
  :: HscEnv
1196
  -> String			-- The statement
1197
  -> IO (Maybe ([Id], HValue))
1198
     -- ^ 'Nothing' <==> empty statement (or comment only), but no parse error
vivian's avatar
vivian committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1

hscStmtWithLocation	-- Compile a stmt all the way to an HValue, but don't run it
  :: HscEnv
  -> String			-- The statement
  -> String                     -- the source
  -> Int                        -- ^ starting line
  -> IO (Maybe ([Id], HValue))
     -- ^ 'Nothing' <==> empty statement (or comment only), but no parse error
hscStmtWithLocation hsc_env stmt source linenumber = runHsc hsc_env $ do
    maybe_stmt <- hscParseStmtWithLocation source linenumber stmt
1210 1211 1212 1213 1214 1215
    case maybe_stmt of
      Nothing -> return Nothing
      Just parsed_stmt -> do  -- The real stuff

             -- Rename and typecheck it
	let icontext = hsc_IC hsc_env
1216 1217
	(ids, tc_expr) <- ioMsgMaybe $ 
                            tcRnStmt hsc_env icontext parsed_stmt
1218 1219 1220 1221 1222