HscMain.hs 69.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
36
    , HscStatus' (..)
37
    , InteractiveStatus, HscStatus
38 39 40 41 42 43 44 45
    , hscCompileOneShot
    , hscCompileBatch
    , hscCompileNothing
    , hscCompileInteractive
    , hscCompileCmmFile
    , hscCompileCore

    -- * Running passes separately
46 47 48
    , hscParse
    , hscTypecheckRename
    , hscDesugar
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
Simon Marlow's avatar
Simon Marlow committed
78
import Id
79
import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
80
import Linker
81 82
import CoreTidy         ( tidyExpr )
import Type             ( Type )
83
import PrelNames
84 85 86
import {- Kind parts of -} Type         ( Kind )
import CoreLint         ( lintUnfolding )
import DsMeta           ( templateHaskellNames )
87
import VarSet
88
import VarEnv           ( emptyTidyEnv )
89
import Panic
90 91

import GHC.Exts
92 93
#endif

94 95
import Module
import Packages
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
109
import MkIface
110 111
import Desugar
import SimplCore
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
import SimplStg         ( stg2stg )
122
import Cmm
123
import CmmParse         ( parseCmmFile )
124
import CmmBuildInfoTables
125
import CmmPipeline
126
import CmmInfo
127
import CodeOutput
128
import NameEnv          ( emptyNameEnv )
129 130
import NameSet          ( emptyNameSet )
import InstEnv
131
import FamInstEnv
132
import Fingerprint      ( Fingerprint )
133

134
import DynFlags
135
import ErrUtils
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
144
import Bag
145
import Exception
146 147 148
import qualified Stream
import Stream (Stream)

149
import Util
Simon Marlow's avatar
Simon Marlow committed
150

151
import Data.List
Simon Marlow's avatar
Simon Marlow committed
152
import Control.Monad
153
import Data.Maybe
Simon Marlow's avatar
Simon Marlow committed
154
import Data.IORef
155
import System.FilePath as FilePath
156
import System.Directory
dterei's avatar
dterei committed
157

158
#include "HsVersions.h"
159

160

dterei's avatar
dterei committed
161 162 163 164 165
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
166

167
newHscEnv :: DynFlags -> IO HscEnv
168
newHscEnv dflags = do
dterei's avatar
dterei committed
169 170 171 172 173
    eps_var <- newIORef initExternalPackageState
    us      <- mkSplitUniqSupply 'r'
    nc_var  <- newIORef (initNameCache us knownKeyNames)
    fc_var  <- newIORef emptyUFM
    mlc_var <- newIORef emptyModuleEnv
174
    return HscEnv {  hsc_dflags       = dflags,
dterei's avatar
dterei committed
175 176
                     hsc_targets      = [],
                     hsc_mod_graph    = [],
177
                     hsc_IC           = emptyInteractiveContext dflags,
dterei's avatar
dterei committed
178 179 180 181 182
                     hsc_HPT          = emptyHomePackageTable,
                     hsc_EPS          = eps_var,
                     hsc_NC           = nc_var,
                     hsc_FC           = fc_var,
                     hsc_MLC          = mlc_var,
183
                     hsc_type_env_var = Nothing }
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

dterei's avatar
dterei committed
208 209 210
instance Functor Hsc where
    fmap f m = m >>= \a -> return $ f a

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

217 218 219 220 221 222 223
-- 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) })

224
getWarnings :: Hsc WarningMessages
dterei's avatar
dterei committed
225
getWarnings = Hsc $ \_ w -> return (w, w)
226 227

clearWarnings :: Hsc ()
dterei's avatar
dterei committed
228
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
229 230

logWarnings :: WarningMessages -> Hsc ()
dterei's avatar
dterei committed
231
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
232 233

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

236 237
instance HasDynFlags Hsc where
    getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
238 239 240

handleWarnings :: Hsc ()
handleWarnings = do
dterei's avatar
dterei committed
241 242 243 244
    dflags <- getDynFlags
    w <- getWarnings
    liftIO $ printOrThrowWarnings dflags w
    clearWarnings
245 246 247 248 249

-- | 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
250 251
    logWarnings warns
    when (not $ isEmptyBag errs) $ throwErrors errs
252 253 254 255

-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
256 257 258 259 260

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

-- | 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
285 286 287
    ((warns,_errs), mb_r) <- liftIO $ ioA
    logWarnings warns
    return mb_r
288 289 290 291 292 293

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

#ifdef GHCI
hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
294 295 296
hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do
   hsc_env <- getHscEnv
   ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
297 298 299
#endif

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

307
hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst]))
308 309 310
hscTcRnGetInfo hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe' $ tcRnGetInfo hsc_env name
311 312

#ifdef GHCI
dterei's avatar
dterei committed
313 314 315 316 317
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

318
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
319 320 321
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ getModuleInterface hsc_env mod
322 323 324

-- -----------------------------------------------------------------------------
-- | Rename some import declarations
325
hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
326 327 328
hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
329 330
#endif

331
-- -----------------------------------------------------------------------------
332
-- | parse a file, returning the abstract syntax
333

334
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
335 336 337
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

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

dterei's avatar
dterei committed
344 345 346
    --------------------------  Parser  ----------------
    liftIO $ showPass dflags "Parser"
    {-# SCC "Parser" #-} do
347 348 349 350

    -- 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
351 352 353
    buf <- case maybe_src_buf of
               Just b  -> return b
               Nothing -> liftIO $ hGetStringBuffer src_filename
354

dterei's avatar
dterei committed
355
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
356

dterei's avatar
dterei committed
357 358
    case unP parseModule (mkPState dflags buf loc) of
        PFailed span err ->
359
            liftIO $ throwOneError (mkPlainErrMsg dflags span err)
360

dterei's avatar
dterei committed
361 362 363 364 365 366
        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
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

            -- 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
382
                            $ filter (not . (isPrefixOf "<"))
383 384 385 386 387 388
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

389 390 391 392 393
            -- sometimes we see source files from earlier
            -- preprocessing stages that cannot be found, so just
            -- filter them out:
            srcs2 <- liftIO $ filterM doesFileExist srcs1

394 395
            return HsParsedModule {
                      hpm_module    = rdr_module,
396
                      hpm_src_files = srcs2
397
                   }
398

399 400 401
-- 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
402
type RenamedStuff =
403
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
404
                Maybe LHsDocString))
405

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

412 413 414 415 416 417
        -- 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)
418

419
    return (tc_result, rn_info)
420

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
-- 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 $
443
                     mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $ errSafe tcg_res')
444 445 446
            return tcg_res'
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
447
    errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
448

449
-- | Convert a typechecked module to Core
450
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
451
hscDesugar hsc_env mod_summary tc_result =
452
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
453

454 455
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
dterei's avatar
dterei committed
456
    hsc_env <- getHscEnv
457 458
    r <- ioMsgMaybe $
      {-# SCC "deSugar" #-}
459
      deSugar hsc_env mod_location tc_result
460

dterei's avatar
dterei committed
461 462 463 464
    -- always check -Werror after desugaring, this is the last opportunity for
    -- warnings to arise before the backend.
    handleWarnings
    return r
465

dterei's avatar
dterei committed
466
-- | Make a 'ModIface' from the results of typechecking. Used when
467 468 469 470
-- 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.
471
makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
472
                -> IO (ModIface,Bool)
473 474 475 476 477
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
478

dterei's avatar
dterei committed
479
-- | Make a 'ModDetails' from the results of typechecking. Used when
480
-- typechecking only, as opposed to full compilation.
481 482
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
483

484

dterei's avatar
dterei committed
485 486 487 488 489 490 491
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
492 493 494 495
                   --------------------------------
                        The compilation proper
                   --------------------------------

dterei's avatar
dterei committed
496 497 498 499 500 501
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
502
targets byte-code.
dterei's avatar
dterei committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528

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.
529
data HscStatus' a
530
    = HscNoRecomp
531
    | HscRecomp
dterei's avatar
dterei committed
532 533 534 535 536
          (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
537

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

546 547 548
type OneShotResult     = HscStatus
type BatchResult       = (HscStatus, ModIface, ModDetails)
type NothingResult     = (HscStatus, ModIface, ModDetails)
549
type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
550

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

dterei's avatar
dterei committed
560
data HsCompiler a = HsCompiler {
561
    -- | Called when no recompilation is necessary.
562 563
    hscNoRecomp :: ModIface
                -> Hsc a,
564 565

    -- | Called to recompile the module.
566 567
    hscRecompile :: ModSummary -> Maybe Fingerprint
                 -> Hsc a,
568

569 570
    hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
               -> Hsc a,
571

572
    -- | Code generation for Boot modules.
573 574
    hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
                     -> Hsc a,
575 576

    -- | Code generation for normal modules.
577
    hscGenOutput :: ModGuts -> ModSummary -> Maybe Fingerprint
578
                 -> Hsc a
579 580
  }

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

        -- 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
613
        -- and we must ignore it. However, if the module is stable
614
        -- (none of the modules it depends on, directly or indirectly,
dterei's avatar
dterei committed
615
        -- changed), then we *can* skip recompilation. This is why
616 617 618
        -- 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
619
        -- changed. Stability is just the same check that make is
620 621
        -- doing for us in one-shot mode.

dterei's avatar
dterei committed
622
    case mb_checked_iface of
623
        Just iface | not (recompileRequired recomp_reqd) ->
dterei's avatar
dterei committed
624
            if mi_used_th iface && not stable
Simon Marlow's avatar
Simon Marlow committed
625
                then compile (RecompBecause "TH")
dterei's avatar
dterei committed
626 627
                else skip iface
        _otherwise ->
628
            compile recomp_reqd
629

630
hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
dterei's avatar
dterei committed
631 632
hscCheckRecompBackend compiler tc_result hsc_env mod_summary
                      source_modified mb_old_iface _m_of_n
633
  = do
dterei's avatar
dterei committed
634 635 636 637 638 639 640
    (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
641
        Just iface | not (recompileRequired recomp_reqd)
dterei's avatar
dterei committed
642
            -> runHsc hsc_env $
dterei's avatar
dterei committed
643 644 645 646 647
                   hscNoRecomp compiler
                       iface{ mi_globals = Just (tcg_rdr_env tc_result) }
        _otherwise
            -> runHsc hsc_env $
                   hscBackend compiler tc_result mod_summary mb_old_hash
648

649
genericHscRecompile :: HsCompiler a
650
                    -> ModSummary -> Maybe Fingerprint
651
                    -> Hsc a
652
genericHscRecompile compiler mod_summary mb_old_hash
dterei's avatar
dterei committed
653 654 655 656 657
    | 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
658

659
genericHscBackend :: HsCompiler a
660
                  -> TcGblEnv -> ModSummary -> Maybe Fingerprint
661
                  -> Hsc a
662
genericHscBackend compiler tc_result mod_summary mb_old_hash
dterei's avatar
dterei committed
663 664 665
    | HsBootFile <- ms_hsc_src mod_summary =
        hscGenBootOutput compiler tc_result mod_summary mb_old_hash
    | otherwise = do
666
        guts <- hscDesugar' (ms_location mod_summary) tc_result
dterei's avatar
dterei committed
667
        hscGenOutput compiler guts mod_summary mb_old_hash
668

669 670
compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
dterei's avatar
dterei committed
671
    runHsc hsc_env $ hscBackend comp tcg ms' Nothing
672

673 674 675 676
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

677
hscOneShotCompiler :: HsCompiler OneShotResult
dterei's avatar
dterei committed
678
hscOneShotCompiler = HsCompiler {
679

680
    hscNoRecomp = \_old_iface -> do
dterei's avatar
dterei committed
681 682 683
        hsc_env <- getHscEnv
        liftIO $ dumpIfaceStats hsc_env
        return HscNoRecomp
684 685 686

  , hscRecompile = genericHscRecompile hscOneShotCompiler

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

694
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
695 696 697
        (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
        hscWriteIface iface changed mod_summary
        return (HscRecomp Nothing ())
698 699

  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
700 701 702 703 704
        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 ())
705
  }
706

707
-- Compile Haskell, boot and extCore in OneShot mode.
708
hscCompileOneShot :: Compiler OneShotResult
709 710
hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  = do
dterei's avatar
dterei committed
711 712 713 714 715
    -- 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) }
716

dterei's avatar
dterei committed
717 718 719
    genericHscCompile hscOneShotCompiler
                      oneShotMsg hsc_env' mod_summary src_changed
                      mb_old_iface mb_i_of_n
720

721 722 723
hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
hscOneShotBackendOnly = compilerBackend hscOneShotCompiler

724 725
--------------------------------------------------------------

726
hscBatchCompiler :: HsCompiler BatchResult
dterei's avatar
dterei committed
727
hscBatchCompiler = HsCompiler {
728

729
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
730 731
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
732

733
  , hscRecompile = genericHscRecompile hscBatchCompiler
734

735 736
  , hscBackend = genericHscBackend hscBatchCompiler

737
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
738 739 740
        (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
        hscWriteIface iface changed mod_summary
        return (HscRecomp Nothing (), iface, details)
741

742
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
743 744 745 746 747
        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)
748
  }
749

dterei's avatar
dterei committed
750
-- | Compile Haskell, boot and extCore in batch mode.
751
hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
752
hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
753

754 755 756
hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler

757 758
--------------------------------------------------------------

759
hscInteractiveCompiler :: HsCompiler InteractiveResult
dterei's avatar
dterei committed
760
hscInteractiveCompiler = HsCompiler {
761
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
762 763
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
764

765
  , hscRecompile = genericHscRecompile hscInteractiveCompiler
766

767 768 769
  , hscBackend = genericHscBackend hscInteractiveCompiler

  , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
770 771
        (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
        return (HscRecomp Nothing Nothing, iface, details)
772

773
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
774 775 776
        guts <- hscSimplify' guts0
        (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
        hscInteractive (iface, details, cgguts) mod_summary
777
  }
778 779 780

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

783 784 785
hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler

786 787
--------------------------------------------------------------

788
hscNothingCompiler :: HsCompiler NothingResult
dterei's avatar
dterei committed
789
hscNothingCompiler = HsCompiler {
790
    hscNoRecomp = \iface -> do
dterei's avatar
dterei committed
791 792
        details <- genModDetails iface
        return (HscNoRecomp, iface, details)
Simon Marlow's avatar
Simon Marlow committed
793

794
  , hscRecompile = genericHscRecompile hscNothingCompiler
795

796
  , hscBackend = \tc_result _mod_summary mb_old_iface -> do
dterei's avatar
dterei committed
797 798 799
        handleWarnings
        (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
        return (HscRecomp Nothing (), iface, details)
800

801 802 803
  , hscGenBootOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenBootOutput should not be called"

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

808
-- Type-check Haskell and .hs-boot only (no external core)
809
hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
810
hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
811

812 813 814
hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
hscNothingBackendOnly = compilerBackend hscNothingCompiler

815 816 817 818
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

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

828 829 830 831
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

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

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

860 861 862
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
863 864

hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
865
hscFileFrontEnd mod_summary = do
866
    hpm <- hscParse' mod_summary
867
    hsc_env <- getHscEnv
868 869
    tcg_env <- tcRnModule' hsc_env mod_summary False hpm
    return tcg_env
870 871

--------------------------------------------------------------
872
-- Safe Haskell
873 874
--------------------------------------------------------------

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
-- 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.


895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
-- 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
    dflags   <- getDynFlags
915
    tcg_env' <- checkSafeImports dflags tcg_env
916 917 918
    case safeLanguageOn dflags of
        True -> do
            -- we nuke user written RULES in -XSafe
919
            logWarnings $ warns dflags (tcg_rules tcg_env')
920 921 922 923 924
            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
925
            -> wipeTrust tcg_env' $ warns dflags (tcg_rules tcg_env')
926

927
              -- trustworthy OR safe inferred with no RULES
928 929 930
            | otherwise
            -> return tcg_env'

dterei's avatar
dterei committed
931
  where
932 933 934
    warns dflags rules = listToBag $ map (warnRules dflags) rules
    warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
        mkPlainWarnMsg dflags loc $
dterei's avatar
dterei committed
935 936
            text "Rule \"" <> ftext n <> text "\" ignored" $+$
            text "User defined rules are disabled under Safe Haskell"
937

938 939 940 941 942 943
-- | 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. See the Note [Safe Haskell Trust Check] above for more
-- information.
944
--
945 946 947 948 949
-- The code for this is quite tricky as the whole algorithm is done in a few
-- distinct phases in different parts of the code base. See
-- RnNames.rnImportDecl for where package trust dependencies for a module are
-- collected and unioned.  Specifically see the Note [RnNames . Tracking Trust
-- Transitively] and the Note [RnNames . Trust Own Package].
950 951
checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags tcg_env
952
    = do
953 954 955 956 957
        -- We want to use the warning state specifically for detecting if safe
        -- inference has failed, so store and clear any existing warnings.
        oldErrs <- getWarnings
        clearWarnings

958
        imps <- mapM condense imports'
959
        pkgs <- mapM checkSafe imps
dterei's avatar
dterei committed
960 961 962 963 964 965

        -- grab any safe haskell specific errors and restore old warnings
        errs <- getWarnings
        clearWarnings
        logWarnings oldErrs

966
        -- See the Note [Safe Haskell Inference]
dterei's avatar
dterei committed
967 968 969 970 971 972
        case (not $ isEmptyBag errs) of

            -- We have errors!
            True ->
                -- did we fail safe inference or fail -XSafe?
                case safeInferOn dflags of
973
                    True  -> wipeTrust tcg_env errs
dterei's avatar
dterei committed
974
                    False -> liftIO . throwIO . mkSrcErr $ errs
dterei's avatar
dterei committed
975