HscMain.hs 68.6 KB
Newer Older
dterei's avatar
dterei committed
1 2
-------------------------------------------------------------------------------
--
3
-- | Main API for compiling plain Haskell source code.
4
--
dterei's avatar
dterei committed
5
-- This module implements compilation of a Haskell source. It is
6 7 8 9 10
-- /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
dterei's avatar
dterei committed
11
-- "interactive" mode (GHCi). There are also entry points for
12 13 14 15 16 17 18 19 20 21 22 23
-- 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.
24
--
dterei's avatar
dterei committed
25 26 27 28
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
--
-------------------------------------------------------------------------------

29
module HscMain
dterei's avatar
dterei committed
30
    (
31 32 33 34 35
    -- * Making an HscEnv
      newHscEnv

    -- * Compiling complete source files
    , Compiler
Thomas Schilling's avatar
Thomas Schilling committed
36
    , HscStatus' (..)
37
    , InteractiveStatus, HscStatus
38 39 40 41 42 43 44 45
    , hscCompileOneShot
    , hscCompileBatch
    , hscCompileNothing
    , hscCompileInteractive
    , hscCompileCmmFile
    , hscCompileCore

    -- * Running passes separately
Thomas Schilling's avatar
Thomas Schilling committed
46 47 48
    , hscParse
    , hscTypecheckRename
    , hscDesugar
Simon Marlow's avatar
Simon Marlow committed
49 50
    , makeSimpleIface
    , makeSimpleDetails
51 52 53 54 55 56 57 58 59 60 61 62
    , hscSimplify -- ToDo, shouldn't really export this

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

    -- * Support for interactive evaluation
    , hscParseIdentifier
    , hscTcRcLookupName
    , hscTcRnGetInfo
63
    , hscCheckSafe
dterei's avatar
dterei committed
64
    , hscGetSafe
65
#ifdef GHCI
dterei's avatar
dterei committed
66
    , hscIsGHCiMonad
67
    , hscGetModuleInterface
68
    , hscRnImportDecls
69
    , hscTcRnLookupRdrName
vivian's avatar
vivian committed
70
    , hscStmt, hscStmtWithLocation
71
    , hscDecls, hscDeclsWithLocation
vivian's avatar
vivian committed
72
    , hscTcExpr, hscImport, hscKcType
73 74
    , hscCompileCoreExpr
#endif
75
    ) where
76

77
#ifdef GHCI
78
import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
79
import Linker
80 81
import CoreTidy         ( tidyExpr )
import Type             ( Type )
82
import PrelNames
83 84 85
import {- Kind parts of -} Type         ( Kind )
import CoreLint         ( lintUnfolding )
import DsMeta           ( templateHaskellNames )
86
import VarSet
87
import VarEnv           ( emptyTidyEnv )
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
88
import Panic
89 90

import GHC.Exts
91 92
#endif

93
import Id
94 95
import Module
import Packages
Simon Marlow's avatar
Simon Marlow committed
96 97
import RdrName
import HsSyn
98
import CoreSyn
Ian Lynagh's avatar
Ian Lynagh committed
99
import StringBuffer
100
import Parser
101
import Lexer
102 103
import SrcLoc
import TcRnDriver
104
import TcIface          ( typecheckIface )
105
import TcRnMonad
106 107
import IfaceEnv         ( initNameCache )
import LoadIface        ( ifaceStats, initExternalPackageState )
108
import PrelInfo
Simon Marlow's avatar
Simon Marlow committed
109
import MkIface
110 111
import Desugar
import SimplCore
Simon Marlow's avatar
Simon Marlow committed
112
import TidyPgm
113
import CorePrep
114 115
import CoreToStg        ( coreToStg )
import qualified StgCmm ( codeGen )
116 117
import StgSyn
import CostCentre
118
import ProfInit
119 120
import TyCon
import Name
121 122
import SimplStg         ( stg2stg )
import CodeGen          ( codeGen )
123 124
import qualified OldCmm as Old
import qualified Cmm as New
125
import CmmParse         ( parseCmmFile )
126
import CmmBuildInfoTables
Edward Z. Yang's avatar
Edward Z. Yang committed
127
import CmmPipeline
128
import CmmInfo
129
import CmmCvt
130
import CodeOutput
131
import NameEnv          ( emptyNameEnv )
132 133
import NameSet          ( emptyNameSet )
import InstEnv
134
import FamInstEnv
Thomas Schilling's avatar
Thomas Schilling committed
135
import Fingerprint      ( Fingerprint )
136

137
import DynFlags
138
import ErrUtils
139
import UniqSupply       ( mkSplitUniqSupply )
140

141
import Outputable
142
import HscStats         ( ppSourceStats )
143
import HscTypes
144
import MkExternalCore   ( emitExternalCore )
145
import FastString
146
import UniqFM           ( emptyUFM )
147
import UniqSupply       ( initUs_ )
148
import Bag
Thomas Schilling's avatar
Thomas Schilling committed
149
import Exception
150 151 152
import qualified Stream
import Stream (Stream)

153
import Util
Simon Marlow's avatar
Simon Marlow committed
154

155
import Data.List
Simon Marlow's avatar
Simon Marlow committed
156
import Control.Monad
157
import Data.Maybe
Simon Marlow's avatar
Simon Marlow committed
158
import Data.IORef
159
import System.FilePath as FilePath
160
import System.Directory
dterei's avatar
dterei committed
161

Thomas Schilling's avatar
Thomas Schilling committed
162
#include "HsVersions.h"
163

164

dterei's avatar
dterei committed
165 166 167 168 169
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
170

171
newHscEnv :: DynFlags -> IO HscEnv
172
newHscEnv dflags = do
dterei's avatar
dterei committed
173 174 175 176 177
    eps_var <- newIORef initExternalPackageState
    us      <- mkSplitUniqSupply 'r'
    nc_var  <- newIORef (initNameCache us knownKeyNames)
    fc_var  <- newIORef emptyUFM
    mlc_var <- newIORef emptyModuleEnv
178
    return HscEnv {  hsc_dflags       = dflags,
dterei's avatar
dterei committed
179 180
                     hsc_targets      = [],
                     hsc_mod_graph    = [],
181
                     hsc_IC           = emptyInteractiveContext dflags,
dterei's avatar
dterei committed
182 183 184 185 186
                     hsc_HPT          = emptyHomePackageTable,
                     hsc_EPS          = eps_var,
                     hsc_NC           = nc_var,
                     hsc_FC           = fc_var,
                     hsc_MLC          = mlc_var,
187
                     hsc_type_env_var = Nothing }
Thomas Schilling's avatar
Thomas Schilling committed
188

189

190
knownKeyNames :: [Name]      -- Put here to avoid loops involving DsMeta,
191
knownKeyNames =              -- where templateHaskellNames are defined
dterei's avatar
dterei committed
192
    map getName wiredInThings
dterei's avatar
dterei committed
193
        ++ basicKnownKeyNames
194
#ifdef GHCI
dterei's avatar
dterei committed
195
        ++ templateHaskellNames
196 197
#endif

198
-- -----------------------------------------------------------------------------
199
-- The Hsc monad: Passing an enviornment and warning state
200

dterei's avatar
dterei committed
201
newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
202 203

instance Monad Hsc where
dterei's avatar
dterei committed
204 205 206 207
    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
208 209

instance MonadIO Hsc where
dterei's avatar
dterei committed
210
    liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
211

dterei's avatar
dterei committed
212 213 214
instance Functor Hsc where
    fmap f m = m >>= \a -> return $ f a

215 216
runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env (Hsc hsc) = do
dterei's avatar
dterei committed
217 218 219
    (a, w) <- hsc hsc_env emptyBag
    printOrThrowWarnings (hsc_dflags hsc_env) w
    return a
220

221 222 223 224 225 226 227
-- A variant of runHsc that switches in the DynFlags from the
-- InteractiveContext before running the Hsc computation.
--
runInteractiveHsc :: HscEnv -> Hsc a -> IO a
runInteractiveHsc hsc_env =
  runHsc (hsc_env { hsc_dflags = ic_dflags (hsc_IC hsc_env) })

228
getWarnings :: Hsc WarningMessages
dterei's avatar
dterei committed
229
getWarnings = Hsc $ \_ w -> return (w, w)
230 231

clearWarnings :: Hsc ()
dterei's avatar
dterei committed
232
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
233 234

logWarnings :: WarningMessages -> Hsc ()
dterei's avatar
dterei committed
235
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
236 237

getHscEnv :: Hsc HscEnv
dterei's avatar
dterei committed
238
getHscEnv = Hsc $ \e w -> return (e, w)
239

240 241
instance HasDynFlags Hsc where
    getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
242 243 244

handleWarnings :: Hsc ()
handleWarnings = do
dterei's avatar
dterei committed
245 246 247 248
    dflags <- getDynFlags
    w <- getWarnings
    liftIO $ printOrThrowWarnings dflags w
    clearWarnings
249 250 251 252 253

-- | log warning in the monad, and if there are errors then
-- throw a SourceError exception.
logWarningsReportErrors :: Messages -> Hsc ()
logWarningsReportErrors (warns,errs) = do
dterei's avatar
dterei committed
254 255
    logWarnings warns
    when (not $ isEmptyBag errs) $ throwErrors errs
256 257 258 259

-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
260 261 262 263 264

-- | 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
dterei's avatar
dterei committed
265
-- and signal success via by wrapping the result in a 'Maybe' type. This
266 267 268 269 270 271 272 273 274
-- 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
dterei's avatar
dterei committed
275
--     there should be warnings in the first result. That is, if the action
276 277 278
--     failed, it must have been due to the warnings (i.e., @-Werror@).
ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
ioMsgMaybe ioA = do
279
    ((warns,errs), mb_r) <- liftIO ioA
dterei's avatar
dterei committed
280 281 282 283
    logWarnings warns
    case mb_r of
        Nothing -> throwErrors errs
        Just r  -> ASSERT( isEmptyBag errs ) return r
284 285 286 287 288

-- | like ioMsgMaybe, except that we ignore error messages and return
-- 'Nothing' instead.
ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
ioMsgMaybe' ioA = do
dterei's avatar
dterei committed
289 290 291
    ((warns,_errs), mb_r) <- liftIO $ ioA
    logWarnings warns
    return mb_r
292 293 294 295 296 297

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

#ifdef GHCI
hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
298 299 300
hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do
   hsc_env <- getHscEnv
   ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
301 302 303
#endif

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
304 305 306
hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe' $ tcRnLookupName hsc_env name
dterei's avatar
dterei committed
307 308 309
      -- 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.
310

311
hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst]))
312 313 314
hscTcRnGetInfo hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe' $ tcRnGetInfo hsc_env name
315 316

#ifdef GHCI
dterei's avatar
dterei committed
317 318 319 320 321
hscIsGHCiMonad :: HscEnv -> String -> IO Name
hscIsGHCiMonad hsc_env name =
    let icntxt   = hsc_IC hsc_env
    in runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env icntxt name

322
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
323 324 325
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ getModuleInterface hsc_env mod
326 327 328

-- -----------------------------------------------------------------------------
-- | Rename some import declarations
329
hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
330 331 332
hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
333 334
#endif

335
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
336
-- | parse a file, returning the abstract syntax
337

338
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
339 340 341
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
342
hscParse' :: ModSummary -> Hsc HsParsedModule
343
hscParse' mod_summary = do
dterei's avatar
dterei committed
344 345 346
    dflags <- getDynFlags
    let src_filename  = ms_hspp_file mod_summary
        maybe_src_buf = ms_hspp_buf  mod_summary
347

dterei's avatar
dterei committed
348 349 350
    --------------------------  Parser  ----------------
    liftIO $ showPass dflags "Parser"
    {-# SCC "Parser" #-} do
351 352 353 354

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

dterei's avatar
dterei committed
359
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
360

dterei's avatar
dterei committed
361 362
    case unP parseModule (mkPState dflags buf loc) of
        PFailed span err ->
Ian Lynagh's avatar
Ian Lynagh committed
363
            liftIO $ throwOneError (mkPlainErrMsg dflags span err)
364

dterei's avatar
dterei committed
365 366 367 368 369 370
        POk pst rdr_module -> do
            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
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

            -- To get the list of extra source files, we take the list
            -- that the parser gave us,
            --   - eliminate files beginning with '<'.  gcc likes to use
            --     pseudo-filenames like "<built-in>" and "<command-line>"
            --   - normalise them (elimiante differences between ./f and f)
            --   - filter out the preprocessed source file
            --   - filter out anything beginning with tmpdir
            --   - remove duplicates
            --   - filter out the .hs/.lhs source filename if we have one
            --
            let n_hspp  = FilePath.normalise src_filename
                srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`))
                            $ filter (not . (== n_hspp))
                            $ map FilePath.normalise
386
                            $ filter (not . (isPrefixOf "<"))
387 388 389 390 391 392
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

393 394 395 396 397
            -- sometimes we see source files from earlier
            -- preprocessing stages that cannot be found, so just
            -- filter them out:
            srcs2 <- liftIO $ filterM doesFileExist srcs1

398 399
            return HsParsedModule {
                      hpm_module    = rdr_module,
400
                      hpm_src_files = srcs2
401
                   }
Simon Marlow's avatar
Simon Marlow committed
402

Thomas Schilling's avatar
Thomas Schilling committed
403 404 405
-- 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.
dterei's avatar
dterei committed
406
type RenamedStuff =
Simon Marlow's avatar
Simon Marlow committed
407
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
408
                Maybe LHsDocString))
Simon Marlow's avatar
Simon Marlow committed
409

Thomas Schilling's avatar
Thomas Schilling committed
410
-- | Rename and typecheck a module, additionally returning the renamed syntax
411
hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
412
                   -> IO (TcGblEnv, RenamedStuff)
dterei's avatar
dterei committed
413
hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
414
    tc_result <- tcRnModule' hsc_env mod_summary True rdr_module
Thomas Schilling's avatar
Thomas Schilling committed
415

416 417 418 419 420 421
        -- This 'do' is in the Maybe monad!
    let rn_info = do decl <- tcg_rn_decls tc_result
                     let imports = tcg_rn_imports tc_result
                         exports = tcg_rn_exports tc_result
                         doc_hdr = tcg_doc_hdr tc_result
                     return (decl,imports,exports,doc_hdr)
Thomas Schilling's avatar
Thomas Schilling committed
422

423
    return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
424

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
-- wrapper around tcRnModule to handle safe haskell extras
tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule
            -> Hsc TcGblEnv
tcRnModule' hsc_env sum save_rn_syntax mod = do
    tcg_res <- {-# SCC "Typecheck-Rename" #-}
               ioMsgMaybe $
                   tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod

    tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_res)
    dflags   <- getDynFlags

    -- end of the Safe Haskell line, how to respond to user?
    if not (safeHaskellOn dflags) || (safeInferOn dflags && not tcSafeOK)
        -- if safe haskell off or safe infer failed, wipe trust
        then wipeTrust tcg_res emptyBag

        -- module safe, throw warning if needed
        else do
            tcg_res' <- hscCheckSafeImports tcg_res
            safe <- liftIO $ readIORef (tcg_safeInfer tcg_res')
            when (safe && wopt Opt_WarnSafe dflags)
                 (logWarnings $ unitBag $
Ian Lynagh's avatar
Ian Lynagh committed
447
                     mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $ errSafe tcg_res')
448 449 450
            return tcg_res'
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
451
    errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
452

Simon Marlow's avatar
Simon Marlow committed
453
-- | Convert a typechecked module to Core
454
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
455
hscDesugar hsc_env mod_summary tc_result =
Ian Lynagh's avatar
Ian Lynagh committed
456
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
457

Ian Lynagh's avatar
Ian Lynagh committed
458 459
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
dterei's avatar
dterei committed
460
    hsc_env <- getHscEnv
Simon Marlow's avatar
Simon Marlow committed
461 462
    r <- ioMsgMaybe $
      {-# SCC "deSugar" #-}
Ian Lynagh's avatar
Ian Lynagh committed
463
      deSugar hsc_env mod_location tc_result
464

dterei's avatar
dterei committed
465 466 467 468
    -- always check -Werror after desugaring, this is the last opportunity for
    -- warnings to arise before the backend.
    handleWarnings
    return r
Simon Marlow's avatar
Simon Marlow committed
469

dterei's avatar
dterei committed
470
-- | Make a 'ModIface' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
471 472 473 474
-- 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.
475
makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
476
                -> IO (ModIface,Bool)
477 478 479 480 481
makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do
    safe_mode <- hscGetSafeMode tc_result
    ioMsgMaybe $ do
        mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode
                  details tc_result
Simon Marlow's avatar
Simon Marlow committed
482

dterei's avatar
dterei committed
483
-- | Make a 'ModDetails' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
484
-- typechecking only, as opposed to full compilation.
485 486
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
Simon Marlow's avatar
Simon Marlow committed
487

488

dterei's avatar
dterei committed
489 490 491 492 493 494 495
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
496 497 498 499
                   --------------------------------
                        The compilation proper
                   --------------------------------

dterei's avatar
dterei committed
500 501 502 503 504 505
It's the task of the compilation proper to compile Haskell, hs-boot and core
files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
(the module is still parsed and type-checked. This feature is mostly used by
IDE's and the likes). 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
506
targets byte-code.
dterei's avatar
dterei committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

The modes are kept separate because of their different types and meanings:

 * 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 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.

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.
-}


-- | Status of a compilation to hard-code or nothing.
Thomas Schilling's avatar
Thomas Schilling committed
533
data HscStatus' a
534
    = HscNoRecomp
Thomas Schilling's avatar
Thomas Schilling committed
535
    | HscRecomp
dterei's avatar
dterei committed
536 537 538 539 540
          (Maybe FilePath) -- Has stub files. This is a hack. We can't compile
                           -- C files here since it's done in DriverPipeline.
                           -- For now we just return True if we want the caller
                           -- to compile them for us.
          a
Thomas Schilling's avatar
Thomas Schilling committed
541

dterei's avatar
dterei committed
542
-- This is a bit ugly. Since we use a typeclass below and would like to avoid
Thomas Schilling's avatar
Thomas Schilling committed
543
-- functional dependencies, we have to parameterise the typeclass over the
dterei's avatar
dterei committed
544 545
-- 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.
546
type HscStatus         = HscStatus' ()
547 548
type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
    -- INVARIANT: result is @Nothing@ <=> input was a boot file
Thomas Schilling's avatar
Thomas Schilling committed
549

550 551 552
type OneShotResult     = HscStatus
type BatchResult       = (HscStatus, ModIface, ModDetails)
type NothingResult     = (HscStatus, ModIface, ModDetails)
Thomas Schilling's avatar
Thomas Schilling committed
553
type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
554

555 556
-- ToDo: The old interface and module index are only using in 'batch' and
--       'interactive' mode. They should be removed from 'oneshot' mode.
557
type Compiler result =  HscEnv
558
                     -> ModSummary
559
                     -> SourceModified
560 561
                     -> Maybe ModIface  -- Old interface, if available
                     -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
562
                     -> IO result
563

dterei's avatar
dterei committed
564
data HsCompiler a = HsCompiler {
565
    -- | Called when no recompilation is necessary.
566 567
    hscNoRecomp :: ModIface
                -> Hsc a,
568 569

    -- | Called to recompile the module.
570 571
    hscRecompile :: ModSummary -> Maybe Fingerprint
                 -> Hsc a,
572

573 574
    hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
               -> Hsc a,
575

576
    -- | Code generation for Boot modules.
577 578
    hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
                     -> Hsc a,
579 580

    -- | Code generation for normal modules.
581
    hscGenOutput :: ModGuts -> ModSummary -> Maybe Fingerprint
582
                 -> Hsc a
583 584
  }

585
genericHscCompile :: HsCompiler a
586
                  -> (HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary -> IO ())
587
                  -> HscEnv -> ModSummary -> SourceModified
Thomas Schilling's avatar
Thomas Schilling committed
588
                  -> Maybe ModIface -> Maybe (Int, Int)
589 590
                  -> IO a
genericHscCompile compiler hscMessage hsc_env
591
                  mod_summary source_modified
592
                  mb_old_iface0 mb_mod_index
dterei's avatar
dterei committed
593 594 595
  = do
    (recomp_reqd, mb_checked_iface)
        <- {-# SCC "checkOldIface" #-}
dterei's avatar
dterei committed
596
           checkOldIface hsc_env mod_summary
dterei's avatar
dterei committed
597 598 599 600 601 602 603
                         source_modified mb_old_iface0
    -- 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

    let skip iface = do
604
            hscMessage hsc_env mb_mod_index UpToDate mod_summary
dterei's avatar
dterei committed
605 606 607 608 609 610 611 612 613
            runHsc hsc_env $ hscNoRecomp compiler iface

        compile reason = do
            hscMessage hsc_env mb_mod_index reason mod_summary
            runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash

        stable = case source_modified of
                     SourceUnmodifiedAndStable -> True
                     _                         -> False
614 615 616

        -- If the module used TH splices when it was last compiled,
        -- then the recompilation check is not accurate enough (#481)
dterei's avatar
dterei committed
617
        -- and we must ignore it. However, if the module is stable
618
        -- (none of the modules it depends on, directly or indirectly,
dterei's avatar
dterei committed
619
        -- changed), then we *can* skip recompilation. This is why
620 621 622
        -- the SourceModified type contains SourceUnmodifiedAndStable,
        -- and it's pretty important: otherwise ghc --make would
        -- always recompile TH modules, even if nothing at all has
dterei's avatar
dterei committed
623
        -- changed. Stability is just the same check that make is
624 625
        -- doing for us in one-shot mode.

dterei's avatar
dterei committed
626
    case mb_checked_iface of
627
        Just iface | not (recompileRequired recomp_reqd) ->
dterei's avatar
dterei committed
628
            if mi_used_th iface && not stable
Simon Marlow's avatar
Simon Marlow committed
629
                then compile (RecompBecause "TH")
dterei's avatar
dterei committed
630 631
                else skip iface
        _otherwise ->
632
            compile recomp_reqd
Thomas Schilling's avatar
Thomas Schilling committed
633

634
hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
dterei's avatar
dterei committed
635 636
hscCheckRecompBackend compiler tc_result hsc_env mod_summary
                      source_modified mb_old_iface _m_of_n
637
  = do
dterei's avatar
dterei committed
638 639 640 641 642 643 644
    (recomp_reqd, mb_checked_iface)
        <- {-# SCC "checkOldIface" #-}
           checkOldIface hsc_env mod_summary
                         source_modified mb_old_iface

    let mb_old_hash = fmap mi_iface_hash mb_checked_iface
    case mb_checked_iface of
645
        Just iface | not (recompileRequired recomp_reqd)
dterei's avatar
dterei committed
646
            -> runHsc hsc_env $
dterei's avatar
dterei committed
647 648 649 650 651
                   hscNoRecomp compiler
                       iface{ mi_globals = Just (tcg_rdr_env tc_result) }
        _otherwise
            -> runHsc hsc_env $
                   hscBackend compiler tc_result mod_summary mb_old_hash
652

653
genericHscRecompile :: HsCompiler a
654
                    -> ModSummary -> Maybe Fingerprint
655
                    -> Hsc a
656
genericHscRecompile compiler mod_summary mb_old_hash
dterei's avatar
dterei committed
657 658 659 660 661
    | ExtCoreFile <- ms_hsc_src mod_summary =
        panic "GHC does not currently support reading External Core files"
    | otherwise = do
        tc_result <- hscFileFrontEnd mod_summary
        hscBackend compiler tc_result mod_summary mb_old_hash
662

663
genericHscBackend :: HsCompiler a
664
                  -> TcGblEnv -> ModSummary -> Maybe Fingerprint
665
                  -> Hsc a
666
genericHscBackend compiler tc_result mod_summary mb_old_hash
dterei's avatar
dterei committed
667 668 669
    | HsBootFile <- ms_hsc_src mod_summary =
        hscGenBootOutput compiler tc_result mod_summary mb_old_hash
    | otherwise = do
Ian Lynagh's avatar
Ian Lynagh committed
670
        guts <- hscDesugar' (ms_location mod_summary) tc_result
dterei's avatar
dterei committed
671
        hscGenOutput compiler guts mod_summary mb_old_hash
Thomas Schilling's avatar
Thomas Schilling committed
672

673 674
compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
dterei's avatar
dterei committed
675
    runHsc hsc_env $ hscBackend comp tcg ms' Nothing
676

677 678 679 680
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

681
hscOneShotCompiler :: HsCompiler OneShotResult
dterei's avatar
dterei committed
682
hscOneShotCompiler = HsCompiler {
683

684
    hscNoRecomp = \_old_iface -> do
dterei's avatar
dterei committed
685 686 687
        hsc_env <- getHscEnv
        liftIO $ dumpIfaceStats hsc_env
        return HscNoRecomp
688 689 690

  , hscRecompile = genericHscRecompile hscOneShotCompiler

dterei's avatar
dterei committed
691
  , hscBackend = \tc_result mod_summary mb_old_hash -> do
dterei's avatar
dterei committed
692 693 694 695 696
        dflags <- getDynFlags
        case hscTarget dflags of
            HscNothing -> return (HscRecomp Nothing ())
            _otherw    -> genericHscBackend hscOneShotCompiler
                              tc_result mod_summary mb_old_hash
697

698
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
699 700 701
        (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
        hscWriteIface iface changed mod_summary
        return (HscRecomp Nothing ())
702 703

  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
704 705 706 707 708
        guts <- hscSimplify' guts0
        (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface
        hscWriteIface iface changed mod_summary
        hasStub <- hscGenHardCode cgguts mod_summary
        return (HscRecomp hasStub ())
709
  }
710

Thomas Schilling's avatar
Thomas Schilling committed
711
-- Compile Haskell, boot and extCore in OneShot mode.
712
hscCompileOneShot :: Compiler OneShotResult
713 714
hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  = do
dterei's avatar
dterei committed
715 716 717 718 719
    -- One-shot mode needs a knot-tying mutable variable for interface
    -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
    type_env_var <- newIORef emptyNameEnv
    let mod = ms_mod mod_summary
        hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
720

dterei's avatar
dterei committed
721 722 723
    genericHscCompile hscOneShotCompiler
                      oneShotMsg hsc_env' mod_summary src_changed
                      mb_old_iface mb_i_of_n
Thomas Schilling's avatar
Thomas Schilling committed
724

725 726 727
hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
hscOneShotBackendOnly = compilerBackend hscOneShotCompiler

Thomas Schilling's avatar
Thomas Schilling committed
728 729
--------------------------------------------------------------

730
hscBatchCompiler :: HsCompiler BatchResult
dterei's avatar
dterei committed
731
hscBatchCompiler = HsCompiler {
Thomas Schilling's avatar
Thomas Schilling committed
732

733
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
734 735
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
736

737
  , hscRecompile = genericHscRecompile hscBatchCompiler
Thomas Schilling's avatar
Thomas Schilling committed
738

739 740
  , hscBackend = genericHscBackend hscBatchCompiler

741
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
742 743 744
        (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
        hscWriteIface iface changed mod_summary
        return (HscRecomp Nothing (), iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
745

746
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
747 748 749 750 751
        guts <- hscSimplify' guts0
        (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface
        hscWriteIface iface changed mod_summary
        hasStub <- hscGenHardCode cgguts mod_summary
        return (HscRecomp hasStub (), iface, details)
752
  }
753

dterei's avatar
dterei committed
754
-- | Compile Haskell, boot and extCore in batch mode.
755
hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
756
hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
Thomas Schilling's avatar
Thomas Schilling committed
757

758 759 760
hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler

Thomas Schilling's avatar
Thomas Schilling committed
761 762
--------------------------------------------------------------

763
hscInteractiveCompiler :: HsCompiler InteractiveResult
dterei's avatar
dterei committed
764
hscInteractiveCompiler = HsCompiler {
765
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
766 767
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
768

769
  , hscRecompile = genericHscRecompile hscInteractiveCompiler
Thomas Schilling's avatar
Thomas Schilling committed
770

771 772 773
  , hscBackend = genericHscBackend hscInteractiveCompiler

  , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
774 775
        (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
        return (HscRecomp Nothing Nothing, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
776

777
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
778 779 780
        guts <- hscSimplify' guts0
        (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
        hscInteractive (iface, details, cgguts) mod_summary
781
  }
782 783 784

-- Compile Haskell, extCore to bytecode.
hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
785
hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
Thomas Schilling's avatar
Thomas Schilling committed
786

787 788 789
hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler

Thomas Schilling's avatar
Thomas Schilling committed
790 791
--------------------------------------------------------------

792
hscNothingCompiler :: HsCompiler NothingResult
dterei's avatar
dterei committed
793
hscNothingCompiler = HsCompiler {
794
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
795 796
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
Simon Marlow's avatar
Simon Marlow committed
797

798
  , hscRecompile = genericHscRecompile hscNothingCompiler
799

800
  , hscBackend = \tc_result _mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
801 802 803
        handleWarnings
        (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
        return (HscRecomp Nothing (), iface, details)
804

805 806 807
  , hscGenBootOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenBootOutput should not be called"

808 809 810
  , hscGenOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenOutput should not be called"
  }
811

812
-- Type-check Haskell and .hs-boot only (no external core)
813
hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
814
hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
815

816 817 818
hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
hscNothingBackendOnly = compilerBackend hscNothingCompiler

819 820 821 822
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

823 824 825
genModDetails :: ModIface -> Hsc ModDetails
genModDetails old_iface
  = do
dterei's avatar
dterei committed
826 827 828 829 830
    hsc_env <- getHscEnv
    new_details <- {-# SCC "tcRnIface" #-}
                   liftIO $ initIfaceCheck hsc_env (typecheckIface old_iface)
    liftIO $ dumpIfaceStats hsc_env
    return new_details
831

832 833 834 835
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

836 837
oneShotMsg :: HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary
            -> IO ()
838
oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
dterei's avatar
dterei committed
839
    case recomp of
840
        UpToDate ->
841 842
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
dterei's avatar
dterei committed
843
        _other ->
844 845
            return ()

846 847
batchMsg :: HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary
         -> IO ()
dterei's avatar
dterei committed
848 849
batchMsg hsc_env mb_mod_index recomp mod_summary =
    case recomp of
850 851 852
        MustCompile -> showMsg "Compiling " ""
        UpToDate
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  " ""
dterei's avatar
dterei committed
853
            | otherwise -> return ()
854
        RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
dterei's avatar
dterei committed
855
    where
Ian Lynagh's avatar
Ian Lynagh committed
856
        dflags = hsc_dflags hsc_env
857
        showMsg msg reason =
Ian Lynagh's avatar
Ian Lynagh committed
858
            compilationProgressMsg dflags $
dterei's avatar