HscMain.hs 73 KB
Newer Older
1 2
{-# LANGUAGE BangPatterns, CPP, MagicHash, NondecreasingIndentation #-}

dterei's avatar
dterei committed
3 4
-------------------------------------------------------------------------------
--
5
-- | Main API for compiling plain Haskell source code.
6
--
dterei's avatar
dterei committed
7
-- This module implements compilation of a Haskell source. It is
8 9 10 11 12
-- /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
13
-- "interactive" mode (GHCi). There are also entry points for
14 15 16 17 18 19 20 21
-- 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).
--
22 23 24 25 26
-- We use the Hsc monad to deal with warning messages consistently:
-- specifically, while executing within an Hsc monad, warnings are
-- collected. When a Hsc monad returns to an IO monad, the
-- warnings are printed, or compilation aborts if the @-Werror@
-- flag is enabled.
27
--
dterei's avatar
dterei committed
28 29 30 31
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
--
-------------------------------------------------------------------------------

32
module HscMain
dterei's avatar
dterei committed
33
    (
34 35 36 37
    -- * Making an HscEnv
      newHscEnv

    -- * Compiling complete source files
38 39
    , Messager, batchMsg
    , HscStatus (..)
40
    , hscIncrementalCompile
41 42 43
    , hscCompileCmmFile
    , hscCompileCore

44
    , hscIncrementalFrontend
45 46 47 48 49 50 51 52

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

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

61 62 63 64
    -- * Safe Haskell
    , hscCheckSafe
    , hscGetSafe

65 66 67 68 69
    -- * Support for interactive evaluation
    , hscParseIdentifier
    , hscTcRcLookupName
    , hscTcRnGetInfo
#ifdef GHCI
dterei's avatar
dterei committed
70
    , hscIsGHCiMonad
71
    , hscGetModuleInterface
72
    , hscRnImportDecls
73
    , hscTcRnLookupRdrName
74
    , hscStmt, hscStmtWithLocation, hscParsedStmt
75
    , hscDecls, hscDeclsWithLocation
vivian's avatar
vivian committed
76
    , hscTcExpr, hscImport, hscKcType
77
    , hscParseExpr
78
    , hscCompileCoreExpr
79 80
    -- * Low-level exports for hooks
    , hscCompileCoreExpr'
81
#endif
Edsko de Vries's avatar
Edsko de Vries committed
82 83
      -- We want to make sure that we export enough to be able to redefine
      -- hscFileFrontEnd in client code
84
    , hscParse', hscSimplify', hscDesugar', tcRnModule'
Edsko de Vries's avatar
Edsko de Vries committed
85
    , getHscEnv
86 87 88
    , hscSimpleIface', hscNormalIface'
    , oneShotMsg
    , hscFileFrontEnd, genericHscFrontend, dumpIfaceStats
89
    ) where
90

91
#ifdef GHCI
Simon Marlow's avatar
Simon Marlow committed
92
import Id
93
import BasicTypes       ( HValue )
94
import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
95
import Linker
96
import CoreTidy         ( tidyExpr )
97 98
import Type             ( Type )
import {- Kind parts of -} Type         ( Kind )
99
import CoreLint         ( lintInteractiveExpr )
100
import VarEnv           ( emptyTidyEnv )
101
import THNames          ( templateHaskellNames )
102
import ConLike
103 104

import GHC.Exts
105 106
#endif

107
import Panic
108 109
import Module
import Packages
Simon Marlow's avatar
Simon Marlow committed
110 111
import RdrName
import HsSyn
112
import CoreSyn
Ian Lynagh's avatar
Ian Lynagh committed
113
import StringBuffer
114
import Parser
115
import Lexer
116 117
import SrcLoc
import TcRnDriver
118
import TcIface          ( typecheckIface )
119
import TcRnMonad
120
import IfaceEnv         ( initNameCache )
121 122
import LoadIface        ( ifaceStats, initExternalPackageState
                        , findAndReadIface )
123
import PrelInfo
Simon Marlow's avatar
Simon Marlow committed
124
import MkIface
125 126
import Desugar
import SimplCore
Simon Marlow's avatar
Simon Marlow committed
127
import TidyPgm
128
import CorePrep
129 130
import CoreToStg        ( coreToStg )
import qualified StgCmm ( codeGen )
131 132
import StgSyn
import CostCentre
133
import ProfInit
134 135
import TyCon
import Name
136
import SimplStg         ( stg2stg )
137
import Cmm
138
import CmmParse         ( parseCmmFile )
139
import CmmBuildInfoTables
Edward Z. Yang's avatar
Edward Z. Yang committed
140
import CmmPipeline
141
import CmmInfo
142
import CodeOutput
143
import NameEnv          ( emptyNameEnv )
144 145
import NameSet          ( emptyNameSet )
import InstEnv
146
import FamInstEnv
Thomas Schilling's avatar
Thomas Schilling committed
147
import Fingerprint      ( Fingerprint )
148
import Hooks
149
import Maybes
150

151
import DynFlags
152
import ErrUtils
153

154
import Outputable
155
import HscStats         ( ppSourceStats )
156
import HscTypes
157
import FastString
158
import UniqSupply
159
import Bag
Thomas Schilling's avatar
Thomas Schilling committed
160
import Exception
161 162 163
import qualified Stream
import Stream (Stream)

164
import Util
Simon Marlow's avatar
Simon Marlow committed
165

166
import Data.List
Simon Marlow's avatar
Simon Marlow committed
167 168
import Control.Monad
import Data.IORef
169
import System.FilePath as FilePath
170
import System.Directory
Alan Zimmerman's avatar
Alan Zimmerman committed
171
import qualified Data.Map as Map
dterei's avatar
dterei committed
172

Thomas Schilling's avatar
Thomas Schilling committed
173
#include "HsVersions.h"
174

175

dterei's avatar
dterei committed
176 177 178 179 180
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
181

182
newHscEnv :: DynFlags -> IO HscEnv
183
newHscEnv dflags = do
dterei's avatar
dterei committed
184 185
    eps_var <- newIORef initExternalPackageState
    us      <- mkSplitUniqSupply 'r'
186
    nc_var  <- newIORef (initNameCache us allKnownKeyNames)
187
    fc_var  <- newIORef emptyModuleEnv
188
    return HscEnv {  hsc_dflags       = dflags,
dterei's avatar
dterei committed
189 190
                     hsc_targets      = [],
                     hsc_mod_graph    = [],
191
                     hsc_IC           = emptyInteractiveContext dflags,
dterei's avatar
dterei committed
192 193 194 195
                     hsc_HPT          = emptyHomePackageTable,
                     hsc_EPS          = eps_var,
                     hsc_NC           = nc_var,
                     hsc_FC           = fc_var,
196
                     hsc_type_env_var = Nothing }
Thomas Schilling's avatar
Thomas Schilling committed
197

198

199 200 201 202 203 204 205
allKnownKeyNames :: [Name]      -- Put here to avoid loops involving DsMeta,
allKnownKeyNames =              -- where templateHaskellNames are defined
    knownKeyNames
#ifdef GHCI
        ++ templateHaskellNames
#endif

206
-- -----------------------------------------------------------------------------
207

208
getWarnings :: Hsc WarningMessages
dterei's avatar
dterei committed
209
getWarnings = Hsc $ \_ w -> return (w, w)
210 211

clearWarnings :: Hsc ()
dterei's avatar
dterei committed
212
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
213 214

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

getHscEnv :: Hsc HscEnv
dterei's avatar
dterei committed
218
getHscEnv = Hsc $ \e w -> return (e, w)
219 220 221

handleWarnings :: Hsc ()
handleWarnings = do
dterei's avatar
dterei committed
222 223 224 225
    dflags <- getDynFlags
    w <- getWarnings
    liftIO $ printOrThrowWarnings dflags w
    clearWarnings
226 227 228 229 230

-- | 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
231 232
    logWarnings warns
    when (not $ isEmptyBag errs) $ throwErrors errs
233 234 235 236

-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
237 238 239 240 241

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

-- | 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
266 267 268
    ((warns,_errs), mb_r) <- liftIO $ ioA
    logWarnings warns
    return mb_r
269 270 271 272 273

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

#ifdef GHCI
274 275 276 277 278
hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name]
hscTcRnLookupRdrName hsc_env0 rdr_name 
  = runInteractiveHsc hsc_env0 $ 
    do { hsc_env <- getHscEnv
       ; ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name }
279 280 281
#endif

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
282 283 284
hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe' $ tcRnLookupName hsc_env name
dterei's avatar
dterei committed
285 286 287
      -- 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.
288

289
hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
290 291 292 293
hscTcRnGetInfo hsc_env0 name
  = runInteractiveHsc hsc_env0 $
    do { hsc_env <- getHscEnv
       ; ioMsgMaybe' $ tcRnGetInfo hsc_env name }
294 295

#ifdef GHCI
dterei's avatar
dterei committed
296
hscIsGHCiMonad :: HscEnv -> String -> IO Name
Edsko de Vries's avatar
Edsko de Vries committed
297
hscIsGHCiMonad hsc_env name
298
  = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name
dterei's avatar
dterei committed
299

300
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
301 302 303
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ getModuleInterface hsc_env mod
304 305 306

-- -----------------------------------------------------------------------------
-- | Rename some import declarations
307
hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
308 309 310
hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
311 312
#endif

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

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

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

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

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

dterei's avatar
dterei committed
337
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
338

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

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

            -- 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
364
                            $ filter (not . (isPrefixOf "<"))
365 366 367 368 369 370
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

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

376 377
            return HsParsedModule {
                      hpm_module    = rdr_module,
Alan Zimmerman's avatar
Alan Zimmerman committed
378 379 380 381 382
                      hpm_src_files = srcs2,
                      hpm_annotations
                              = (Map.fromListWith (++) $ annotations pst,
                                 Map.fromList $ ((noSrcSpan,comment_q pst)
                                                 :(annotations_comments pst)))
383
                   }
Simon Marlow's avatar
Simon Marlow committed
384

Thomas Schilling's avatar
Thomas Schilling committed
385 386 387
-- 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
388
type RenamedStuff =
Simon Marlow's avatar
Simon Marlow committed
389
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
390
                Maybe LHsDocString))
Simon Marlow's avatar
Simon Marlow committed
391

Thomas Schilling's avatar
Thomas Schilling committed
392
-- | Rename and typecheck a module, additionally returning the renamed syntax
393
hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
394
                   -> IO (TcGblEnv, RenamedStuff)
dterei's avatar
dterei committed
395
hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
396
    tc_result <- tcRnModule' hsc_env mod_summary True rdr_module
Thomas Schilling's avatar
Thomas Schilling committed
397

398 399 400 401 402 403
        -- 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
404

405
    return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
406

407 408 409 410 411 412 413 414
-- 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

415 416 417
    -- See Note [Safe Haskell Overlapping Instances Implementation]
    -- although this is used for more than just that failure case.
    (tcSafeOK, whyUnsafe) <- liftIO $ readIORef (tcg_safeInfer tcg_res)
418
    dflags   <- getDynFlags
419
    let allSafeOK = safeInferred dflags && tcSafeOK
420

421 422 423
    -- end of the safe haskell line, how to respond to user?
    if not (safeHaskellOn dflags) || (safeInferOn dflags && not allSafeOK)
        -- if safe Haskell off or safe infer failed, mark unsafe
424
        then markUnsafeInfer tcg_res whyUnsafe
425

426
        -- module (could be) safe, throw warning if needed
427 428
        else do
            tcg_res' <- hscCheckSafeImports tcg_res
429
            safe <- liftIO $ fst <$> readIORef (tcg_safeInfer tcg_res')
430 431 432 433 434 435 436 437 438
            when safe $ do
              case wopt Opt_WarnSafe dflags of
                True -> (logWarnings $ unitBag $ mkPlainWarnMsg dflags
                       (warnSafeOnLoc dflags) $ errSafe tcg_res')
                False | safeHaskell dflags == Sf_Trustworthy &&
                        wopt Opt_WarnTrustworthySafe dflags ->
                  (logWarnings $ unitBag $ mkPlainWarnMsg dflags
                    (trustworthyOnLoc dflags) $ errTwthySafe tcg_res')
                False -> return ()
439 440 441
            return tcg_res'
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
442
    errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
443 444
    errTwthySafe t = quotes (pprMod t)
      <+> text "is marked as Trustworthy but has been inferred as safe!"
445

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

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

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

dterei's avatar
dterei committed
463
-- | Make a 'ModIface' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
464 465 466 467
-- 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.
468
makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
469
                -> IO (ModIface,Bool)
470 471
makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do
    safe_mode <- hscGetSafeMode tc_result
472
    liftIO $ do
473 474
        mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode
                  details tc_result
Simon Marlow's avatar
Simon Marlow committed
475

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

481

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

{-
489 490 491 492
                   --------------------------------
                        The compilation proper
                   --------------------------------

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

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


525 526
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
-- | This function runs GHC's frontend with recompilation
-- avoidance. Specifically, it checks if recompilation is needed,
-- and if it is, it parses and typechecks the input module.
-- It does not write out the results of typechecking (See
-- compileOne and hscIncrementalCompile).
hscIncrementalFrontend :: Bool -- always do basic recompilation check?
                       -> Maybe TcGblEnv
                       -> Maybe Messager
                       -> ModSummary
                       -> SourceModified
                       -> Maybe ModIface  -- Old interface, if available
                       -> (Int,Int)       -- (i,n) = module i of n (for msgs)
                       -> Hsc (Either ModIface (FrontendResult, Maybe Fingerprint))

hscIncrementalFrontend
Simon Marlow's avatar
Simon Marlow committed
542
  always_do_basic_recompilation_check m_tc_result
543
  mHscMessage mod_summary source_modified mb_old_iface mod_index
544
    = do
545
    hsc_env <- getHscEnv
546 547 548 549

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

551
        skip iface = do
552
            liftIO $ msg UpToDate
553
            return $ Left iface
dterei's avatar
dterei committed
554

555
        compile mb_old_hash reason = do
556 557 558
            liftIO $ msg reason
            result <- genericHscFrontend mod_summary
            return $ Right (result, mb_old_hash)
dterei's avatar
dterei committed
559 560 561 562

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

564 565 566
    case m_tc_result of
         Just tc_result
          | not always_do_basic_recompilation_check ->
567
             return $ Right (FrontendTypecheck tc_result, Nothing)
568 569 570
         _ -> do
            (recomp_reqd, mb_checked_iface)
                <- {-# SCC "checkOldIface" #-}
571
                   liftIO $ checkOldIface hsc_env mod_summary
572 573 574 575 576 577 578 579
                                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) ->
Simon Marlow's avatar
Simon Marlow committed
580 581 582 583 584 585 586 587 588 589 590 591 592
                    -- 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.
593 594 595 596 597 598 599 600 601 602
                    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 ->
603
                        return $ Right (FrontendTypecheck tc_result, mb_old_hash)
604

605
genericHscFrontend :: ModSummary -> Hsc FrontendResult
606 607 608
genericHscFrontend mod_summary =
  getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)

609 610 611 612 613 614
genericHscFrontend' :: ModSummary -> Hsc FrontendResult
genericHscFrontend' mod_summary
    | ms_hsc_src mod_summary == HsBootMerge
    = FrontendMerge `fmap` hscMergeFrontEnd mod_summary
    | otherwise
    = FrontendTypecheck `fmap` hscFileFrontEnd mod_summary
615

616 617 618 619
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

Austin Seipp's avatar
Austin Seipp committed
620
-- Compile Haskell/boot in OneShot mode.
621 622 623 624 625 626 627 628 629 630 631 632 633
hscIncrementalCompile :: Bool
                      -> Maybe TcGblEnv
                      -> Maybe Messager
                      -> HscEnv
                      -> ModSummary
                      -> SourceModified
                      -> Maybe ModIface
                      -> (Int,Int)
                      -- HomeModInfo does not contain linkable, since we haven't
                      -- code-genned yet
                      -> IO (HscStatus, HomeModInfo)
hscIncrementalCompile always_do_basic_recompilation_check m_tc_result
    mHscMessage hsc_env' mod_summary source_modified mb_old_iface mod_index
634
  = do
dterei's avatar
dterei committed
635 636 637 638
    -- 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
639
        hsc_env = hsc_env'{ hsc_type_env_var = Just (mod, type_env_var) }
640

641 642 643 644 645 646
    -- NB: enter Hsc monad here so that we don't bail out early with
    -- -Werror on typechecker warnings; we also want to run the desugarer
    -- to get those warnings too. (But we'll always exit at that point
    -- because the desugarer runs ioMsgMaybe.)
    runHsc hsc_env $ do
    let dflags = hsc_dflags hsc_env
647

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    e <- hscIncrementalFrontend always_do_basic_recompilation_check m_tc_result mHscMessage
            mod_summary source_modified mb_old_iface mod_index
    case e of
        Left iface -> do
            details <- liftIO $ genModDetails hsc_env iface
            return (HscUpToDate, HomeModInfo{
                hm_details = details,
                hm_iface = iface,
                hm_linkable = Nothing
            })
        Right (result, mb_old_hash) -> do
            (status, hmi, no_change) <- case result of
                FrontendTypecheck tc_result ->
                    if hscTarget dflags /= HscNothing &&
                       ms_hsc_src mod_summary == HsSrcFile
                       then finish              hsc_env mod_summary tc_result mb_old_hash
                       else finishTypecheckOnly hsc_env mod_summary tc_result mb_old_hash
                FrontendMerge raw_iface ->
                            finishMerge         hsc_env mod_summary raw_iface mb_old_hash
            liftIO $ hscMaybeWriteIface dflags (hm_iface hmi) no_change mod_summary
            return (status, hmi)

-- Generates and writes out the final interface for an hs-boot merge.
finishMerge :: HscEnv
            -> ModSummary
            -> ModIface
            -> Maybe Fingerprint
            -> Hsc (HscStatus, HomeModInfo, Bool)
finishMerge hsc_env summary iface0 mb_old_hash = do
    MASSERT( ms_hsc_src summary == HsBootMerge )
    (iface, changed) <- liftIO $ mkIfaceDirect hsc_env mb_old_hash iface0
    details <- liftIO $ genModDetails hsc_env iface
    let dflags = hsc_dflags hsc_env
        hsc_status =
682
            case hscTarget dflags of
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
                HscNothing -> HscNotGeneratingCode
                _ -> HscUpdateBootMerge
    return (hsc_status,
            HomeModInfo{ hm_details  = details,
                         hm_iface    = iface,
                         hm_linkable = Nothing },
            changed)

-- Generates and writes out the final interface for a typecheck.
finishTypecheckOnly :: HscEnv
              -> ModSummary
              -> TcGblEnv
              -> Maybe Fingerprint
              -> Hsc (HscStatus, HomeModInfo, Bool)
finishTypecheckOnly hsc_env summary tc_result mb_old_hash = do
    let dflags = hsc_dflags hsc_env
    MASSERT( hscTarget dflags == HscNothing || ms_hsc_src summary == HsBootFile )
    (iface, changed, details) <- liftIO $ hscSimpleIface hsc_env tc_result mb_old_hash
    let hsc_status =
          case (hscTarget dflags, ms_hsc_src summary) of
            (HscNothing, _) -> HscNotGeneratingCode
            (_, HsBootFile) -> HscUpdateBoot
            _ -> panic "finishTypecheckOnly"
    return (hsc_status,
            HomeModInfo{ hm_details  = details,
                         hm_iface    = iface,
                         hm_linkable = Nothing },
            changed)

-- Runs the post-typechecking frontend (desugar and simplify),
-- and then generates and writes out the final interface. We want
-- to write the interface AFTER simplification so we can get
-- as up-to-date and good unfoldings and other info as possible
-- in the interface file.  This is only ever run for HsSrcFile,
-- and NOT for HscNothing.
finish :: HscEnv
       -> ModSummary
       -> TcGblEnv
       -> Maybe Fingerprint
       -> Hsc (HscStatus, HomeModInfo, Bool)
finish hsc_env summary tc_result mb_old_hash = do
    let dflags = hsc_dflags hsc_env
    MASSERT( ms_hsc_src summary == HsSrcFile )
    MASSERT( hscTarget dflags /= HscNothing )
    guts0 <- hscDesugar' (ms_location summary) tc_result
    guts <- hscSimplify' guts0
    (iface, changed, details, cgguts) <- liftIO $ hscNormalIface hsc_env guts mb_old_hash

    return (HscRecomp cgguts summary,
            HomeModInfo{ hm_details  = details,
                         hm_iface    = iface,
                         hm_linkable = Nothing },
            changed)

hscMaybeWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO ()
hscMaybeWriteIface dflags iface changed summary =
    let force_write_interface = gopt Opt_WriteInterface dflags
        write_interface = case hscTarget dflags of
                            HscNothing      -> False
                            HscInterpreted  -> False
                            _               -> True
    in when (write_interface || force_write_interface) $
            hscWriteIface dflags iface changed summary
746

747 748 749 750
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

751 752
genModDetails :: HscEnv -> ModIface -> IO ModDetails
genModDetails hsc_env old_iface
753
  = do
dterei's avatar
dterei committed
754
    new_details <- {-# SCC "tcRnIface" #-}
755 756
                   initIfaceCheck hsc_env (typecheckIface old_iface)
    dumpIfaceStats hsc_env
dterei's avatar
dterei committed
757
    return new_details
758

759 760 761 762
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

763 764
oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
oneShotMsg hsc_env recomp =
dterei's avatar
dterei committed
765
    case recomp of
766
        UpToDate ->
767 768
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
769
        _ ->
770 771
            return ()

772 773
batchMsg :: Messager
batchMsg hsc_env mod_index recomp mod_summary =
dterei's avatar
dterei committed
774
    case recomp of
775 776 777
        MustCompile -> showMsg "Compiling " ""
        UpToDate
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  " ""
dterei's avatar
dterei committed
778
            | otherwise -> return ()
779
        RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
dterei's avatar
dterei committed
780
    where
Ian Lynagh's avatar
Ian Lynagh committed
781
        dflags = hsc_dflags hsc_env
782
        showMsg msg reason =
Ian Lynagh's avatar
Ian Lynagh committed
783
            compilationProgressMsg dflags $
784
            (showModuleIndex mod_index ++
Ian Lynagh's avatar
Ian Lynagh committed
785
            msg ++ showModMsg dflags (hscTarget dflags)
786 787
                              (recompileRequired recomp) mod_summary)
                ++ reason
788

789 790 791
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
792

793 794
-- | Given an 'HsBootMerge' 'ModSummary', merges all @hs-boot@ files
-- under this module name into a composite, publically visible 'ModIface'.
795 796 797
hscMergeFrontEnd :: ModSummary -> Hsc ModIface
hscMergeFrontEnd mod_summary = do
    hsc_env <- getHscEnv
798 799 800 801 802 803 804 805 806 807 808 809 810
    MASSERT( ms_hsc_src mod_summary == HsBootMerge )
    let dflags = hsc_dflags hsc_env
    -- TODO: actually merge in signatures from external packages.
    -- Grovel in HPT if necessary
    -- TODO: replace with 'computeInterface'
    let hpt = hsc_HPT hsc_env
    -- TODO multiple mods
    let name = moduleName (ms_mod mod_summary)
        mod = mkModule (thisPackage dflags) name
        is_boot = True
    iface0 <- case lookupHptByModule hpt mod of
        Just hm -> return (hm_iface hm)
        Nothing -> do
811
            mb_iface0 <- liftIO . initIfaceCheck hsc_env
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
                    $ findAndReadIface (text "merge-requirements")
                                       mod is_boot
            case mb_iface0 of
                Succeeded (i, _) -> return i
                Failed err -> liftIO $ throwGhcExceptionIO
                                (ProgramError (showSDoc dflags err))
    let iface = iface0 {
                    mi_hsc_src = HsBootMerge,
                    -- TODO: mkDependencies doublecheck
                    mi_deps = (mi_deps iface0) {
                        dep_mods = (name, is_boot)
                                 : dep_mods (mi_deps iface0)
                      }
                    }
    return iface

-- | Given a 'ModSummary', parses and typechecks it, returning the
-- 'TcGblEnv' resulting from type-checking.
830
hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
831
hscFileFrontEnd mod_summary = do
832
    MASSERT( ms_hsc_src mod_summary == HsBootFile || ms_hsc_src mod_summary == HsSrcFile )
833
    hpm <- hscParse' mod_summary
834
    hsc_env <- getHscEnv
835 836
    tcg_env <- tcRnModule' hsc_env mod_summary False hpm
    return tcg_env
837 838

--------------------------------------------------------------
839
-- Safe Haskell
840 841
--------------------------------------------------------------

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
-- 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.


862 863 864 865 866 867 868 869 870 871 872
-- 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.
873 874 875
--
-- It used to be that we only did safe inference on modules that had no Safe
-- Haskell flags, but now we perform safe inference on all modules as we want
876 877
-- to allow users to set the `-fwarn-safe`, `-fwarn-unsafe` and
-- `-fwarn-trustworthy-safe` flags on Trustworthy and Unsafe modules so that a
878 879 880 881 882 883 884
-- user can ensure their assumptions are correct and see reasons for why a
-- module is safe or unsafe.
--
-- This is tricky as we must be careful when we should throw an error compared
-- to just warnings. For checking safe imports we manage it as two steps. First
-- we check any imports that are required to be safe, then we check all other
-- imports to see if we can infer them to be safe.
885 886 887 888 889 890 891 892 893


-- | 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
894
    tcg_env' <- checkSafeImports dflags tcg_env
895
    checkRULES dflags tcg_env'
896

dterei's avatar
dterei committed
897
  where
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
    checkRULES dflags tcg_env' = do
      case safeLanguageOn dflags of
          True -> do
              -- XSafe: we nuke user written RULES
              logWarnings $ warns dflags (tcg_rules tcg_env')
              return tcg_env' { tcg_rules = [] }
          False
                -- SafeInferred: user defined RULES, so not safe
              | safeInferOn dflags && not (null $ tcg_rules tcg_env')
              -> markUnsafeInfer tcg_env' $ warns dflags (tcg_rules tcg_env')

                -- Trustworthy OR SafeInferred: with no RULES
              | otherwise
              -> return tcg_env'

Ian Lynagh's avatar
Ian Lynagh committed
913 914 915
    warns dflags rules = listToBag $ map (warnRules dflags) rules
    warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
        mkPlainWarnMsg dflags loc $
916
            text "Rule \"" <> ftext (snd $ unLoc n) <> text "\" ignored" $+$
dterei's avatar
dterei committed
917
            text "User defined rules are disabled under Safe Haskell"
918

919 920 921 922 923 924
-- | 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.
925
--
926 927 928 929 930
-- 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].
931 932
checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags tcg_env
933
    = do
934 935 936
        imps <- mapM condense imports'
        let (safeImps, regImps) = partition (\(_,_,s) -> s) imps

937 938 939 940 941
        -- We want to use the warning state specifically for detecting if safe
        -- inference has failed, so store and clear any existing warnings.
        oldErrs <- getWarnings
<