HscMain.hs 64.2 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 63
    , hscSimplify -- ToDo, shouldn't really export this

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

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

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

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

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

137
import Outputable
138
import HscStats         ( ppSourceStats )
139
import HscTypes
140
import MkExternalCore   ( emitExternalCore )
141
import FastString
142
import UniqFM           ( emptyUFM )
143
import UniqSupply       ( initUs_ )
144
import Bag
Thomas Schilling's avatar
Thomas Schilling committed
145
import Exception
Simon Marlow's avatar
Simon Marlow committed
146

147
import Data.List
Simon Marlow's avatar
Simon Marlow committed
148
import Control.Monad
149
import Data.Maybe
Simon Marlow's avatar
Simon Marlow committed
150
import Data.IORef
151
import System.FilePath as FilePath
152
import System.Directory
dterei's avatar
dterei committed
153

Thomas Schilling's avatar
Thomas Schilling committed
154
#include "HsVersions.h"
155

156

dterei's avatar
dterei committed
157 158 159 160 161
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
162

163
newHscEnv :: DynFlags -> IO HscEnv
164
newHscEnv dflags = do
dterei's avatar
dterei committed
165 166 167 168 169 170 171
    eps_var <- newIORef initExternalPackageState
    us      <- mkSplitUniqSupply 'r'
    nc_var  <- newIORef (initNameCache us knownKeyNames)
    fc_var  <- newIORef emptyUFM
    mlc_var <- newIORef emptyModuleEnv
    optFuel <- initOptFuelState
    safe_var <- newIORef True
172
    return HscEnv {  hsc_dflags       = dflags,
dterei's avatar
dterei committed
173 174 175 176 177 178 179 180 181
                     hsc_targets      = [],
                     hsc_mod_graph    = [],
                     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,
dterei's avatar
dterei committed
182
                     hsc_type_env_var = Nothing,
dterei's avatar
dterei committed
183
                     hsc_safeInf      = safe_var }
Thomas Schilling's avatar
Thomas Schilling committed
184

185

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

194
-- -----------------------------------------------------------------------------
195
-- The Hsc monad: Passing an enviornment and warning state
196

dterei's avatar
dterei committed
197
newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
198 199

instance Monad Hsc where
dterei's avatar
dterei committed
200 201 202 203
    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
204 205

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

runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env (Hsc hsc) = do
dterei's avatar
dterei committed
210 211 212
    (a, w) <- hsc hsc_env emptyBag
    printOrThrowWarnings (hsc_dflags hsc_env) w
    return a
213 214

getWarnings :: Hsc WarningMessages
dterei's avatar
dterei committed
215
getWarnings = Hsc $ \_ w -> return (w, w)
216 217

clearWarnings :: Hsc ()
dterei's avatar
dterei committed
218
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
219 220

logWarnings :: WarningMessages -> Hsc ()
dterei's avatar
dterei committed
221
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
222 223

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

226 227
instance HasDynFlags Hsc where
    getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
228 229 230

handleWarnings :: Hsc ()
handleWarnings = do
dterei's avatar
dterei committed
231 232 233 234
    dflags <- getDynFlags
    w <- getWarnings
    liftIO $ printOrThrowWarnings dflags w
    clearWarnings
235 236 237 238 239

-- | 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
240 241
    logWarnings warns
    when (not $ isEmptyBag errs) $ throwErrors errs
242 243 244 245

-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
246 247 248 249 250

-- | 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
251
-- and signal success via by wrapping the result in a 'Maybe' type. This
252 253 254 255 256 257 258 259 260
-- 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
261
--     there should be warnings in the first result. That is, if the action
262 263 264
--     failed, it must have been due to the warnings (i.e., @-Werror@).
ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
ioMsgMaybe ioA = do
dterei's avatar
dterei committed
265 266 267 268 269
    ((warns,errs), mb_r) <- liftIO $ ioA
    logWarnings warns
    case mb_r of
        Nothing -> throwErrors errs
        Just r  -> ASSERT( isEmptyBag errs ) return r
270 271 272 273 274

-- | 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
275 276 277
    ((warns,_errs), mb_r) <- liftIO $ ioA
    logWarnings warns
    return mb_r
278 279 280 281 282 283

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

#ifdef GHCI
hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
dterei's avatar
dterei committed
284
hscTcRnLookupRdrName hsc_env rdr_name =
dterei's avatar
dterei committed
285
    runHsc hsc_env $ ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
286 287 288
#endif

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
dterei's avatar
dterei committed
289
hscTcRcLookupName hsc_env name =
dterei's avatar
dterei committed
290 291 292 293
    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.
294 295 296

hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [Instance]))
hscTcRnGetInfo hsc_env name =
dterei's avatar
dterei committed
297
    runHsc hsc_env $ ioMsgMaybe' $ tcRnGetInfo hsc_env name
298 299

#ifdef GHCI
300
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
301
hscGetModuleInterface hsc_env mod =
dterei's avatar
dterei committed
302
    runHsc hsc_env $ ioMsgMaybe $ getModuleInterface hsc_env mod
303 304 305

-- -----------------------------------------------------------------------------
-- | Rename some import declarations
306
hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
dterei's avatar
dterei committed
307 308
hscRnImportDecls hsc_env import_decls =
    runHsc hsc_env $ ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
309 310
#endif

311
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
312
-- | parse a file, returning the abstract syntax
313

314
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
315 316 317
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
318
hscParse' :: ModSummary -> Hsc HsParsedModule
319
hscParse' mod_summary = do
dterei's avatar
dterei committed
320 321 322
    dflags <- getDynFlags
    let src_filename  = ms_hspp_file mod_summary
        maybe_src_buf = ms_hspp_buf  mod_summary
323

dterei's avatar
dterei committed
324 325 326
    --------------------------  Parser  ----------------
    liftIO $ showPass dflags "Parser"
    {-# SCC "Parser" #-} do
327 328 329 330

    -- 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
331 332 333
    buf <- case maybe_src_buf of
               Just b  -> return b
               Nothing -> liftIO $ hGetStringBuffer src_filename
334

dterei's avatar
dterei committed
335
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
336

dterei's avatar
dterei committed
337 338 339
    case unP parseModule (mkPState dflags buf loc) of
        PFailed span err ->
            liftIO $ throwOneError (mkPlainErrMsg span err)
340

dterei's avatar
dterei committed
341 342 343 344 345 346
        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
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

            -- 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
                            $ filter (not . (== '<') . head)
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

369 370 371 372 373
            -- sometimes we see source files from earlier
            -- preprocessing stages that cannot be found, so just
            -- filter them out:
            srcs2 <- liftIO $ filterM doesFileExist srcs1

374 375
            return HsParsedModule {
                      hpm_module    = rdr_module,
376
                      hpm_src_files = srcs2
377
                   }
Simon Marlow's avatar
Simon Marlow committed
378

Thomas Schilling's avatar
Thomas Schilling committed
379 380 381
-- 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
382
type RenamedStuff =
Simon Marlow's avatar
Simon Marlow committed
383
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
384
                Maybe LHsDocString))
Simon Marlow's avatar
Simon Marlow committed
385

Thomas Schilling's avatar
Thomas Schilling committed
386
-- | Rename and typecheck a module, additionally returning the renamed syntax
387
hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
388
                   -> IO (TcGblEnv, RenamedStuff)
dterei's avatar
dterei committed
389
hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
390
    tc_result <- {-# SCC "Typecheck-Rename" #-}
dterei's avatar
dterei committed
391
                 ioMsgMaybe $
dterei's avatar
dterei committed
392 393
                     tcRnModule hsc_env (ms_hsc_src mod_summary)
                                True rdr_module
Thomas Schilling's avatar
Thomas Schilling committed
394

395 396 397 398 399 400
        -- 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
401

402
    return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
403 404

-- | Convert a typechecked module to Core
405
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
406
hscDesugar hsc_env mod_summary tc_result =
Ian Lynagh's avatar
Ian Lynagh committed
407
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
408

Ian Lynagh's avatar
Ian Lynagh committed
409 410
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
dterei's avatar
dterei committed
411
    hsc_env <- getHscEnv
Simon Marlow's avatar
Simon Marlow committed
412 413
    r <- ioMsgMaybe $
      {-# SCC "deSugar" #-}
Ian Lynagh's avatar
Ian Lynagh committed
414
      deSugar hsc_env mod_location tc_result
415

dterei's avatar
dterei committed
416 417 418 419
    -- 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
420

dterei's avatar
dterei committed
421
-- | Make a 'ModIface' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
422 423 424 425
-- 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.
426
makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
427
                -> IO (ModIface,Bool)
428
makeSimpleIface hsc_env maybe_old_iface tc_result details =
dterei's avatar
dterei committed
429
    runHsc hsc_env $ ioMsgMaybe $
dterei's avatar
dterei committed
430
        mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
Simon Marlow's avatar
Simon Marlow committed
431

dterei's avatar
dterei committed
432
-- | Make a 'ModDetails' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
433
-- typechecking only, as opposed to full compilation.
434 435
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
Simon Marlow's avatar
Simon Marlow committed
436

437

dterei's avatar
dterei committed
438 439 440 441 442 443 444
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
445 446 447 448
                   --------------------------------
                        The compilation proper
                   --------------------------------

dterei's avatar
dterei committed
449 450 451 452 453 454
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
455
targets byte-code.
dterei's avatar
dterei committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

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
482
data HscStatus' a
483
    = HscNoRecomp
Thomas Schilling's avatar
Thomas Schilling committed
484
    | HscRecomp
dterei's avatar
dterei committed
485 486 487 488 489
          (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
490

dterei's avatar
dterei committed
491
-- This is a bit ugly. Since we use a typeclass below and would like to avoid
Thomas Schilling's avatar
Thomas Schilling committed
492
-- functional dependencies, we have to parameterise the typeclass over the
dterei's avatar
dterei committed
493 494
-- 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.
495
type HscStatus         = HscStatus' ()
496 497
type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
    -- INVARIANT: result is @Nothing@ <=> input was a boot file
Thomas Schilling's avatar
Thomas Schilling committed
498

499 500 501
type OneShotResult     = HscStatus
type BatchResult       = (HscStatus, ModIface, ModDetails)
type NothingResult     = (HscStatus, ModIface, ModDetails)
Thomas Schilling's avatar
Thomas Schilling committed
502
type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
503

504 505
-- ToDo: The old interface and module index are only using in 'batch' and
--       'interactive' mode. They should be removed from 'oneshot' mode.
506
type Compiler result =  HscEnv
507
                     -> ModSummary
508
                     -> SourceModified
509 510
                     -> Maybe ModIface  -- Old interface, if available
                     -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
511
                     -> IO result
512

dterei's avatar
dterei committed
513
data HsCompiler a = HsCompiler {
514
    -- | Called when no recompilation is necessary.
515 516
    hscNoRecomp :: ModIface
                -> Hsc a,
517 518

    -- | Called to recompile the module.
519 520
    hscRecompile :: ModSummary -> Maybe Fingerprint
                 -> Hsc a,
521

522 523
    hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
               -> Hsc a,
524

525
    -- | Code generation for Boot modules.
526 527
    hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
                     -> Hsc a,
528 529

    -- | Code generation for normal modules.
530 531
    hscGenOutput :: ModGuts  -> ModSummary -> Maybe Fingerprint
                 -> Hsc a
532 533
  }

534
genericHscCompile :: HsCompiler a
535 536
                  -> (HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ())
                  -> HscEnv -> ModSummary -> SourceModified
Thomas Schilling's avatar
Thomas Schilling committed
537
                  -> Maybe ModIface -> Maybe (Int, Int)
538 539
                  -> IO a
genericHscCompile compiler hscMessage hsc_env
540
                  mod_summary source_modified
541
                  mb_old_iface0 mb_mod_index
dterei's avatar
dterei committed
542 543 544
  = do
    (recomp_reqd, mb_checked_iface)
        <- {-# SCC "checkOldIface" #-}
dterei's avatar
dterei committed
545
           checkOldIface hsc_env mod_summary
dterei's avatar
dterei committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
                         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
            hscMessage hsc_env mb_mod_index RecompNotRequired mod_summary
            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
563 564 565

        -- 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
566
        -- and we must ignore it. However, if the module is stable
567
        -- (none of the modules it depends on, directly or indirectly,
dterei's avatar
dterei committed
568
        -- changed), then we *can* skip recompilation. This is why
569 570 571
        -- 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
572
        -- changed. Stability is just the same check that make is
573 574
        -- doing for us in one-shot mode.

dterei's avatar
dterei committed
575 576 577 578 579 580 581
    case mb_checked_iface of
        Just iface | not recomp_reqd ->
            if mi_used_th iface && not stable
                then compile RecompForcedByTH
                else skip iface
        _otherwise ->
            compile RecompRequired
Thomas Schilling's avatar
Thomas Schilling committed
582

583
hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
dterei's avatar
dterei committed
584 585
hscCheckRecompBackend compiler tc_result hsc_env mod_summary
                      source_modified mb_old_iface _m_of_n
586
  = do
dterei's avatar
dterei committed
587 588 589 590 591 592 593 594
    (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
        Just iface | not recomp_reqd
dterei's avatar
dterei committed
595
            -> runHsc hsc_env $
dterei's avatar
dterei committed
596 597 598 599 600
                   hscNoRecomp compiler
                       iface{ mi_globals = Just (tcg_rdr_env tc_result) }
        _otherwise
            -> runHsc hsc_env $
                   hscBackend compiler tc_result mod_summary mb_old_hash
601

602
genericHscRecompile :: HsCompiler a
603
                    -> ModSummary -> Maybe Fingerprint
604
                    -> Hsc a
605
genericHscRecompile compiler mod_summary mb_old_hash
dterei's avatar
dterei committed
606 607 608 609 610
    | 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
611

612
genericHscBackend :: HsCompiler a
613
                  -> TcGblEnv -> ModSummary -> Maybe Fingerprint
614
                  -> Hsc a
615
genericHscBackend compiler tc_result mod_summary mb_old_hash
dterei's avatar
dterei committed
616 617 618
    | HsBootFile <- ms_hsc_src mod_summary =
        hscGenBootOutput compiler tc_result mod_summary mb_old_hash
    | otherwise = do
Ian Lynagh's avatar
Ian Lynagh committed
619
        guts <- hscDesugar' (ms_location mod_summary) tc_result
dterei's avatar
dterei committed
620
        hscGenOutput compiler guts mod_summary mb_old_hash
Thomas Schilling's avatar
Thomas Schilling committed
621

622 623
compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
dterei's avatar
dterei committed
624
    runHsc hsc_env $ hscBackend comp tcg ms' Nothing
625

626 627 628 629
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

630
hscOneShotCompiler :: HsCompiler OneShotResult
dterei's avatar
dterei committed
631
hscOneShotCompiler = HsCompiler {
632

633
    hscNoRecomp = \_old_iface -> do
dterei's avatar
dterei committed
634 635 636
        hsc_env <- getHscEnv
        liftIO $ dumpIfaceStats hsc_env
        return HscNoRecomp
637 638 639

  , hscRecompile = genericHscRecompile hscOneShotCompiler

dterei's avatar
dterei committed
640
  , hscBackend = \tc_result mod_summary mb_old_hash -> do
dterei's avatar
dterei committed
641 642 643 644 645
        dflags <- getDynFlags
        case hscTarget dflags of
            HscNothing -> return (HscRecomp Nothing ())
            _otherw    -> genericHscBackend hscOneShotCompiler
                              tc_result mod_summary mb_old_hash
646

647
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
648 649 650
        (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
        hscWriteIface iface changed mod_summary
        return (HscRecomp Nothing ())
651 652

  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
653 654 655 656 657
        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 ())
658
  }
659

Thomas Schilling's avatar
Thomas Schilling committed
660
-- Compile Haskell, boot and extCore in OneShot mode.
661
hscCompileOneShot :: Compiler OneShotResult
662 663
hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  = do
dterei's avatar
dterei committed
664 665 666 667 668
    -- 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) }
669

dterei's avatar
dterei committed
670 671 672
    genericHscCompile hscOneShotCompiler
                      oneShotMsg hsc_env' mod_summary src_changed
                      mb_old_iface mb_i_of_n
Thomas Schilling's avatar
Thomas Schilling committed
673

674 675 676
hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
hscOneShotBackendOnly = compilerBackend hscOneShotCompiler

Thomas Schilling's avatar
Thomas Schilling committed
677 678
--------------------------------------------------------------

679
hscBatchCompiler :: HsCompiler BatchResult
dterei's avatar
dterei committed
680
hscBatchCompiler = HsCompiler {
Thomas Schilling's avatar
Thomas Schilling committed
681

682
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
683 684
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
685

686
  , hscRecompile = genericHscRecompile hscBatchCompiler
Thomas Schilling's avatar
Thomas Schilling committed
687

688 689
  , hscBackend = genericHscBackend hscBatchCompiler

690
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
691 692 693
        (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
694

695
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
696 697 698 699 700
        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)
701
  }
702

dterei's avatar
dterei committed
703
-- | Compile Haskell, boot and extCore in batch mode.
704
hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
705
hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
Thomas Schilling's avatar
Thomas Schilling committed
706

707 708 709
hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler

Thomas Schilling's avatar
Thomas Schilling committed
710 711
--------------------------------------------------------------

712
hscInteractiveCompiler :: HsCompiler InteractiveResult
dterei's avatar
dterei committed
713
hscInteractiveCompiler = HsCompiler {
714
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
715 716
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
717

718
  , hscRecompile = genericHscRecompile hscInteractiveCompiler
Thomas Schilling's avatar
Thomas Schilling committed
719

720 721 722
  , hscBackend = genericHscBackend hscInteractiveCompiler

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

726
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
727 728 729
        guts <- hscSimplify' guts0
        (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
        hscInteractive (iface, details, cgguts) mod_summary
730
  }
731 732 733

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

736 737 738
hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler

Thomas Schilling's avatar
Thomas Schilling committed
739 740
--------------------------------------------------------------

741
hscNothingCompiler :: HsCompiler NothingResult
dterei's avatar
dterei committed
742
hscNothingCompiler = HsCompiler {
743
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
744 745
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
Simon Marlow's avatar
Simon Marlow committed
746

747
  , hscRecompile = genericHscRecompile hscNothingCompiler
748

749
  , hscBackend = \tc_result _mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
750 751 752
        handleWarnings
        (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
        return (HscRecomp Nothing (), iface, details)
753

754 755 756
  , hscGenBootOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenBootOutput should not be called"

757 758 759
  , hscGenOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenOutput should not be called"
  }
760

761
-- Type-check Haskell and .hs-boot only (no external core)
762
hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
763
hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
764

765 766 767
hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
hscNothingBackendOnly = compilerBackend hscNothingCompiler

768 769 770 771
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

772 773 774
genModDetails :: ModIface -> Hsc ModDetails
genModDetails old_iface
  = do
dterei's avatar
dterei committed
775 776 777 778 779
    hsc_env <- getHscEnv
    new_details <- {-# SCC "tcRnIface" #-}
                   liftIO $ initIfaceCheck hsc_env (typecheckIface old_iface)
    liftIO $ dumpIfaceStats hsc_env
    return new_details
780

781 782 783 784
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

785
data RecompReason = RecompNotRequired | RecompRequired | RecompForcedByTH
dterei's avatar
dterei committed
786
    deriving Eq
787

788 789
oneShotMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ()
oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
dterei's avatar
dterei committed
790 791
    case recomp of
        RecompNotRequired ->
792 793
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
dterei's avatar
dterei committed
794
        _other ->
795 796 797
            return ()

batchMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ()
dterei's avatar
dterei committed
798 799 800 801 802 803 804 805 806 807 808 809 810
batchMsg hsc_env mb_mod_index recomp mod_summary =
    case recomp of
        RecompRequired -> showMsg "Compiling "
        RecompNotRequired
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  "
            | otherwise -> return ()
        RecompForcedByTH -> showMsg "Compiling [TH] "
    where
        showMsg msg =
            compilationProgressMsg (hsc_dflags hsc_env) $
            (showModuleIndex mb_mod_index ++
            msg ++ showModMsg (hscTarget (hsc_dflags hsc_env))
                              (recomp == RecompRequired) mod_summary)
811

812 813 814
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
815 816

hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
817
hscFileFrontEnd mod_summary = do
818
    hpm <- hscParse' mod_summary
819
    hsc_env <- getHscEnv
820
    dflags  <- getDynFlags
dterei's avatar
dterei committed
821 822 823
    tcg_env <-
        {-# SCC "Typecheck-Rename" #-}
        ioMsgMaybe $
824
            tcRnModule hsc_env (ms_hsc_src mod_summary) False hpm
825
    tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_env)
826 827

    -- end of the Safe Haskell line, how to respond to user?
828
    if not (safeHaskellOn dflags) || (safeInferOn dflags && not tcSafeOK)
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844

        -- if safe haskell off or safe infer failed, wipe trust
        then wipeTrust tcg_env emptyBag

        -- module safe, throw warning if needed
        else do
            tcg_env' <- hscCheckSafeImports tcg_env
            safe <- liftIO $ hscGetSafeInf hsc_env
            when (safe && wopt Opt_WarnSafe dflags)
                 (logWarnings $ unitBag $
                     mkPlainWarnMsg (warnSafeOnLoc dflags) $ errSafe tcg_env')
            return tcg_env'
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
    errSafe t = text "Warning:" <+> quotes (pprMod t)
                   <+> text "has been infered as safe!"
845 846

--------------------------------------------------------------
847
-- Safe Haskell
848 849
--------------------------------------------------------------

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
-- Note [Safe Haskell Trust Check]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Safe Haskell checks that an import is trusted according to the following
-- rules for an import of module M that resides in Package P:
--
--   * If M is recorded as Safe and all its trust dependencies are OK
--     then M is considered safe.
--   * If M is recorded as Trustworthy and P is considered trusted and
--     all M's trust dependencies are OK then M is considered safe.
--
-- By trust dependencies we mean that the check is transitive. So if
-- a module M that is Safe relies on a module N that is trustworthy,
-- importing module M will first check (according to the second case)
-- that N is trusted before checking M is trusted.
--
-- This is a minimal description, so please refer to the user guide
-- for more details. The user guide is also considered the authoritative
-- source in this matter, not the comments or code.


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 899 900
-- Note [Safe Haskell Inference]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Safe Haskell does Safe inference on modules that don't have any specific
-- safe haskell mode flag. The basic aproach to this is:
--   * When deciding if we need to do a Safe language check, treat
--     an unmarked module as having -XSafe mode specified.
--   * For checks, don't throw errors but return them to the caller.
--   * Caller checks if there are errors:
--     * For modules explicitly marked -XSafe, we throw the errors.
--     * For unmarked modules (inference mode), we drop the errors
--       and mark the module as being Unsafe.


-- | Check that the safe imports of the module being compiled are valid.
-- If not we either issue a compilation error if the module is explicitly
-- using Safe Haskell, or mark the module as unsafe if we're in safe
-- inference mode.
hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv
hscCheckSafeImports tcg_env = do
    hsc_env  <- getHscEnv
    dflags   <- getDynFlags
    tcg_env' <- checkSafeImports dflags hsc_env tcg_env
    case safeLanguageOn dflags of
        True -> do
            -- we nuke user written RULES in -XSafe
            logWarnings $ warns (tcg_rules tcg_env')
            return tcg_env' { tcg_rules = [] }
        False
              -- user defined RULES, so not safe or already unsafe
            | safeInferOn dflags && not (null $ tcg_rules tcg_env') ||
              safeHaskell dflags == Sf_None
901
            -> wipeTrust tcg_env' $ warns (tcg_rules tcg_env')
902

903
              -- trustworthy OR safe infered with no RULES
904 905 906
            | otherwise
            -> return tcg_env'

dterei's avatar
dterei committed