HscMain.hs 65.4 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
    -- * Making an HscEnv
      newHscEnv

    -- * Compiling complete source files
35 36
    , Messager, batchMsg
    , HscStatus (..)
37 38 39 40
    , hscCompileOneShot
    , hscCompileCmmFile
    , hscCompileCore

41 42 43 44 45 46 47 48 49
    , genericHscCompileGetFrontendResult

    , genModDetails
    , hscSimpleIface
    , hscWriteIface
    , hscNormalIface
    , hscGenHardCode
    , hscInteractive

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

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

76
#ifdef GHCI
Simon Marlow's avatar
Simon Marlow committed
77
import Id
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 94
import Module
import Packages
Simon Marlow's avatar
Simon Marlow committed
95 96
import RdrName
import HsSyn
97
import CoreSyn
Ian Lynagh's avatar
Ian Lynagh committed
98
import StringBuffer
99
import Parser
100
import Lexer
101 102
import SrcLoc
import TcRnDriver
103
import TcIface          ( typecheckIface )
104
import TcRnMonad
105 106
import IfaceEnv         ( initNameCache )
import LoadIface        ( ifaceStats, initExternalPackageState )
107
import PrelInfo
Simon Marlow's avatar
Simon Marlow committed
108
import MkIface
109 110
import Desugar
import SimplCore
Simon Marlow's avatar
Simon Marlow committed
111
import TidyPgm
112
import CorePrep
113 114
import CoreToStg        ( coreToStg )
import qualified StgCmm ( codeGen )
115 116
import StgSyn
import CostCentre
117
import ProfInit
118 119
import TyCon
import Name
120
import SimplStg         ( stg2stg )
121
import Cmm
122
import CmmParse         ( parseCmmFile )
123
import CmmBuildInfoTables
Edward Z. Yang's avatar
Edward Z. Yang committed
124
import CmmPipeline
125
import CmmInfo
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

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

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

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

Thomas Schilling's avatar
Thomas Schilling committed
157
#include "HsVersions.h"
158

159

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

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

184

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

330
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
331
-- | parse a file, returning the abstract syntax
332

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

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

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

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

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

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

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

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

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

393 394
            return HsParsedModule {
                      hpm_module    = rdr_module,
395
                      hpm_src_files = srcs2
396
                   }
Simon Marlow's avatar
Simon Marlow committed
397

Thomas Schilling's avatar
Thomas Schilling committed
398 399 400
-- 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
401
type RenamedStuff =
Simon Marlow's avatar
Simon Marlow committed
402
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
403
                Maybe LHsDocString))
Simon Marlow's avatar
Simon Marlow committed
404

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

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

418
    return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
419

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

Simon Marlow's avatar
Simon Marlow committed
448
-- | Convert a typechecked module to Core
449
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
450
hscDesugar hsc_env mod_summary tc_result =
Ian Lynagh's avatar
Ian Lynagh committed
451
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
452

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

dterei's avatar
dterei committed
460 461 462 463
    -- 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
464

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

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

483

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

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

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

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


527
-- | Status of a compilation to hard-code
528 529 530 531 532 533
data HscStatus
    = HscNotGeneratingCode
    | HscUpToDate
    | HscUpdateBoot
    | HscRecomp
          FilePath
dterei's avatar
dterei committed
534 535 536 537
          (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.
Thomas Schilling's avatar
Thomas Schilling committed
538

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()

genericHscCompileGetFrontendResult ::
                     Bool -- always do basic recompilation check?
                  -> Maybe TcGblEnv
                  -> Maybe Messager
                  -> HscEnv
                  -> ModSummary
                  -> SourceModified
                  -> Maybe ModIface  -- Old interface, if available
                  -> (Int,Int)       -- (i,n) = module i of n (for msgs)
                  -> IO (Either ModIface (TcGblEnv, Maybe Fingerprint))

genericHscCompileGetFrontendResult always_do_basic_recompilation_check m_tc_result
                                   mHscMessage hsc_env mod_summary source_modified mb_old_iface mod_index
    = do

    let msg what = case mHscMessage of
                   Just hscMessage -> hscMessage hsc_env mod_index what mod_summary
                   Nothing -> return ()
dterei's avatar
dterei committed
559

560 561 562
        skip iface = do
            msg UpToDate
            return $ Left iface
dterei's avatar
dterei committed
563

564 565 566 567
        compile mb_old_hash reason = do
            msg reason
            tc_result <- runHsc hsc_env $ genericHscFrontend mod_summary
            return $ Right (tc_result, mb_old_hash)
dterei's avatar
dterei committed
568 569 570 571

        stable = case source_modified of
                     SourceUnmodifiedAndStable -> True
                     _                         -> False
572

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    case m_tc_result of
         Just tc_result
          | not always_do_basic_recompilation_check ->
             return $ Right (tc_result, Nothing)
         _ -> do
            (recomp_reqd, mb_checked_iface)
                <- {-# SCC "checkOldIface" #-}
                   checkOldIface hsc_env mod_summary
                                source_modified mb_old_iface
            -- save the interface that comes back from checkOldIface.
            -- In one-shot mode we don't have the old iface until this
            -- point, when checkOldIface reads it from the disk.
            let mb_old_hash = fmap mi_iface_hash mb_checked_iface

            case mb_checked_iface of
                Just iface | not (recompileRequired recomp_reqd) ->
                    -- If the module used TH splices when it was last compiled,
                    -- then the recompilation check is not accurate enough (#481)
                    -- and we must ignore it. However, if the module is stable
                    -- (none of the modules it depends on, directly or indirectly,
                    -- changed), then we *can* skip recompilation. This is why
                    -- the SourceModified type contains SourceUnmodifiedAndStable,
                    -- and it's pretty important: otherwise ghc --make would
                    -- always recompile TH modules, even if nothing at all has
                    -- changed. Stability is just the same check that make is
                    -- doing for us in one-shot mode.
                    case m_tc_result of
                    Nothing
                     | mi_used_th iface && not stable ->
                        compile mb_old_hash (RecompBecause "TH")
                    _ ->
                        skip iface
                _ ->
                    case m_tc_result of
                    Nothing -> compile mb_old_hash recomp_reqd
                    Just tc_result ->
                        return $ Right (tc_result, mb_old_hash)

genericHscFrontend :: ModSummary -> Hsc TcGblEnv
genericHscFrontend mod_summary
dterei's avatar
dterei committed
613 614 615
    | ExtCoreFile <- ms_hsc_src mod_summary =
        panic "GHC does not currently support reading External Core files"
    | otherwise = do
616
        hscFileFrontEnd mod_summary
617

618 619 620 621
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

Thomas Schilling's avatar
Thomas Schilling committed
622
-- Compile Haskell, boot and extCore in OneShot mode.
623 624 625
hscCompileOneShot :: HscEnv
                  -> ModSummary
                  -> SourceModified
626
                  -> IO HscStatus
627
hscCompileOneShot hsc_env mod_summary src_changed
628
  = do
dterei's avatar
dterei committed
629 630 631 632 633
    -- 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) }
634

635 636 637 638
        msg what = oneShotMsg hsc_env' what

        skip = do msg UpToDate
                  dumpIfaceStats hsc_env'
639
                  return HscUpToDate
640 641 642 643 644 645

        compile mb_old_hash reason = runHsc hsc_env' $ do
            liftIO $ msg reason
            tc_result <- genericHscFrontend mod_summary
            dflags <- getDynFlags
            case hscTarget dflags of
646
                HscNothing -> return HscNotGeneratingCode
647 648 649 650 651
                _ ->
                    case ms_hsc_src mod_summary of
                    HsBootFile ->
                        do (iface, changed, _) <- hscSimpleIface' tc_result mb_old_hash
                           liftIO $ hscWriteIface dflags iface changed mod_summary
652
                           return HscUpdateBoot
653 654 655 656 657
                    _ ->
                        do guts0 <- hscDesugar' (ms_location mod_summary) tc_result
                           guts <- hscSimplify' guts0
                           (iface, changed, _details, cgguts) <- hscNormalIface' guts mb_old_hash
                           liftIO $ hscWriteIface dflags iface changed mod_summary
658 659
                           (outputFilename, mStub) <- liftIO $ hscGenHardCode hsc_env' cgguts mod_summary
                           return $ HscRecomp outputFilename mStub
660 661 662 663

        stable = case src_changed of
                     SourceUnmodifiedAndStable -> True
                     _                         -> False
664

665 666 667 668 669 670 671
    (recomp_reqd, mb_checked_iface)
        <- {-# SCC "checkOldIface" #-}
           checkOldIface hsc_env' mod_summary src_changed Nothing
    -- 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
672

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
    case mb_checked_iface of
        Just iface | not (recompileRequired recomp_reqd) ->
            -- If the module used TH splices when it was last compiled,
            -- then the recompilation check is not accurate enough (#481)
            -- and we must ignore it. However, if the module is stable
            -- (none of the modules it depends on, directly or indirectly,
            -- changed), then we *can* skip recompilation. This is why
            -- the SourceModified type contains SourceUnmodifiedAndStable,
            -- and it's pretty important: otherwise ghc --make would
            -- always recompile TH modules, even if nothing at all has
            -- changed. Stability is just the same check that make is
            -- doing for us in one-shot mode.
            if mi_used_th iface && not stable
            then compile mb_old_hash (RecompBecause "TH")
            else skip
        _ ->
            compile mb_old_hash recomp_reqd
690

691 692 693 694
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

695 696
genModDetails :: HscEnv -> ModIface -> IO ModDetails
genModDetails hsc_env old_iface
697
  = do
dterei's avatar
dterei committed
698
    new_details <- {-# SCC "tcRnIface" #-}
699 700
                   initIfaceCheck hsc_env (typecheckIface old_iface)
    dumpIfaceStats hsc_env
dterei's avatar
dterei committed
701
    return new_details
702

703 704 705 706
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

707 708
oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
oneShotMsg hsc_env recomp =
dterei's avatar
dterei committed
709
    case recomp of
710
        UpToDate ->
711 712
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
713
        _ ->
714 715
            return ()

716 717
batchMsg :: Messager
batchMsg hsc_env mod_index recomp mod_summary =
dterei's avatar
dterei committed
718
    case recomp of
719 720 721
        MustCompile -> showMsg "Compiling " ""
        UpToDate
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  " ""
dterei's avatar
dterei committed
722
            | otherwise -> return ()
723
        RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
dterei's avatar
dterei committed
724
    where
Ian Lynagh's avatar
Ian Lynagh committed
725
        dflags = hsc_dflags hsc_env
726
        showMsg msg reason =
Ian Lynagh's avatar
Ian Lynagh committed
727
            compilationProgressMsg dflags $
728
            (showModuleIndex mod_index ++
Ian Lynagh's avatar
Ian Lynagh committed
729
            msg ++ showModMsg dflags (hscTarget dflags)
730 731
                              (recompileRequired recomp) mod_summary)
                ++ reason
732

733 734 735
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
736 737

hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
738
hscFileFrontEnd mod_summary = do
739
    hpm <- hscParse' mod_summary
740
    hsc_env <- getHscEnv
741 742
    tcg_env <- tcRnModule' hsc_env mod_summary False hpm
    return tcg_env
743 744

--------------------------------------------------------------
745
-- Safe Haskell
746 747
--------------------------------------------------------------

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
-- 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.


768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
-- 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
788
    tcg_env' <- checkSafeImports dflags tcg_env
789 790 791
    case safeLanguageOn dflags of
        True -> do
            -- we nuke user written RULES in -XSafe
Ian Lynagh's avatar
Ian Lynagh committed
792
            logWarnings $ warns dflags (tcg_rules tcg_env')
793 794 795 796 797
            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
Ian Lynagh's avatar
Ian Lynagh committed
798
            -> wipeTrust tcg_env' $ warns dflags (tcg_rules tcg_env')
799

800
              -- trustworthy OR safe inferred with no RULES
801 802 803
            | otherwise
            -> return tcg_env'

dterei's avatar
dterei committed
804
  where
Ian Lynagh's avatar
Ian Lynagh committed
805 806 807
    warns dflags rules = listToBag $ map (warnRules dflags) rules
    warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
        mkPlainWarnMsg dflags loc $
dterei's avatar
dterei committed
808 809
            text "Rule \"" <> ftext n <> text "\" ignored" $+$
            text "User defined rules are disabled under Safe Haskell"
810

811 812 813 814 815 816
-- | 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.
817
--
818 819 820 821 822
-- 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].
823 824
checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags tcg_env
825
    = do
826 827 828 829 830
        -- 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

831
        imps <- mapM condense imports'
832
        pkgs <- mapM checkSafe imps
dterei's avatar
dterei committed
833 834 835 836 837 838

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

839
        -- See the Note [Safe Haskell Inference]
dterei's avatar
dterei committed
840 841 842 843 844 845
        case (not $ isEmptyBag errs) of

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

dterei's avatar
dterei committed
849 850
            -- All good matey!
            False -> do
851
                when (packageTrustOn dflags) $ checkPkgTrust dflags pkg_reqs
dterei's avatar
dterei committed
852 853 854
                -- add in trusted package requirements for this module
                let new_trust = emptyImportAvails { imp_trust_pkgs = catMaybes pkgs }
                return tcg_env { tcg_imports = imp_info `plusImportAvails` new_trust }
855

dterei's avatar
dterei committed
856 857 858 859 860 861 862 863 864
  where
    imp_info = tcg_imports tcg_env     -- ImportAvails
    imports  = imp_mods imp_info       -- ImportedMods
    imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
    pkg_reqs = imp_trust_pkgs imp_info -- [PackageId]

    condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
    condense (_, [])   = panic "HscMain.condense: Pattern match failure!"
    condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs
865 866 867 868
                            -- we turn all imports into safe ones when
                            -- inference mode is on.
                            let s' = if safeInferOn dflags then True else s
                            return (m, l, s')
dterei's avatar
dterei committed
869

dterei's avatar
dterei committed
870 871 872 873
    -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
    cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
    cond' v1@(m1,_,l1,s1) (_,_,_,s2)
        | s1 /= s2
Ian Lynagh's avatar
Ian Lynagh committed
874
        = throwErrors $ unitBag $ mkPlainErrMsg dflags l1
dterei's avatar
dterei committed
875 876 877 878
              (text "Module" <+> ppr m1 <+>
              (text $ "is imported both as a safe and unsafe import!"))
        | otherwise
        = return v1
879 880 881
    
    -- easier interface to work with
    checkSafe (_, _, False) = return Nothing
dterei's avatar
dterei committed
882
    checkSafe (m, l, True ) = fst `fmap` hscCheckSafe' dflags m l
dterei's avatar
dterei committed
883

884 885
-- | Check that a module is safe to import.
--
dterei's avatar
dterei committed
886 887 888
-- We return True to indicate the import is safe and False otherwise
-- although in the False case an exception may be thrown first.
hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool
889 890
hscCheckSafe hsc_env m l = runHsc hsc_env $ do
    dflags <- getDynFlags
dterei's avatar
dterei committed
891 892 893 894
    pkgs <- snd `fmap` hscCheckSafe' dflags m l
    when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs
    errs <- getWarnings
    return $ isEmptyBag errs
895

dterei's avatar
dterei committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
-- | Return if a module is trusted and the pkgs it depends on to be trusted.
hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageId])
hscGetSafe hsc_env m l = runHsc hsc_env $ do
    dflags       <- getDynFlags
    (self, pkgs) <- hscCheckSafe' dflags m l
    good         <- isEmptyBag `fmap` getWarnings
    clearWarnings -- don't want them printed...
    let pkgs' | Just p <- self = p:pkgs
              | otherwise      = pkgs
    return (good, pkgs')
 
-- | Is a module trusted? If not, throw or log errors depending on the type.
-- Return (regardless of trusted or not) if the trust type requires the modules
-- own package be trusted and a list of other packages required to be trusted
-- (these later ones haven't been checked) but the own package trust has been.
dterei's avatar
dterei committed
911
hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageId, [PackageId])
912
hscCheckSafe' dflags m l = do
dterei's avatar
dterei committed
913
    (tw, pkgs) <- isModSafe m l
914
    case tw of
dterei's avatar
dterei committed
915 916 917
        False              -> return (Nothing, pkgs)
        True | isHomePkg m -> return (Nothing, pkgs)
             | otherwise   -> return (Just $ modulePackageId m, pkgs)
918
  where
dterei's avatar
dterei committed
919
    isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageId])
dterei's avatar
dterei committed
920 921 922 923
    isModSafe m l = do
        iface <- lookup' m
        case iface of
            -- can't load iface to check trust!
Ian Lynagh's avatar
Ian Lynagh committed
924
            Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l
925 926
                         $ text "Can't load the interface file for" <+> ppr m
                           <> text ", to check that it can be safely imported"
dterei's avatar
dterei committed
927 928

            -- got iface, check trust
929
            Just iface' ->
dterei's avatar
dterei committed
930 931 932
                let trust = getSafeMode $ mi_trust iface'
                    trust_own_pkg = mi_trust_pkg iface'
                    -- check module is trusted
933
                    safeM = trust `elem` [Sf_SafeInferred, Sf_Safe, Sf_Trustworthy]
dterei's avatar
dterei committed
934 935
                    -- check package is trusted
                    safeP = packageTrusted trust trust_own_pkg m
dterei's avatar
dterei committed
936 937
                    -- pkg trust reqs
                    pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface'
dterei's avatar
dterei committed
938
                    -- General errors we throw but Safe errors we log
939 940 941 942 943 944 945
                    errs = case (safeM, safeP) of
                        (True, True ) -> emptyBag
                        (True, False) -> pkgTrustErr
                        (False, _   ) -> modTrustErr
                in do
                    logWarnings errs
                    return (trust == Sf_Trustworthy, pkgRs)
dterei's avatar
dterei committed
946 947

                where
948
                    pkgTrustErr = unitBag $ mkPlainErrMsg dflags l $
949 950
                        sep [ ppr (moduleName m)
                                <> text ": Can't be safely imported!"
951
                            , text "The package (" <> ppr (modulePackageId m)
952
                                <> text ") the module resides in isn't trusted."
953
                            ]
Ian Lynagh's avatar
Ian Lynagh committed
954
                    modTrustErr = unitBag $ mkPlainErrMsg dflags l $
955 956
                        sep [ ppr (moduleName m)
                                <> text ": Can't be safely imported!"
957
                            , text "The module itself isn't safe." ]
dterei's avatar
dterei committed
958

959 960 961 962
    -- | Check the package a module resides in is trusted. Safe compiled
    -- modules are trusted without requiring that their package is trusted. For
    -- trustworthy modules, modules in the home package are trusted but
    -- otherwise we check the package trust flag.
963
    packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
dterei's avatar
dterei committed
964 965
    packageTrusted Sf_None             _ _ = False -- shouldn't hit these cases
    packageTrusted Sf_Unsafe           _ _ = False -- prefer for completeness.
966
    packageTrusted _ _ _
967 968 969
        | not (packageTrustOn dflags)      = True
    packageTrusted Sf_Safe         False _ = True
    packageTrusted Sf_SafeInferred False _ = True
970 971 972 973
    packageTrusted _ _ m
        | isHomePkg m = True
        | otherwise   = trusted $ getPackageDetails (pkgState dflags)
                                                    (modulePackageId m)
dterei's avatar
dterei committed
974

975 976 977 978 979 980 981
    lookup' :: Module -> Hsc (Maybe ModIface)
    lookup' m = do
        hsc_env <- getHscEnv
        hsc_eps <- liftIO $ hscEPS hsc_env
        let pkgIfaceT = eps_PIT hsc_eps
            homePkgT  = hsc_HPT hsc_env
            iface     = lookupIfaceByModule dflags homePkgT pkgIfaceT m
dterei's avatar
dterei committed
982 983 984 985 986 987 988 989 990
#ifdef GHCI
        -- the 'lookupIfaceByModule' method will always fail when calling from GHCi
        -- as the compiler hasn't filled in the various module tables
        -- so we need to call 'getModuleInterface' to load from disk
        iface' <- case iface of
            Just _  -> return iface
            Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m)
        return iface'
#else