Main.hs 80.5 KB
Newer Older
1
{-# LANGUAGE BangPatterns, CPP, MagicHash, NondecreasingIndentation #-}
Simon Marlow's avatar
Simon Marlow committed
2
{-# OPTIONS_GHC -fprof-auto-top #-}
3

dterei's avatar
dterei committed
4
5
-------------------------------------------------------------------------------
--
6
-- | Main API for compiling plain Haskell source code.
7
--
dterei's avatar
dterei committed
8
-- This module implements compilation of a Haskell source. It is
9
-- /not/ concerned with preprocessing of source files; this is handled
Sylvain Henry's avatar
Sylvain Henry committed
10
-- in GHC.Driver.Pipeline
11
12
13
--
-- 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
14
-- "interactive" mode (GHCi). There are also entry points for
15
16
17
18
19
20
21
22
-- 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).
--
23
24
25
26
27
-- 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.
28
--
dterei's avatar
dterei committed
29
30
31
32
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
--
-------------------------------------------------------------------------------

Sylvain Henry's avatar
Sylvain Henry committed
33
module GHC.Driver.Main
dterei's avatar
dterei committed
34
    (
35
36
37
38
    -- * Making an HscEnv
      newHscEnv

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

45
46
47
    , hscGenHardCode
    , hscInteractive

48
    -- * Running passes separately
Thomas Schilling's avatar
Thomas Schilling committed
49
50
51
    , hscParse
    , hscTypecheckRename
    , hscDesugar
Simon Marlow's avatar
Simon Marlow committed
52
    , makeSimpleDetails
53
54
    , hscSimplify -- ToDo, shouldn't really export this

55
56
57
58
    -- * Safe Haskell
    , hscCheckSafe
    , hscGetSafe

59
60
61
62
    -- * Support for interactive evaluation
    , hscParseIdentifier
    , hscTcRcLookupName
    , hscTcRnGetInfo
dterei's avatar
dterei committed
63
    , hscIsGHCiMonad
64
    , hscGetModuleInterface
65
    , hscRnImportDecls
66
    , hscTcRnLookupRdrName
67
68
    , hscStmt, hscParseStmtWithLocation, hscStmtWithLocation, hscParsedStmt
    , hscDecls, hscParseDeclsWithLocation, hscDeclsWithLocation, hscParsedDecls
69
    , hscTcExpr, TcRnExprMode(..), hscImport, hscKcType
70
    , hscParseExpr
xldenis's avatar
xldenis committed
71
    , hscParseType
72
    , hscCompileCoreExpr
73
74
    -- * Low-level exports for hooks
    , hscCompileCoreExpr'
Edsko de Vries's avatar
Edsko de Vries committed
75
      -- We want to make sure that we export enough to be able to redefine
76
      -- hsc_typecheck in client code
Sylvain Henry's avatar
Sylvain Henry committed
77
    , hscParse', hscSimplify', hscDesugar', tcRnModule', doCodeGen
Edsko de Vries's avatar
Edsko de Vries committed
78
    , getHscEnv
79
    , hscSimpleIface'
80
    , oneShotMsg
81
    , dumpIfaceStats
Edward Z. Yang's avatar
Edward Z. Yang committed
82
83
    , ioMsgMaybe
    , showModuleIndex
84
    , hscAddSptEntries
85
    ) where
86

87
88
import GhcPrelude

89
import Data.Data hiding (Fixity, TyCon)
Alec Theriault's avatar
Alec Theriault committed
90
import Data.Maybe       ( fromJust )
Sylvain Henry's avatar
Sylvain Henry committed
91
import GHC.Types.Id
92
import GHC.Runtime.Interpreter ( addSptEntry )
Sylvain Henry's avatar
Sylvain Henry committed
93
94
import GHCi.RemoteTypes        ( ForeignHValue )
import GHC.CoreToByteCode      ( byteCodeGen, coreExprToBCOs )
95
import GHC.Runtime.Linker
Sylvain Henry's avatar
Sylvain Henry committed
96
import GHC.Core.Tidy           ( tidyExpr )
Sylvain Henry's avatar
Sylvain Henry committed
97
import GHC.Core.Type           ( Type, Kind )
Sylvain Henry's avatar
Sylvain Henry committed
98
import GHC.Core.Lint           ( lintInteractiveExpr )
Sylvain Henry's avatar
Sylvain Henry committed
99
import GHC.Types.Var.Env       ( emptyTidyEnv )
100
import Panic
Sylvain Henry's avatar
Sylvain Henry committed
101
import GHC.Core.ConLike
102

Sylvain Henry's avatar
Sylvain Henry committed
103
import GHC.Parser.Annotation
Sylvain Henry's avatar
Sylvain Henry committed
104
import GHC.Types.Module
Sylvain Henry's avatar
Sylvain Henry committed
105
import GHC.Driver.Packages
Sylvain Henry's avatar
Sylvain Henry committed
106
import GHC.Types.Name.Reader
Sylvain Henry's avatar
Sylvain Henry committed
107
108
import GHC.Hs
import GHC.Hs.Dump
Sylvain Henry's avatar
Sylvain Henry committed
109
import GHC.Core
Ian Lynagh's avatar
Ian Lynagh committed
110
import StringBuffer
Sylvain Henry's avatar
Sylvain Henry committed
111
112
import GHC.Parser
import GHC.Parser.Lexer as Lexer
Sylvain Henry's avatar
Sylvain Henry committed
113
import GHC.Types.SrcLoc
Sylvain Henry's avatar
Sylvain Henry committed
114
import GHC.Tc.Module
115
import GHC.IfaceToCore  ( typecheckIface )
Sylvain Henry's avatar
Sylvain Henry committed
116
117
import GHC.Tc.Utils.Monad
import GHC.Tc.Utils.Zonk    ( ZonkFlexi (DefaultFlexi) )
Sylvain Henry's avatar
Sylvain Henry committed
118
import GHC.Types.Name.Cache ( initNameCache )
Sylvain Henry's avatar
Sylvain Henry committed
119
import GHC.Builtin.Utils
Sylvain Henry's avatar
Sylvain Henry committed
120
import GHC.Core.Opt.Driver
Sylvain Henry's avatar
Sylvain Henry committed
121
122
123
124
import GHC.HsToCore
import GHC.Iface.Load   ( ifaceStats, initExternalPackageState, writeIface )
import GHC.Iface.Make
import GHC.Iface.Recomp
125
import GHC.Iface.Tidy
Sylvain Henry's avatar
Sylvain Henry committed
126
import GHC.CoreToStg.Prep
127
import GHC.CoreToStg    ( coreToStg )
Sylvain Henry's avatar
Sylvain Henry committed
128
129
130
import GHC.Stg.Syntax
import GHC.Stg.FVs      ( annTopBindingsFreeVars )
import GHC.Stg.Pipeline ( stg2stg )
131
import qualified GHC.StgToCmm as StgToCmm ( codeGen )
Sylvain Henry's avatar
Sylvain Henry committed
132
import GHC.Types.CostCentre
Sylvain Henry's avatar
Sylvain Henry committed
133
import GHC.Core.TyCon
Sylvain Henry's avatar
Sylvain Henry committed
134
135
import GHC.Types.Name
import GHC.Types.Name.Set
136
137
138
139
140
import GHC.Cmm
import GHC.Cmm.Parser         ( parseCmmFile )
import GHC.Cmm.Info.Build
import GHC.Cmm.Pipeline
import GHC.Cmm.Info
Sylvain Henry's avatar
Sylvain Henry committed
141
import GHC.Driver.CodeOutput
Sylvain Henry's avatar
Sylvain Henry committed
142
143
import GHC.Core.InstEnv
import GHC.Core.FamInstEnv
Thomas Schilling's avatar
Thomas Schilling committed
144
import Fingerprint      ( Fingerprint )
Sylvain Henry's avatar
Sylvain Henry committed
145
import GHC.Driver.Hooks
Sylvain Henry's avatar
Sylvain Henry committed
146
import GHC.Tc.Utils.Env
Sylvain Henry's avatar
Sylvain Henry committed
147
import GHC.Builtin.Names
Sylvain Henry's avatar
Sylvain Henry committed
148
import GHC.Driver.Plugins
149
import GHC.Runtime.Loader   ( initializePlugins )
150

Sylvain Henry's avatar
Sylvain Henry committed
151
import GHC.Driver.Session
152
import ErrUtils
153

154
import Outputable
Sylvain Henry's avatar
Sylvain Henry committed
155
import GHC.Types.Name.Env
156
import HscStats         ( ppSourceStats )
Sylvain Henry's avatar
Sylvain Henry committed
157
import GHC.Driver.Types
158
import FastString
Sylvain Henry's avatar
Sylvain Henry committed
159
import GHC.Types.Unique.Supply
160
import Bag
Thomas Schilling's avatar
Thomas Schilling committed
161
import Exception
162
163
164
import qualified Stream
import Stream (Stream)

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

167
import Data.List        ( nub, isPrefixOf, partition )
Simon Marlow's avatar
Simon Marlow committed
168
169
import Control.Monad
import Data.IORef
170
import System.FilePath as FilePath
171
import System.Directory
172
import System.IO (fixIO)
Alec Theriault's avatar
Alec Theriault committed
173
import qualified Data.Map as M
174
175
import qualified Data.Set as S
import Data.Set (Set)
176
import Data.Functor
177
import Control.DeepSeq (force)
dterei's avatar
dterei committed
178

179
180
181
182
import GHC.Iface.Ext.Ast    ( mkHieFile )
import GHC.Iface.Ext.Types  ( getAsts, hie_asts, hie_module )
import GHC.Iface.Ext.Binary ( readHieFile, writeHieFile , hie_file_result)
import GHC.Iface.Ext.Debug  ( diffFile, validateScopes )
Alec Theriault's avatar
Alec Theriault committed
183

Thomas Schilling's avatar
Thomas Schilling committed
184
#include "HsVersions.h"
185

186

dterei's avatar
dterei committed
187
188
189
190
191
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
192

193
newHscEnv :: DynFlags -> IO HscEnv
194
newHscEnv dflags = do
dterei's avatar
dterei committed
195
196
    eps_var <- newIORef initExternalPackageState
    us      <- mkSplitUniqSupply 'r'
197
    nc_var  <- newIORef (initNameCache us knownKeyNames)
198
    fc_var  <- newIORef emptyInstalledModuleEnv
199
    emptyDynLinker <- uninitializedLinker
200
201
    return HscEnv {  hsc_dflags       = dflags
                  ,  hsc_targets      = []
202
                  ,  hsc_mod_graph    = emptyMG
203
204
205
206
207
208
                  ,  hsc_IC           = emptyInteractiveContext dflags
                  ,  hsc_HPT          = emptyHomePackageTable
                  ,  hsc_EPS          = eps_var
                  ,  hsc_NC           = nc_var
                  ,  hsc_FC           = fc_var
                  ,  hsc_type_env_var = Nothing
209
                  ,  hsc_interp       = Nothing
210
                  ,  hsc_dynLinker    = emptyDynLinker
211
                  }
Thomas Schilling's avatar
Thomas Schilling committed
212

213
-- -----------------------------------------------------------------------------
214

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

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

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

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

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

-- | 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
238
239
    logWarnings warns
    when (not $ isEmptyBag errs) $ throwErrors errs
240

241
242
243
244
245
246
247
248
249
-- | Log warnings and throw errors, assuming the messages
-- contain at least one error (e.g. coming from PFailed)
handleWarningsThrowErrors :: Messages -> Hsc a
handleWarningsThrowErrors (warns, errs) = do
    logWarnings warns
    dflags <- getDynFlags
    (wWarns, wErrs) <- warningsToMessages dflags <$> getWarnings
    liftIO $ printBagOfErrors dflags wWarns
    throwErrors (unionBags errs wErrs)
250
251
252
253
254

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

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

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

286
hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name]
287
288
hscTcRnLookupRdrName hsc_env0 rdr_name
  = runInteractiveHsc hsc_env0 $
289
290
    do { hsc_env <- getHscEnv
       ; ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name }
291
292

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
293
294
295
hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe' $ tcRnLookupName hsc_env name
dterei's avatar
dterei committed
296
297
298
      -- 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.
299

300
301
hscTcRnGetInfo :: HscEnv -> Name
               -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))
302
303
304
305
hscTcRnGetInfo hsc_env0 name
  = runInteractiveHsc hsc_env0 $
    do { hsc_env <- getHscEnv
       ; ioMsgMaybe' $ tcRnGetInfo hsc_env name }
306

dterei's avatar
dterei committed
307
hscIsGHCiMonad :: HscEnv -> String -> IO Name
Edsko de Vries's avatar
Edsko de Vries committed
308
hscIsGHCiMonad hsc_env name
309
  = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name
dterei's avatar
dterei committed
310

311
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
312
313
314
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ getModuleInterface hsc_env mod
315
316
317

-- -----------------------------------------------------------------------------
-- | Rename some import declarations
318
hscRnImportDecls :: HscEnv -> [LImportDecl GhcPs] -> IO GlobalRdrEnv
319
320
321
hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
322

323
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
324
-- | parse a file, returning the abstract syntax
325

326
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
327
328
329
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
330
hscParse' :: ModSummary -> Hsc HsParsedModule
Edward Z. Yang's avatar
Edward Z. Yang committed
331
332
333
hscParse' mod_summary
 | Just r <- ms_parsed_mod mod_summary = return r
 | otherwise = {-# SCC "Parser" #-}
334
335
    withTimingD (text "Parser"<+>brackets (ppr $ ms_mod mod_summary))
                (const ()) $ do
dterei's avatar
dterei committed
336
337
338
    dflags <- getDynFlags
    let src_filename  = ms_hspp_file mod_summary
        maybe_src_buf = ms_hspp_buf  mod_summary
339

dterei's avatar
dterei committed
340
    --------------------------  Parser  ----------------
341
342
343
    -- 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
344
345
346
    buf <- case maybe_src_buf of
               Just b  -> return b
               Nothing -> liftIO $ hGetStringBuffer src_filename
347

dterei's avatar
dterei committed
348
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
Edward Z. Yang's avatar
Edward Z. Yang committed
349
350
351
    let parseMod | HsigFile == ms_hsc_src mod_summary
                 = parseSignature
                 | otherwise = parseModule
352

Edward Z. Yang's avatar
Edward Z. Yang committed
353
    case unP parseMod (mkPState dflags buf loc) of
354
355
        PFailed pst ->
            handleWarningsThrowErrors (getMessages pst dflags)
dterei's avatar
dterei committed
356
        POk pst rdr_module -> do
357
358
            let (warns, errs) = getMessages pst dflags
            logWarnings warns
Sylvain Henry's avatar
Sylvain Henry committed
359
360
361
362
363
364
            liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser"
                        FormatHaskell (ppr rdr_module)
            liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed_ast "Parser AST"
                        FormatHaskell (showAstData NoBlankSrcSpan rdr_module)
            liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
                        FormatText (ppSourceStats False rdr_module)
365
            when (not $ isEmptyBag errs) $ throwErrors errs
366
367
368
369
370

            -- 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>"
Gabor Greif's avatar
Gabor Greif committed
371
            --   - normalise them (eliminate differences between ./f and f)
372
373
374
375
376
377
378
379
380
            --   - 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
Gabor Greif's avatar
Gabor Greif committed
381
                            $ filter (not . isPrefixOf "<")
382
383
384
385
386
387
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

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

393
394
395
396
397
398
399
            let api_anns = ApiAnns {
                      apiAnnItems = M.fromListWith (++) $ annotations pst,
                      apiAnnEofPos = eof_pos pst,
                      apiAnnComments = M.fromList (annotations_comments pst),
                      apiAnnRogueComments = comment_q pst
                   }
                res = HsParsedModule {
400
                      hpm_module    = rdr_module,
Alan Zimmerman's avatar
Alan Zimmerman committed
401
                      hpm_src_files = srcs2,
402
                      hpm_annotations = api_anns
403
                   }
Simon Marlow's avatar
Simon Marlow committed
404

405
406
407
408
409
            -- apply parse transformation of plugins
            let applyPluginAction p opts
                  = parsedResultAction p opts mod_summary
            withPlugins dflags applyPluginAction res

Simon Marlow's avatar
Simon Marlow committed
410

411
412
-- -----------------------------------------------------------------------------
-- | If the renamed source has been kept, extract it. Dump it if requested.
Alec Theriault's avatar
Alec Theriault committed
413
414
extract_renamed_stuff :: ModSummary -> TcGblEnv -> Hsc RenamedStuff
extract_renamed_stuff mod_summary tc_result = do
415
    let rn_info = getRenamedStuff tc_result
Thomas Schilling's avatar
Thomas Schilling committed
416

417
    dflags <- getDynFlags
Sylvain Henry's avatar
Sylvain Henry committed
418
419
    liftIO $ dumpIfSet_dyn dflags Opt_D_dump_rn_ast "Renamer"
                FormatHaskell (showAstData NoBlankSrcSpan rn_info)
420

Alec Theriault's avatar
Alec Theriault committed
421
422
    -- Create HIE files
    when (gopt Opt_WriteHie dflags) $ do
423
424
425
        -- I assume this fromJust is safe because `-fwrite-hie-file`
        -- enables the option which keeps the renamed source.
        hieFile <- mkHieFile mod_summary tc_result (fromJust rn_info)
Alec Theriault's avatar
Alec Theriault committed
426
427
        let out_file = ml_hie_file $ ms_location mod_summary
        liftIO $ writeHieFile out_file hieFile
428
        liftIO $ dumpIfSet_dyn dflags Opt_D_dump_hie "HIE AST" FormatHaskell (ppr $ hie_asts hieFile)
Alec Theriault's avatar
Alec Theriault committed
429
430
431
432
433
434

        -- Validate HIE files
        when (gopt Opt_ValidateHie dflags) $ do
            hs_env <- Hsc $ \e w -> return (e, w)
            liftIO $ do
              -- Validate Scopes
435
              case validateScopes (hie_module hieFile) $ getAsts $ hie_asts hieFile of
Alec Theriault's avatar
Alec Theriault committed
436
437
438
439
440
441
442
                  [] -> putMsg dflags $ text "Got valid scopes"
                  xs -> do
                    putMsg dflags $ text "Got invalid scopes"
                    mapM_ (putMsg dflags) xs
              -- Roundtrip testing
              nc <- readIORef $ hsc_NC hs_env
              (file', _) <- readHieFile nc out_file
443
              case diffFile hieFile (hie_file_result file') of
Alec Theriault's avatar
Alec Theriault committed
444
445
446
447
                [] ->
                  putMsg dflags $ text "Got no roundtrip errors"
                xs -> do
                  putMsg dflags $ text "Got roundtrip errors"
448
                  mapM_ (putMsg (dopt_set dflags Opt_D_ppr_debug)) xs
Alec Theriault's avatar
Alec Theriault committed
449
    return rn_info
Simon Marlow's avatar
Simon Marlow committed
450

451
452
453
454
455

-- -----------------------------------------------------------------------------
-- | Rename and typecheck a module, additionally returning the renamed syntax
hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
                   -> IO (TcGblEnv, RenamedStuff)
456
457
hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $
    hsc_typecheck True mod_summary (Just rdr_module)
458
459


460
461
462
463
-- | A bunch of logic piled around around @tcRnModule'@, concerning a) backpack
-- b) concerning dumping rename info and hie files. It would be nice to further
-- separate this stuff out, probably in conjunction better separating renaming
-- and type checking (#17781).
Alec Theriault's avatar
Alec Theriault committed
464
hsc_typecheck :: Bool -- ^ Keep renamed source?
465
              -> ModSummary -> Maybe HsParsedModule
466
              -> Hsc (TcGblEnv, RenamedStuff)
Alec Theriault's avatar
Alec Theriault committed
467
hsc_typecheck keep_rn mod_summary mb_rdr_module = do
Edward Z. Yang's avatar
Edward Z. Yang committed
468
469
470
471
    hsc_env <- getHscEnv
    let hsc_src = ms_hsc_src mod_summary
        dflags = hsc_dflags hsc_env
        outer_mod = ms_mod mod_summary
472
473
474
        mod_name = moduleName outer_mod
        outer_mod' = mkModule (thisPackage dflags) mod_name
        inner_mod = canonicalizeHomeModule dflags mod_name
Edward Z. Yang's avatar
Edward Z. Yang committed
475
476
        src_filename  = ms_hspp_file mod_summary
        real_loc = realSrcLocSpan $ mkRealSrcLoc (mkFastString src_filename) 1 1
Alec Theriault's avatar
Alec Theriault committed
477
        keep_rn' = gopt Opt_WriteHie dflags || keep_rn
Edward Z. Yang's avatar
Edward Z. Yang committed
478
    MASSERT( moduleUnitId outer_mod == thisPackage dflags )
479
    tc_result <- if hsc_src == HsigFile && not (isHoleModule inner_mod)
480
        then ioMsgMaybe $ tcRnInstantiateSignature hsc_env outer_mod' real_loc
Edward Z. Yang's avatar
Edward Z. Yang committed
481
482
483
484
        else
         do hpm <- case mb_rdr_module of
                    Just hpm -> return hpm
                    Nothing -> hscParse' mod_summary
Alec Theriault's avatar
Alec Theriault committed
485
            tc_result0 <- tcRnModule' mod_summary keep_rn' hpm
Edward Z. Yang's avatar
Edward Z. Yang committed
486
487
488
            if hsc_src == HsigFile
                then do (iface, _, _) <- liftIO $ hscSimpleIface hsc_env tc_result0 Nothing
                        ioMsgMaybe $
489
                            tcRnMergeSignatures hsc_env hpm tc_result0 iface
Edward Z. Yang's avatar
Edward Z. Yang committed
490
                else return tc_result0
491
492
493
494
    -- TODO are we extracting anything when we merely instantiate a signature?
    -- If not, try to move this into the "else" case above.
    rn_info <- extract_renamed_stuff mod_summary tc_result
    return (tc_result, rn_info)
Edward Z. Yang's avatar
Edward Z. Yang committed
495

496
-- wrapper around tcRnModule to handle safe haskell extras
497
tcRnModule' :: ModSummary -> Bool -> HsParsedModule
498
            -> Hsc TcGblEnv
499
500
tcRnModule' sum save_rn_syntax mod = do
    hsc_env <- getHscEnv
501
502
    dflags   <- getDynFlags

503
504
505
506
507
508
509
510
    -- -Wmissing-safe-haskell-mode
    when (not (safeHaskellModeEnabled dflags)
          && wopt Opt_WarnMissingSafeHaskellMode dflags) $
        logWarnings $ unitBag $
        makeIntoWarning (Reason Opt_WarnMissingSafeHaskellMode) $
        mkPlainWarnMsg dflags (getLoc (hpm_module mod)) $
        warnMissingSafeHaskellMode

511
512
    tcg_res <- {-# SCC "Typecheck-Rename" #-}
               ioMsgMaybe $
513
                   tcRnModule hsc_env sum
514
                     save_rn_syntax mod
515

516
517
518
    -- 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)
519
    let allSafeOK = safeInferred dflags && tcSafeOK
520

521
    -- end of the safe haskell line, how to respond to user?
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
    if not (safeHaskellOn dflags)
         || (safeInferOn dflags && not allSafeOK)
      -- if safe Haskell off or safe infer failed, mark unsafe
      then markUnsafeInfer tcg_res whyUnsafe

      -- module (could be) safe, throw warning if needed
      else do
          tcg_res' <- hscCheckSafeImports tcg_res
          safe <- liftIO $ fst <$> readIORef (tcg_safeInfer tcg_res')
          when safe $ do
            case wopt Opt_WarnSafe dflags of
              True
                | safeHaskell dflags == Sf_Safe -> return ()
                | otherwise -> (logWarnings $ unitBag $
                       makeIntoWarning (Reason Opt_WarnSafe) $
                       mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $
                       errSafe tcg_res')
              False | safeHaskell dflags == Sf_Trustworthy &&
                      wopt Opt_WarnTrustworthySafe dflags ->
                      (logWarnings $ unitBag $
                       makeIntoWarning (Reason Opt_WarnTrustworthySafe) $
                       mkPlainWarnMsg dflags (trustworthyOnLoc dflags) $
                       errTwthySafe tcg_res')
              False -> return ()
          return tcg_res'
547
548
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
549
    errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
550
551
    errTwthySafe t = quotes (pprMod t)
      <+> text "is marked as Trustworthy but has been inferred as safe!"
552
553
    warnMissingSafeHaskellMode = ppr (moduleName (ms_mod sum))
      <+> text "is missing Safe Haskell mode"
554

Simon Marlow's avatar
Simon Marlow committed
555
-- | Convert a typechecked module to Core
556
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
557
hscDesugar hsc_env mod_summary tc_result =
Ian Lynagh's avatar
Ian Lynagh committed
558
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
559

Ian Lynagh's avatar
Ian Lynagh committed
560
561
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
dterei's avatar
dterei committed
562
    hsc_env <- getHscEnv
Simon Marlow's avatar
Simon Marlow committed
563
564
    r <- ioMsgMaybe $
      {-# SCC "deSugar" #-}
Ian Lynagh's avatar
Ian Lynagh committed
565
      deSugar hsc_env mod_location tc_result
566

dterei's avatar
dterei committed
567
568
569
570
    -- 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
571

dterei's avatar
dterei committed
572
-- | Make a 'ModDetails' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
573
-- typechecking only, as opposed to full compilation.
574
575
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
Simon Marlow's avatar
Simon Marlow committed
576

577

dterei's avatar
dterei committed
578
579
580
581
582
583
584
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
585
586
587
588
                   --------------------------------
                        The compilation proper
                   --------------------------------

dterei's avatar
dterei committed
589
It's the task of the compilation proper to compile Haskell, hs-boot and core
Gabor Greif's avatar
Gabor Greif committed
590
files to either byte-code, hard-code (C, asm, LLVM, etc.) or to nothing at all
dterei's avatar
dterei committed
591
592
593
594
(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
595
targets byte-code.
dterei's avatar
dterei committed
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620

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


621
622
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()

623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
-- | 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
638
  always_do_basic_recompilation_check m_tc_result
639
  mHscMessage mod_summary source_modified mb_old_iface mod_index
640
    = do
641
    hsc_env <- getHscEnv
642
643
644
645

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

647
        skip iface = do
648
            liftIO $ msg UpToDate
649
            return $ Left iface
dterei's avatar
dterei committed
650

651
        compile mb_old_hash reason = do
652
            liftIO $ msg reason
653
654
            (tc_result, _) <- hsc_typecheck False mod_summary Nothing
            return $ Right (FrontendTypecheck tc_result, mb_old_hash)
dterei's avatar
dterei committed
655
656
657
658

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

660
661
662
    case m_tc_result of
         Just tc_result
          | not always_do_basic_recompilation_check ->
663
             return $ Right (FrontendTypecheck tc_result, Nothing)
664
665
666
         _ -> do
            (recomp_reqd, mb_checked_iface)
                <- {-# SCC "checkOldIface" #-}
667
                   liftIO $ checkOldIface hsc_env mod_summary
668
669
670
671
                                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.
672
            let mb_old_hash = fmap (mi_iface_hash . mi_final_exts) mb_checked_iface
673
674
675

            case mb_checked_iface of
                Just iface | not (recompileRequired recomp_reqd) ->
Simon Marlow's avatar
Simon Marlow committed
676
677
678
679
680
681
682
683
684
685
686
687
688
                    -- 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.
689
690
691
692
693
694
695
696
697
698
                    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 ->
699
                        return $ Right (FrontendTypecheck tc_result, mb_old_hash)
700

701
702
703
704
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

705
706
707
708
709
-- | Used by both OneShot and batch mode. Runs the pipeline HsSyn and Core parts
-- of the pipeline.
-- We return a interface if we already had an old one around and recompilation
-- was not needed. Otherwise it will be created during later passes when we
-- run the compilation pipeline.
710
711
712
713
714
715
716
717
hscIncrementalCompile :: Bool
                      -> Maybe TcGblEnv
                      -> Maybe Messager
                      -> HscEnv
                      -> ModSummary
                      -> SourceModified
                      -> Maybe ModIface
                      -> (Int,Int)
718
                      -> IO (HscStatus, DynFlags)
719
720
hscIncrementalCompile always_do_basic_recompilation_check m_tc_result
    mHscMessage hsc_env' mod_summary source_modified mb_old_iface mod_index
721
  = do
Matthew Pickering's avatar
Matthew Pickering committed
722
723
724
    dflags <- initializePlugins hsc_env' (hsc_dflags hsc_env')
    let hsc_env'' = hsc_env' { hsc_dflags = dflags }

dterei's avatar
dterei committed
725
    -- One-shot mode needs a knot-tying mutable variable for interface
Sylvain Henry's avatar
Sylvain Henry committed
726
    -- files. See GHC.Tc.Utils.TcGblEnv.tcg_type_env_var.
727
    -- See also Note [hsc_type_env_var hack]
dterei's avatar
dterei committed
728
729
    type_env_var <- newIORef emptyNameEnv
    let mod = ms_mod mod_summary
Matthew Pickering's avatar
Matthew Pickering committed
730
731
        hsc_env | isOneShot (ghcMode (hsc_dflags hsc_env''))
                = hsc_env'' { hsc_type_env_var = Just (mod, type_env_var) }
732
                | otherwise
Matthew Pickering's avatar
Matthew Pickering committed
733
                = hsc_env''
734

735
736
737
738
739
740
741
742
    -- 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
    e <- hscIncrementalFrontend always_do_basic_recompilation_check m_tc_result mHscMessage
            mod_summary source_modified mb_old_iface mod_index
    case e of
743
744
        -- We didn't need to do any typechecking; the old interface
        -- file on disk was good enough.
745
        Left iface -> do
746
            -- Knot tying!  See Note [Knot-tying typecheckIface]
747
            details <- liftIO . fixIO $ \details' -> do
748
749
750
                let hsc_env' =
                        hsc_env {
                            hsc_HPT = addToHpt (hsc_HPT hsc_env)
751
                                        (ms_mod_name mod_summary) (HomeModInfo iface details' Nothing)
752
753
754
755
756
757
                        }
                -- NB: This result is actually not that useful
                -- in one-shot mode, since we're not going to do
                -- any further typechecking.  It's much more useful
                -- in make mode, since this HMI will go into the HPT.
                details <- genModDetails hsc_env' iface
758
                return details
759
            return (HscUpToDate iface details, dflags)
760
761
762
763
        -- We finished type checking.  (mb_old_hash is the hash of
        -- the interface that existed on disk; it's possible we had
        -- to retypecheck but the resulting interface is exactly
        -- the same.)
764
        Right (FrontendTypecheck tc_result, mb_old_hash) -> do
765
766
            status <- finish mod_summary tc_result mb_old_hash
            return (status, dflags)
767

768
769
770
771
772
773
774
775
776
777
778
779
-- Runs the post-typechecking frontend (desugar and simplify). We want to
-- generate most of the interface as late as possible. This gets us up-to-date
-- and good unfoldings and other info in the interface file.
--
-- We might create a interface right away, in which case we also return the
-- updated HomeModInfo. But we might also need to run the backend first. In the
-- later case Status will be HscRecomp and we return a function from ModIface ->
-- HomeModInfo.
--
-- HscRecomp in turn will carry the information required to compute a interface
-- when passed the result of the code generator. So all this can and is done at
-- the call site of the backend code gen if it is run.
780
finish :: ModSummary
781
782
       -> TcGblEnv
       -> Maybe Fingerprint
783
       -> Hsc HscStatus
784
785
finish summary tc_result mb_old_hash = do
  hsc_env <- getHscEnv
786
787
788
  let dflags = hsc_dflags hsc_env
      target = hscTarget dflags
      hsc_src = ms_hsc_src summary
789

John Ericson's avatar
John Ericson committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
  -- Desugar, if appropriate
  --
  -- We usually desugar even when we are not generating code, otherwise we
  -- would miss errors thrown by the desugaring (see #10600). The only
  -- exceptions are when the Module is Ghc.Prim or when it is not a
  -- HsSrcFile Module.
  mb_desugar <-
      if ms_mod summary /= gHC_PRIM && hsc_src == HsSrcFile
      then Just <$> hscDesugar' (ms_location summary) tc_result
      else pure Nothing

  -- Simplify, if appropriate, and (whether we simplified or not) generate an
  -- interface file.
  case mb_desugar of
      -- Just cause we desugared doesn't mean we are generating code, see above.
      Just desugared_guts | target /= HscNothing -> do
806
          plugins <- liftIO $ readIORef (tcg_th_coreplugins tc_result)
John Ericson's avatar
John Ericson committed
807
          simplified_guts <- hscSimplify' plugins desugared_guts
808
809

          (cg_guts, details) <- {-# SCC "CoreTidy" #-}
John Ericson's avatar
John Ericson committed
810
              liftIO $ tidyProgram hsc_env simplified_guts
811
812

          let !partial_iface =
Sylvain Henry's avatar
Sylvain Henry committed
813
                {-# SCC "GHC.Driver.Main.mkPartialIface" #-}
814
815
                -- This `force` saves 2M residency in test T10370
                -- See Note [Avoiding space leaks in toIface*] for details.
John Ericson's avatar
John Ericson committed
816
                force (mkPartialIface hsc_env details simplified_guts)
817

818
819
820
821
822
823
          return HscRecomp { hscs_guts = cg_guts,
                             hscs_mod_location = ms_location summary,
                             hscs_mod_details = details,
                             hscs_partial_iface = partial_iface,
                             hscs_old_iface_hash = mb_old_hash,
                             hscs_iface_dflags = dflags }
824

John Ericson's avatar
John Ericson committed
825
826
827
828
829
830
831
832
833
834
835
836
837
      -- We are not generating code, so we can skip simplification
      -- and generate a simple interface.
      _ -> do
        (iface, mb_old_iface_hash, details) <- liftIO $
          hscSimpleIface hsc_env tc_result mb_old_hash

        liftIO $ hscMaybeWriteIface dflags iface mb_old_iface_hash (ms_location summary)

        return $ case (target, hsc_src) of
          (HscNothing, _) -> HscNotGeneratingCode iface details
          (_, HsBootFile) -> HscUpdateBoot iface details
          (_, HsigFile) -> HscUpdateSig iface details
          _ -> panic "finish"
838
839
840
841
842

{-
Note [Writing interface files]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sylvain Henry's avatar
Sylvain Henry committed
843
We write interface files in GHC.Driver.Main and GHC.Driver.Pipeline using
844
845
846
hscMaybeWriteIface, but only once per compilation (twice with dynamic-too).

* If a compilation does NOT require (re)compilation of the hard code we call
Sylvain Henry's avatar
Sylvain Henry committed
847
  hscMaybeWriteIface inside GHC.Driver.Main:finish.
848
849
850
851
852
* If we run in One Shot mode and target bytecode we write it in compileOne'
* Otherwise we must be compiling to regular hard code and require recompilation.
  In this case we create the interface file inside RunPhase using the interface
  generator contained inside the HscRecomp status.
-}
853
854
hscMaybeWriteIface :: DynFlags -> ModIface -> Maybe Fingerprint -> ModLocation -> IO ()
hscMaybeWriteIface dflags iface old_iface location = do
855
856
857
858
859
    let force_write_interface = gopt Opt_WriteInterface dflags
        write_interface = case hscTarget dflags of
                            HscNothing      -> False
                            HscInterpreted  -> False
                            _               -> True
860
861
862
863
        no_change = old_iface == Just (mi_iface_hash (mi_final_exts iface))

    when (write_interface || force_write_interface) $
          hscWriteIface dflags iface no_change location
864

865
866
867
868
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

869
-- NB: this must be knot-tied appropriately, see hscIncrementalCompile
870
871
genModDetails :: HscEnv -> ModIface -> IO ModDetails
genModDetails hsc_env old_iface
872
  = do
dterei's avatar
dterei committed
873
    new_details <- {-# SCC "tcRnIface" #-}
874
                   initIfaceLoad hsc_env (typecheckIface old_iface)
875
    dumpIfaceStats hsc_env
dterei's avatar
dterei committed
876
    return new_details
877

878
879
880
881
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

882
883
oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
oneShotMsg hsc_env recomp =
dterei's avatar
dterei committed
884
    case recomp of
885
        UpToDate ->
886
887
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
888
        _ ->
889
890
            return ()

891
892
batchMsg :: Messager
batchMsg hsc_env mod_index recomp mod_summary =
dterei's avatar
dterei committed
893
    case recomp of
894
895
896
        MustCompile -> showMsg "Compiling " ""
        UpToDate
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  " ""
dterei's avatar
dterei committed
897
            | otherwise -> return ()
898
        RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
dterei's avatar
dterei committed
899
    where
Ian Lynagh's avatar
Ian Lynagh committed
900
        dflags = hsc_dflags hsc_env
901
        showMsg msg reason =
Ian Lynagh's avatar
Ian Lynagh committed
902
            compilationProgressMsg dflags $
903
            (showModuleIndex mod_index ++
Ian Lynagh's avatar
Ian Lynagh committed
904
            msg ++ showModMsg dflags (hscTarget dflags)
905
906
                              (recompileRequired recomp) mod_summary)
                ++ reason
907

908
--------------------------------------------------------------
909
-- Safe Haskell
910
911
--------------------------------------------------------------

912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
-- 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.


932
933
934
-- Note [Safe Haskell Inference]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Safe Haskell does Safe inference on modules that don't have any specific
Gabor Greif's avatar
Gabor Greif committed
935
-- safe haskell mode flag. The basic approach to this is:
936
937
938
939
940
941
942
--   * 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.
943
944
945
--
-- 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
946
947
-- to allow users to set the `-Wsafe`, `-Wunsafe` and
-- `-Wtrustworthy-safe` flags on Trustworthy and Unsafe modules so that a
948
949
950
951
952
953
954
-- 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.
955
956
957
958
959
960
961
962
963


-- | 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
964
    tcg_env' <- checkSafeImports tcg_env
965
    checkRULES dflags tcg_env'
966

dterei's avatar
dterei committed
967
  where
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
    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
983
    warns dflags rules = listToBag $ map (warnRules dflags) rules
984
985

    warnRules :: DynFlags -> GenLocated SrcSpan (RuleDecl GhcTc) -> ErrMsg
986
    warnRules dflags (L loc (HsRule { rd_name = n })) =
Ian Lynagh's avatar
Ian Lynagh committed
987
        mkPlainWarnMsg dflags loc $
988
            text "Rule \"" <> ftext (snd $ unLoc n) <> text "\" ignored" $+$
dterei's avatar
dterei committed
989
            text "User defined rules are disabled under Safe Haskell"
990

991
992
993
-- | 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
Gabor Greif's avatar
Gabor Greif committed
994
-- that reside in another package we also must check that the external package
995
996
-- is trusted. See the Note [Safe Haskell Trust Check] above for more
-- information.
997
--
998
999
-- 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
1000
1001
1002
1003
-- GHC.Rename.Names.rnImportDecl for where package trust dependencies for a
-- module are collected and unioned.  Specifically see the Note [Tracking Trust
-- Transitively] in GHC.Rename.Names and the Note [Trust Own Package] in
-- GHC.Rename.Names.
1004
1005
checkSafeImports :: TcGblEnv -> Hsc TcGblEnv
checkSafeImports tcg_env
1006
    = do
1007
        dflags <- getDynFlags
1008
1009
1010
        imps <- mapM condense imports'
        let (safeImps, regImps) = partition (\(_,_,s) -> s) imps

1011
1012
1013
1014
1015
        -- 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