HscMain.hs 60.5 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3
4
%
\begin{code}
5
-- | Main API for compiling plain Haskell source code.
6
--
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-- This module implements compilation of a Haskell source.  It is
-- /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
-- "interactive" mode (GHCi).  There are also entry points for
-- 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.
26
--
27
module HscMain
28
29
30
31
32
33
    ( 
    -- * Making an HscEnv
      newHscEnv

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

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

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

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

71
    ) where
72

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

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

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

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

import Control.Monad
149
import Data.Maybe
Simon Marlow's avatar
Simon Marlow committed
150
import Data.IORef
151
\end{code}
Thomas Schilling's avatar
Thomas Schilling committed
152
#include "HsVersions.h"
153

154
155
156

%************************************************************************
%*									*
157
158
159
160
161
		Initialisation
%*									*
%************************************************************************

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

184

185
knownKeyNames :: [Name]      -- Put here to avoid loops involving DsMeta,
186
187
knownKeyNames =              -- where templateHaskellNames are defined
  map getName wiredInThings 
188
    ++ basicKnownKeyNames
189
#ifdef GHCI
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
  return a    = Hsc $ \_ w -> return (a, w)
  Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
201
                                 case k a of
dterei's avatar
dterei committed
202
                                   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
207
208

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

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

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

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

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

getDynFlags :: Hsc DynFlags
dterei's avatar
dterei committed
226
getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
227
228
229
230
231
232
233
234
235
236
237
238
239
240

handleWarnings :: Hsc ()
handleWarnings = do
  dflags <- getDynFlags
  w <- getWarnings
  liftIO $ printOrThrowWarnings dflags w
  clearWarnings

-- | log warning in the monad, and if there are errors then
-- throw a SourceError exception.
logWarningsReportErrors :: Messages -> Hsc ()
logWarningsReportErrors (warns,errs) = do
  logWarnings warns
  when (not (isEmptyBag errs)) $ do
241
242
243
244
245
    throwErrors errs

-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

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

-- | like ioMsgMaybe, except that we ignore error messages and return
-- 'Nothing' instead.
ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
ioMsgMaybe' ioA = do
  ((warns,_errs), mb_r) <- liftIO $ ioA
  logWarnings warns
  return mb_r

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

#ifdef GHCI
hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
hscTcRnLookupRdrName hsc_env rdr_name = 
  runHsc hsc_env $ ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
#endif

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
hscTcRcLookupName hsc_env name = 
  runHsc hsc_env $ ioMsgMaybe' $ tcRnLookupName hsc_env name
    -- ignore errors: the only error we're likely to get is
    -- "name not found", and the Maybe in the return type
    -- is used to indicate that.

hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [Instance]))
hscTcRnGetInfo hsc_env name =
  runHsc hsc_env $ ioMsgMaybe' $ tcRnGetInfo hsc_env name

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

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

311
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
312
-- | parse a file, returning the abstract syntax
313
314
315
316
317
318

hscParse :: HscEnv -> ModSummary -> IO (Located (HsModule RdrName))
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
hscParse' :: ModSummary -> Hsc (Located (HsModule RdrName))
319
320
321
322
hscParse' mod_summary = do
  dflags <- getDynFlags
  let src_filename  = ms_hspp_file mod_summary
      maybe_src_buf = ms_hspp_buf  mod_summary
323

Thomas Schilling's avatar
Thomas Schilling committed
324
   --------------------------  Parser  ----------------
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
  liftIO $ showPass dflags "Parser"
  {-# SCC "Parser" #-} do

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

  let loc = mkRealSrcLoc (mkFastString src_filename) 1 1

  case unP parseModule (mkPState dflags buf loc) of
    PFailed span err ->
      liftIO $ throwOneError (mkPlainErrMsg span err)

    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
      return rdr_module
       -- ToDo: free the string buffer later.
Simon Marlow's avatar
Simon Marlow committed
349

Thomas Schilling's avatar
Thomas Schilling committed
350
351
352
-- 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.
Simon Marlow's avatar
Simon Marlow committed
353
354
type RenamedStuff = 
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
355
                Maybe LHsDocString))
Simon Marlow's avatar
Simon Marlow committed
356

Thomas Schilling's avatar
Thomas Schilling committed
357
-- | Rename and typecheck a module, additionally returning the renamed syntax
358
359
hscTypecheckRename :: HscEnv -> ModSummary -> Located (HsModule RdrName)
                   -> IO (TcGblEnv, RenamedStuff)
360
361
362
363
364
hscTypecheckRename hsc_env mod_summary rdr_module =
  runHsc hsc_env $ do
    tc_result <- {-# SCC "Typecheck-Rename" #-}
                 ioMsgMaybe $ 
                   tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
Thomas Schilling's avatar
Thomas Schilling committed
365

366
367
368
369
370
371
        -- 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
372

373
    return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
374
375

-- | Convert a typechecked module to Core
376
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
377
378
hscDesugar hsc_env mod_summary tc_result =
  runHsc hsc_env $ hscDesugar' mod_summary tc_result
379
380

hscDesugar' :: ModSummary -> TcGblEnv -> Hsc ModGuts
381
382
383
hscDesugar' mod_summary tc_result = do
  hsc_env <- getHscEnv
  r <- ioMsgMaybe $ deSugar hsc_env (ms_location mod_summary) tc_result
384

385
386
387
388
  -- 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
389
390
391
392
393
394

-- | Make a 'ModIface' from the results of typechecking.  Used when
-- 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.
395
makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
396
                -> IO (ModIface,Bool)
397
398
399
makeSimpleIface hsc_env maybe_old_iface tc_result details =
  runHsc hsc_env $ ioMsgMaybe $ 
      mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
Simon Marlow's avatar
Simon Marlow committed
400
401
402

-- | Make a 'ModDetails' from the results of typechecking.  Used when
-- typechecking only, as opposed to full compilation.
403
404
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
Simon Marlow's avatar
Simon Marlow committed
405
406
\end{code}

407
408
409
%************************************************************************
%*									*
		The main compiler pipeline
410
411
412
%*									*
%************************************************************************

413
414
415
416
417
                   --------------------------------
                        The compilation proper
                   --------------------------------

It's the task of the compilation proper to compile Haskell, hs-boot and
dterei's avatar
dterei committed
418
core files to either byte-code, hard-code (C, asm, LLVM, ect) or to
419
420
nothing at all (the module is still parsed and type-checked. This
feature is mostly used by IDE's and the likes).
421
422
423
424
425
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
targets byte-code.
The modes are kept separate because of their different types and meanings.
426
427
428
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
429
430
431
432
433
434
435
436
437
438
439
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.

440
441
442
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.

443
\begin{code}
444

445
-- Status of a compilation to hard-code or nothing.
Thomas Schilling's avatar
Thomas Schilling committed
446
data HscStatus' a
447
    = HscNoRecomp
Thomas Schilling's avatar
Thomas Schilling committed
448
    | HscRecomp
449
450
       (Maybe FilePath)
            -- Has stub files.  This is a hack. We can't compile C files here
Thomas Schilling's avatar
Thomas Schilling committed
451
452
453
454
455
456
457
458
            -- since it's done in DriverPipeline. For now we just return True
            -- if we want the caller to compile them for us.
       a

-- This is a bit ugly.  Since we use a typeclass below and would like to avoid
-- functional dependencies, we have to parameterise the typeclass over the
-- result type.  Therefore we need to artificially distinguish some types.  We
-- do this by adding type tags which will simply be ignored by the caller.
459
type HscStatus         = HscStatus' ()
460
461
type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
    -- INVARIANT: result is @Nothing@ <=> input was a boot file
Thomas Schilling's avatar
Thomas Schilling committed
462

463
464
465
type OneShotResult     = HscStatus
type BatchResult       = (HscStatus, ModIface, ModDetails)
type NothingResult     = (HscStatus, ModIface, ModDetails)
Thomas Schilling's avatar
Thomas Schilling committed
466
type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
467

468
469
-- ToDo: The old interface and module index are only using in 'batch' and
--       'interactive' mode. They should be removed from 'oneshot' mode.
470
type Compiler result =  HscEnv
471
                     -> ModSummary
472
                     -> SourceModified
473
474
                     -> Maybe ModIface  -- Old interface, if available
                     -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
475
                     -> IO result
476

477
478
479
data HsCompiler a
  = HsCompiler {
    -- | Called when no recompilation is necessary.
480
481
    hscNoRecomp :: ModIface
                -> Hsc a,
482
483

    -- | Called to recompile the module.
484
485
    hscRecompile :: ModSummary -> Maybe Fingerprint
                 -> Hsc a,
486

487
488
    hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
               -> Hsc a,
489

490
    -- | Code generation for Boot modules.
491
492
    hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
                     -> Hsc a,
493
494

    -- | Code generation for normal modules.
495
496
    hscGenOutput :: ModGuts  -> ModSummary -> Maybe Fingerprint
                 -> Hsc a
497
498
  }

499
genericHscCompile :: HsCompiler a
500
501
                  -> (HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ())
                  -> HscEnv -> ModSummary -> SourceModified
Thomas Schilling's avatar
Thomas Schilling committed
502
                  -> Maybe ModIface -> Maybe (Int, Int)
503
504
                  -> IO a
genericHscCompile compiler hscMessage hsc_env
505
                  mod_summary source_modified
506
507
                  mb_old_iface0 mb_mod_index
 = do
Thomas Schilling's avatar
Thomas Schilling committed
508
509
     (recomp_reqd, mb_checked_iface)
         <- {-# SCC "checkOldIface" #-}
510
            checkOldIface hsc_env mod_summary 
511
                          source_modified mb_old_iface0
Thomas Schilling's avatar
Thomas Schilling committed
512
513
514
515
     -- 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540

     let
       skip iface = do
         hscMessage hsc_env mb_mod_index RecompNotRequired mod_summary
         runHsc hsc_env $ hscNoRecomp compiler iface

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

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

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

Thomas Schilling's avatar
Thomas Schilling committed
541
     case mb_checked_iface of
542
543
544
545
546
547
548
       Just iface | not recomp_reqd ->
           if mi_used_th iface && not stable
               then compile RecompForcedByTH
               else skip iface
       _otherwise ->
           compile RecompRequired

Thomas Schilling's avatar
Thomas Schilling committed
549

550
551
hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
hscCheckRecompBackend compiler tc_result 
552
                   hsc_env mod_summary source_modified mb_old_iface _m_of_n
553
  = do
554
555
     (recomp_reqd, mb_checked_iface)
         <- {-# SCC "checkOldIface" #-}
556
            checkOldIface hsc_env mod_summary
557
                          source_modified mb_old_iface
558
559
560
561

     let mb_old_hash = fmap mi_iface_hash mb_checked_iface
     case mb_checked_iface of
       Just iface | not recomp_reqd
562
563
564
           -> runHsc hsc_env $ 
                 hscNoRecomp compiler
                             iface{ mi_globals = Just (tcg_rdr_env tc_result) }
565
       _otherwise
566
567
           -> runHsc hsc_env $
                 hscBackend compiler tc_result mod_summary mb_old_hash
568

569
genericHscRecompile :: HsCompiler a
570
                    -> ModSummary -> Maybe Fingerprint
571
                    -> Hsc a
572
genericHscRecompile compiler mod_summary mb_old_hash
Thomas Schilling's avatar
Thomas Schilling committed
573
574
575
576
  | ExtCoreFile <- ms_hsc_src mod_summary =
      panic "GHC does not currently support reading External Core files"
  | otherwise = do
      tc_result <- hscFileFrontEnd mod_summary
577
578
      hscBackend compiler tc_result mod_summary mb_old_hash

579
genericHscBackend :: HsCompiler a
580
                  -> TcGblEnv -> ModSummary -> Maybe Fingerprint
581
                  -> Hsc a
582
583
584
585
genericHscBackend compiler tc_result mod_summary mb_old_hash
  | HsBootFile <- ms_hsc_src mod_summary =
      hscGenBootOutput compiler tc_result mod_summary mb_old_hash
  | otherwise = do
586
      guts <- hscDesugar' mod_summary tc_result
587
      hscGenOutput compiler guts mod_summary mb_old_hash
Thomas Schilling's avatar
Thomas Schilling committed
588

589
590
591
592
593
compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
  runHsc hsc_env $
    hscBackend comp tcg ms' Nothing

594
595
596
597
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

598
599
600
601
hscOneShotCompiler :: HsCompiler OneShotResult
hscOneShotCompiler =
  HsCompiler {

602
    hscNoRecomp = \_old_iface -> do
603
604
      hsc_env <- getHscEnv
      liftIO $ dumpIfaceStats hsc_env
605
606
607
608
      return HscNoRecomp

  , hscRecompile = genericHscRecompile hscOneShotCompiler

dterei's avatar
dterei committed
609
  , hscBackend = \tc_result mod_summary mb_old_hash -> do
610
611
       dflags <- getDynFlags
       case hscTarget dflags of
612
         HscNothing -> return (HscRecomp Nothing ())
613
         _otherw    -> genericHscBackend hscOneShotCompiler
614
                                         tc_result mod_summary mb_old_hash
615

616
617
618
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
       (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
       hscWriteIface iface changed mod_summary
619
       return (HscRecomp Nothing ())
620
621

  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
622
623
       guts <- hscSimplify' guts0
       (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface
624
625
626
627
       hscWriteIface iface changed mod_summary
       hasStub <- hscGenHardCode cgguts mod_summary
       return (HscRecomp hasStub ())
  }
628

Thomas Schilling's avatar
Thomas Schilling committed
629
-- Compile Haskell, boot and extCore in OneShot mode.
630
hscCompileOneShot :: Compiler OneShotResult
631
632
hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  = do
633
634
       -- One-shot mode needs a knot-tying mutable variable for interface
       -- files.  See TcRnTypes.TcGblEnv.tcg_type_env_var.
635
      type_env_var <- newIORef emptyNameEnv
636
637
638
639
640
641
642
643
      let
         mod = ms_mod mod_summary
         hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
      ---
      genericHscCompile hscOneShotCompiler
                        oneShotMsg hsc_env' mod_summary src_changed
                        mb_old_iface mb_i_of_n

Thomas Schilling's avatar
Thomas Schilling committed
644

645
646
647
hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
hscOneShotBackendOnly = compilerBackend hscOneShotCompiler

Thomas Schilling's avatar
Thomas Schilling committed
648
649
--------------------------------------------------------------

650
651
652
hscBatchCompiler :: HsCompiler BatchResult
hscBatchCompiler =
  HsCompiler {
Thomas Schilling's avatar
Thomas Schilling committed
653

654
    hscNoRecomp = \iface -> do
655
656
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
657

658
  , hscRecompile = genericHscRecompile hscBatchCompiler
Thomas Schilling's avatar
Thomas Schilling committed
659

660
661
  , hscBackend = genericHscBackend hscBatchCompiler

662
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
663
       (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
664
       hscWriteIface iface changed mod_summary
665
       return (HscRecomp Nothing (), iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
666

667
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
668
669
       guts <- hscSimplify' guts0
       (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface
670
671
672
673
       hscWriteIface iface changed mod_summary
       hasStub <- hscGenHardCode cgguts mod_summary
       return (HscRecomp hasStub (), iface, details)
  }
674

675
-- Compile Haskell, boot and extCore in batch mode.
676
hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
677
hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
Thomas Schilling's avatar
Thomas Schilling committed
678

679
680
681
hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler

Thomas Schilling's avatar
Thomas Schilling committed
682
683
--------------------------------------------------------------

684
685
686
hscInteractiveCompiler :: HsCompiler InteractiveResult
hscInteractiveCompiler =
  HsCompiler {
687
    hscNoRecomp = \iface -> do
688
689
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
690

691
  , hscRecompile = genericHscRecompile hscInteractiveCompiler
Thomas Schilling's avatar
Thomas Schilling committed
692

693
694
695
696
  , hscBackend = genericHscBackend hscInteractiveCompiler

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

699
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
700
701
       guts <- hscSimplify' guts0
       (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
702
703
       hscInteractive (iface, details, cgguts) mod_summary
  }
704
705
706

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

709
710
711
hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler

Thomas Schilling's avatar
Thomas Schilling committed
712
713
--------------------------------------------------------------

714
715
716
hscNothingCompiler :: HsCompiler NothingResult
hscNothingCompiler =
  HsCompiler {
717
    hscNoRecomp = \iface -> do
718
719
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
Simon Marlow's avatar
Simon Marlow committed
720

721
  , hscRecompile = genericHscRecompile hscNothingCompiler
722

723
  , hscBackend = \tc_result _mod_summary mb_old_iface -> do
724
       handleWarnings
725
       (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
726
       return (HscRecomp Nothing (), iface, details)
727

728
729
730
  , hscGenBootOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenBootOutput should not be called"

731
732
733
  , hscGenOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenOutput should not be called"
  }
734

735
-- Type-check Haskell and .hs-boot only (no external core)
736
hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
737
hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
738

739
740
741
hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
hscNothingBackendOnly = compilerBackend hscNothingCompiler

742
743
744
745
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

746
747
748
749
genModDetails :: ModIface -> Hsc ModDetails
genModDetails old_iface
  = do
      hsc_env <- getHscEnv
Thomas Schilling's avatar
Thomas Schilling committed
750
      new_details <- {-# SCC "tcRnIface" #-}
751
752
753
                     liftIO $ initIfaceCheck hsc_env $
                              typecheckIface old_iface
      liftIO $ dumpIfaceStats hsc_env
Thomas Schilling's avatar
Thomas Schilling committed
754
      return new_details
755

756
757
758
759
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

760
761
data RecompReason = RecompNotRequired | RecompRequired | RecompForcedByTH
  deriving Eq
762

763
764
765
766
767
768
769
770
771
772
oneShotMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ()
oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
  case recomp of
    RecompNotRequired ->
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
    _other ->
            return ()

batchMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ()
773
batchMsg hsc_env mb_mod_index recomp mod_summary
774
775
776
777
778
779
780
781
782
783
784
 = case recomp of
     RecompRequired -> showMsg "Compiling "
     RecompNotRequired
       | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  "
       | otherwise -> return ()
     RecompForcedByTH -> showMsg "Compiling [TH] "
   where
     showMsg msg =
        compilationProgressMsg (hsc_dflags hsc_env) $
         (showModuleIndex mb_mod_index ++
         msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) (recomp == RecompRequired) mod_summary)
785

786
787
788
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
789
790

hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
791
792
793
hscFileFrontEnd mod_summary = do
    rdr_module <- hscParse' mod_summary
    hsc_env <- getHscEnv
794
    dflags  <- getDynFlags
dterei's avatar
dterei committed
795
796
797
    tcg_env <-
        {-# SCC "Typecheck-Rename" #-}
        ioMsgMaybe $
798
            tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
799
800
801
802
803
    tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_env)
    -- if safe haskell off or safe infer failed, wipe trust
    if not (safeHaskellOn dflags) || (safeInferOn dflags && not tcSafeOK)
        then wipeTrust tcg_env
        else hscCheckSafeImports tcg_env
804
805

--------------------------------------------------------------
806
-- Safe Haskell
807
808
--------------------------------------------------------------

809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
-- 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.


829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
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.


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

              -- trustworthy
            | otherwise
            -> return tcg_env'

    where
        warns rules = listToBag $ map warnRules rules
        warnRules (L loc (HsRule n _ _ _ _ _ _)) =
            mkPlainWarnMsg loc $
                text "Rule \"" <> ftext n <> text "\" ignored" $+$
                text "User defined rules are disabled under Safe Haskell"

873
874
875
876
877
-- | 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
878
879
-- external pacakge is trusted. See the Note [Safe Haskell
-- Trust Check] above for more information.
880
--
881
882
883
884
885
886
-- 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].
887
888
889
checkSafeImports :: DynFlags -> HscEnv -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags hsc_env tcg_env
    = do
890
891
892
893
894
        -- 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

895
        imps <- mapM condense imports'
896
        pkgs <- mapM checkSafe imps
dterei's avatar
dterei committed
897
898
899
900
901
902
903

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

        -- See the Note [ Safe Haskell Inference]
dterei's avatar
dterei committed
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
        case (not $ isEmptyBag errs) of

            -- We have errors!
            True ->
                -- did we fail safe inference or fail -XSafe?
                case safeInferOn dflags of
                    True  -> wipeTrust tcg_env
                    False -> liftIO . throwIO . mkSrcErr $ errs
            
            -- All good matey!
            False -> do
                when (packageTrustOn dflags) $ checkPkgTrust pkg_reqs
                -- 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 }
919

920
921
922
923
    where
        imp_info = tcg_imports tcg_env     -- ImportAvails
        imports  = imp_mods imp_info       -- ImportedMods
        imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
924
        pkg_reqs = imp_trust_pkgs imp_info -- [PackageId]
925
926
927
928
929
930
931
932
933
934

        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
                                return (m, l, s)
        
        -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
        cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
        cond' v1@(m1,_,l1,s1) (_,_,_,s2)
            | s1 /= s2
935
            = throwErrors $ unitBag $ mkPlainErrMsg l1
936
937
938
939
940
941
942
943
944
945
946
947
948
                    (text "Module" <+> ppr m1 <+> (text $ "is imported"
                        ++ " both as a safe and unsafe import!"))
            | otherwise
            = return v1

        lookup' :: Module -> Hsc (Maybe ModIface)
        lookup' m = do
            hsc_eps <- liftIO $ hscEPS hsc_env
            let pkgIfaceT = eps_PIT hsc_eps
                homePkgT = hsc_HPT hsc_env
                iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
            return iface

949
950
951
952
953
        isHomePkg :: Module -> Bool
        isHomePkg m
            | thisPackage dflags == modulePackageId m = True
            | otherwise                               = False

954
        -- | Check the package a module resides in is trusted.
955
956
957
958
        -- 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.
959
        packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
960
        packageTrusted _ _ _
961
962
963
            | not (packageTrustOn dflags)     = True
        packageTrusted Sf_Safe        False _ = True
        packageTrusted Sf_SafeInfered False _ = True
964
        packageTrusted _ _ m
965
966
967
            | isHomePkg m = True
            | otherwise   = trusted $ getPackageDetails (pkgState dflags)
                                                        (modulePackageId m)
968

969
        -- Is a module trusted? Return Nothing if True, or a String
970
971
972
973
        -- if it isn't, containing the reason it isn't. Also return
        -- if the module trustworthy (true) or safe (false) so we know
        -- if we should check if the package itself is trusted in the
        -- future.
974
        isModSafe :: Module -> SrcSpan -> Hsc (Bool)
975
976
977
978
        isModSafe m l = do
            iface <- lookup' m
            case iface of
                -- can't load iface to check trust!
979
                Nothing -> throwErrors $ unitBag $ mkPlainErrMsg l
980
981
982
983
984
985
                            $ text "Can't load the interface file for" <+> ppr m <>
                              text ", to check that it can be safely imported"

                -- got iface, check trust
                Just iface' -> do
                    let trust = getSafeMode $ mi_trust iface'
986
                        trust_own_pkg = mi_trust_pkg iface'
987
                        -- check module is trusted
988
                        safeM = trust `elem` [Sf_SafeInfered, Sf_Safe, Sf_Trustworthy]
989
                        -- check package is trusted
990
                        safeP = packageTrusted trust trust_own_pkg m
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
                    case (safeM, safeP) of
                        -- General errors we throw but Safe errors we log
                        (True, True ) -> return $ trust == Sf_Trustworthy
                        (True, False) -> liftIO . throwIO $ pkgTrustErr
                        (False, _   ) -> logWarnings modTrustErr >> return (trust == Sf_Trustworthy)

                    where
                        pkgTrustErr = mkSrcErr $ unitBag $ mkPlainErrMsg l $ ppr m
                            <+> text "can't be safely imported!" <+> text "The package ("
                            <> ppr (modulePackageId m)
                            <> text ") the module resides in isn't trusted."
                        modTrustErr = unitBag $ mkPlainErrMsg l $ ppr m
                            <+> text "can't be safely imported!"
                            <+> text "The module itself isn't safe."
1005

1006
        -- Here we check the transitive package trust requirements are OK still.
dterei's avatar
dterei committed
1007
        checkPkgTrust :: [PackageId] -> Hsc ()
1008
        checkPkgTrust pkgs =
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
            case errors of
                [] -> return ()
                _  -> (liftIO . throwIO . mkSrcErr . listToBag) errors
            where
                errors = catMaybes $ map go pkgs
                go pkg
                    | trusted $ getPackageDetails (pkgState dflags) pkg
                    = Nothing
                    | otherwise
                    = Just $ mkPlainErrMsg noSrcSpan
                           $ text "The package (" <> ppr pkg <> text ") is required"
                          <> text " to be trusted but it isn't!"

        checkSafe :: (Module, SrcSpan, IsSafeImport) -> Hsc (Maybe PackageId)
        checkSafe (_, _, False) = return Nothing
1024
        checkSafe (m, l, True ) = do
1025
1026
            tw <- isModSafe m l
            return $ pkg tw
1027
1028
1029
            where pkg False = Nothing
                  pkg True | isHomePkg m = Nothing
                           | otherwise   = Just (modulePackageId m)
1030
1031
1032
1033

-- | Set module to unsafe and wipe trust information.
wipeTrust :: TcGblEnv -> Hsc TcGblEnv
wipeTrust tcg_env = do
dterei's avatar
dterei committed
1034
1035
    env <- getHscEnv
    liftIO $ hscSetSafeInf env False
1036
1037
1038
    let imps = (tcg_imports tcg_env) { imp_trust_pkgs = [] }
    return $ tcg_env { tcg_imports = imps }

1039
1040
1041
--------------------------------------------------------------
-- Simplifiers
--------------------------------------------------------------
1042

1043
1044
1045
1046
1047
1048
1049
1050
hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts

hscSimplify' :: ModGuts -> Hsc ModGuts
hscSimplify' ds_result
  = do hsc_env <- getHscEnv
       {-# SCC "Core2Core" #-}
         liftIO $ core2core hsc_env ds_result
1051
1052

--------------------------------------------------------------
1053
-- Interface generators
1054
1055
--------------------------------------------------------------

1056
hscSimpleIface :: TcGblEnv
Thomas Schilling's avatar
Thomas Schilling committed
1057
               -> Maybe Fingerprint
1058
               -> Hsc (ModIface, Bool, ModDetails)
Thomas Schilling's avatar
Thomas Schilling committed
1059
hscSimpleIface tc_result mb_old_iface
1060
1061
  = do 
       hsc_env <- getHscEnv
Thomas Schilling's avatar
Thomas Schilling committed
1062
       details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
Thomas Schilling's avatar
Thomas Schilling committed
1063
       (new_iface, no_change)
1064
           <- {-# SCC "MkFinalIface" #-}
1065
1066
              ioMsgMaybe $ 
                mkIfaceTc hsc_env mb_old_iface details tc_result
1067
       -- And the answer is ...
Thomas Schilling's avatar
Thomas Schilling committed
1068
1069
1070
       liftIO $ dumpIfaceStats hsc_env
       return (new_iface, no_change, details)

1071
hscNormalIface :: ModGuts
Thomas Schilling's avatar
Thomas Schilling committed
1072
               -> Maybe Fingerprint
Simon Marlow's avatar