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

dterei's avatar
dterei committed
3 4
-------------------------------------------------------------------------------
--
5
-- | Main API for compiling plain Haskell source code.
6
--
dterei's avatar
dterei committed
7
-- This module implements compilation of a Haskell source. It is
8 9 10 11 12
-- /not/ concerned with preprocessing of source files; this is handled
-- in "DriverPipeline".
--
-- There are various entry points depending on what mode we're in:
-- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
dterei's avatar
dterei committed
13
-- "interactive" mode (GHCi). There are also entry points for
14 15 16 17 18 19 20 21 22 23 24 25
-- 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
--
dterei's avatar
dterei committed
27 28 29 30
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
--
-------------------------------------------------------------------------------

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

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

43 44 45 46 47 48 49 50 51
    , genericHscCompileGetFrontendResult

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

52
    -- * Running passes separately
53 54 55
    , hscParse
    , hscTypecheckRename
    , hscDesugar
56 57
    , makeSimpleIface
    , makeSimpleDetails
58 59 60 61 62 63
    , hscSimplify -- ToDo, shouldn't really export this

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

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

import GHC.Exts
103 104
#endif

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

146
import DynFlags
147
import ErrUtils
148

149
import Outputable
150
import HscStats         ( ppSourceStats )
151
import HscTypes
152
import FastString
153
import UniqSupply
154
import Bag
155
import Exception
156 157 158
import qualified Stream
import Stream (Stream)

159
import Util
Simon Marlow's avatar
Simon Marlow committed
160

161
import Data.List
Simon Marlow's avatar
Simon Marlow committed
162
import Control.Monad
163
import Data.Maybe
Simon Marlow's avatar
Simon Marlow committed
164
import Data.IORef
165
import System.FilePath as FilePath
166
import System.Directory
Alan Zimmerman's avatar
Alan Zimmerman committed
167
import qualified Data.Map as Map
dterei's avatar
dterei committed
168

169
#include "HsVersions.h"
170

171

dterei's avatar
dterei committed
172 173 174 175 176
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
177

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

194

195
knownKeyNames :: [Name]      -- Put here to avoid loops involving DsMeta,
196
knownKeyNames =              -- where templateHaskellNames are defined
dterei's avatar
dterei committed
197
    map getName wiredInThings
dterei's avatar
dterei committed
198
        ++ basicKnownKeyNames
199
#ifdef GHCI
dterei's avatar
dterei committed
200
        ++ templateHaskellNames
201
#endif
202

203
-- -----------------------------------------------------------------------------
204

205
getWarnings :: Hsc WarningMessages
dterei's avatar
dterei committed
206
getWarnings = Hsc $ \_ w -> return (w, w)
207 208

clearWarnings :: Hsc ()
dterei's avatar
dterei committed
209
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
210 211

logWarnings :: WarningMessages -> Hsc ()
dterei's avatar
dterei committed
212
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
213 214

getHscEnv :: Hsc HscEnv
dterei's avatar
dterei committed
215
getHscEnv = Hsc $ \e w -> return (e, w)
216 217 218

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

-- | 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
228 229
    logWarnings warns
    when (not $ isEmptyBag errs) $ throwErrors errs
230 231 232 233

-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
234 235 236 237 238

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

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

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

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

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

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

#ifdef GHCI
dterei's avatar
dterei committed
293
hscIsGHCiMonad :: HscEnv -> String -> IO Name
294
hscIsGHCiMonad hsc_env name
295
  = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name
dterei's avatar
dterei committed
296

297
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
298 299 300
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ getModuleInterface hsc_env mod
301 302 303

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

310
-- -----------------------------------------------------------------------------
311
-- | parse a file, returning the abstract syntax
312

313
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
314 315 316
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

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

dterei's avatar
dterei committed
323 324 325
    --------------------------  Parser  ----------------
    liftIO $ showPass dflags "Parser"
    {-# SCC "Parser" #-} do
326 327 328 329

    -- 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
330 331 332
    buf <- case maybe_src_buf of
               Just b  -> return b
               Nothing -> liftIO $ hGetStringBuffer src_filename
333

dterei's avatar
dterei committed
334
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
335

dterei's avatar
dterei committed
336 337
    case unP parseModule (mkPState dflags buf loc) of
        PFailed span err ->
338
            liftIO $ throwOneError (mkPlainErrMsg dflags span err)
339

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

            -- To get the list of extra source files, we take the list
            -- that the parser gave us,
            --   - eliminate files beginning with '<'.  gcc likes to use
            --     pseudo-filenames like "<built-in>" and "<command-line>"
            --   - normalise them (elimiante differences between ./f and f)
            --   - filter out the preprocessed source file
            --   - filter out anything beginning with tmpdir
            --   - remove duplicates
            --   - filter out the .hs/.lhs source filename if we have one
            --
            let n_hspp  = FilePath.normalise src_filename
                srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`))
                            $ filter (not . (== n_hspp))
                            $ map FilePath.normalise
361
                            $ filter (not . (isPrefixOf "<"))
362 363 364 365 366 367
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

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

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

382 383 384
-- XXX: should this really be a Maybe X?  Check under which circumstances this
-- can become a Nothing and decide whether this should instead throw an
-- exception/signal an error.
dterei's avatar
dterei committed
385
type RenamedStuff =
386
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
387
                Maybe LHsDocString))
388

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

395 396 397 398 399 400
        -- 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)
401

402
    return (tc_result, rn_info)
403

404 405 406 407 408 409 410 411 412 413
-- wrapper around tcRnModule to handle safe haskell extras
tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule
            -> Hsc TcGblEnv
tcRnModule' hsc_env sum save_rn_syntax mod = do
    tcg_res <- {-# SCC "Typecheck-Rename" #-}
               ioMsgMaybe $
                   tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod

    tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_res)
    dflags   <- getDynFlags
414
    let allSafeOK = safeInferred dflags && tcSafeOK
415

416 417 418
    -- end of the safe haskell line, how to respond to user?
    if not (safeHaskellOn dflags) || (safeInferOn dflags && not allSafeOK)
        -- if safe Haskell off or safe infer failed, mark unsafe
419
        then markUnsafeInfer tcg_res emptyBag
420

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

441
-- | Convert a typechecked module to Core
442
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
443
hscDesugar hsc_env mod_summary tc_result =
444
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
445

446 447
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
dterei's avatar
dterei committed
448
    hsc_env <- getHscEnv
449 450
    r <- ioMsgMaybe $
      {-# SCC "deSugar" #-}
451
      deSugar hsc_env mod_location tc_result
452

dterei's avatar
dterei committed
453 454 455 456
    -- always check -Werror after desugaring, this is the last opportunity for
    -- warnings to arise before the backend.
    handleWarnings
    return r
457

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

dterei's avatar
dterei committed
471
-- | Make a 'ModDetails' from the results of typechecking. Used when
472
-- typechecking only, as opposed to full compilation.
473 474
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
475

476

dterei's avatar
dterei committed
477 478 479 480 481 482 483
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
484 485 486 487
                   --------------------------------
                        The compilation proper
                   --------------------------------

dterei's avatar
dterei committed
488 489 490 491 492 493
It's the task of the compilation proper to compile Haskell, hs-boot and core
files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
(the module is still parsed and type-checked. This feature is mostly used by
IDE's and the likes). Compilation can happen in either 'one-shot', 'batch',
'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch'
mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
494
targets byte-code.
dterei's avatar
dterei committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

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


520 521 522 523 524 525 526 527 528 529 530 531 532
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()

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

Simon Marlow's avatar
Simon Marlow committed
533 534 535
genericHscCompileGetFrontendResult
  always_do_basic_recompilation_check m_tc_result
  mHscMessage hsc_env mod_summary source_modified mb_old_iface mod_index
536 537 538 539 540
    = do

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

542 543 544
        skip iface = do
            msg UpToDate
            return $ Left iface
dterei's avatar
dterei committed
545

546 547 548 549
        compile mb_old_hash reason = do
            msg reason
            tc_result <- runHsc hsc_env $ genericHscFrontend mod_summary
            return $ Right (tc_result, mb_old_hash)
dterei's avatar
dterei committed
550 551 552 553

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

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    case m_tc_result of
         Just tc_result
          | not always_do_basic_recompilation_check ->
             return $ Right (tc_result, Nothing)
         _ -> do
            (recomp_reqd, mb_checked_iface)
                <- {-# SCC "checkOldIface" #-}
                   checkOldIface hsc_env mod_summary
                                source_modified mb_old_iface
            -- save the interface that comes back from checkOldIface.
            -- In one-shot mode we don't have the old iface until this
            -- point, when checkOldIface reads it from the disk.
            let mb_old_hash = fmap mi_iface_hash mb_checked_iface

            case mb_checked_iface of
                Just iface | not (recompileRequired recomp_reqd) ->
Simon Marlow's avatar
Simon Marlow committed
571 572 573 574 575 576 577 578 579 580 581 582 583
                    -- 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.
584 585 586 587 588 589 590 591 592 593 594 595 596
                    case m_tc_result of
                    Nothing
                     | mi_used_th iface && not stable ->
                        compile mb_old_hash (RecompBecause "TH")
                    _ ->
                        skip iface
                _ ->
                    case m_tc_result of
                    Nothing -> compile mb_old_hash recomp_reqd
                    Just tc_result ->
                        return $ Right (tc_result, mb_old_hash)

genericHscFrontend :: ModSummary -> Hsc TcGblEnv
597 598 599 600
genericHscFrontend mod_summary =
  getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)

genericHscFrontend' :: ModSummary -> Hsc TcGblEnv
Austin Seipp's avatar
Austin Seipp committed
601
genericHscFrontend' mod_summary = hscFileFrontEnd mod_summary
602

603 604 605 606
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

607 608 609
hscCompileOneShot :: HscEnv
                  -> ModSummary
                  -> SourceModified
610
                  -> IO HscStatus
611 612 613
hscCompileOneShot env =
  lookupHook hscCompileOneShotHook hscCompileOneShot' (hsc_dflags env) env

Austin Seipp's avatar
Austin Seipp committed
614
-- Compile Haskell/boot in OneShot mode.
615 616 617 618
hscCompileOneShot' :: HscEnv
                   -> ModSummary
                   -> SourceModified
                   -> IO HscStatus
Austin Seipp's avatar
Austin Seipp committed
619
hscCompileOneShot' hsc_env mod_summary src_changed
620
  = do
dterei's avatar
dterei committed
621 622 623 624 625
    -- One-shot mode needs a knot-tying mutable variable for interface
    -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
    type_env_var <- newIORef emptyNameEnv
    let mod = ms_mod mod_summary
        hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
626

627 628 629 630
        msg what = oneShotMsg hsc_env' what

        skip = do msg UpToDate
                  dumpIfaceStats hsc_env'
631
                  return HscUpToDate
632 633 634 635

        compile mb_old_hash reason = runHsc hsc_env' $ do
            liftIO $ msg reason
            tc_result <- genericHscFrontend mod_summary
636
            guts0 <- hscDesugar' (ms_location mod_summary) tc_result
637 638
            dflags <- getDynFlags
            case hscTarget dflags of
639
                HscNothing -> do
640 641 642
                    when (gopt Opt_WriteInterface dflags) $ liftIO $ do
                        (iface, changed, _details) <- hscSimpleIface hsc_env tc_result mb_old_hash
                        hscWriteIface dflags iface changed mod_summary
643
                    return HscNotGeneratingCode
644 645
                _ ->
                    case ms_hsc_src mod_summary of
646
                    t | isHsBootOrSig t ->
647 648
                        do (iface, changed, _) <- hscSimpleIface' tc_result mb_old_hash
                           liftIO $ hscWriteIface dflags iface changed mod_summary
649 650 651 652
                           return (case t of
                                    HsBootFile -> HscUpdateBoot
                                    HsigFile -> HscUpdateSig
                                    HsSrcFile -> panic "hscCompileOneShot Src")
653
                    _ ->
654
                        do guts <- hscSimplify' guts0
Austin Seipp's avatar
Austin Seipp committed
655
                           (iface, changed, _details, cgguts) <- hscNormalIface' guts mb_old_hash
656
                           liftIO $ hscWriteIface dflags iface changed mod_summary
657
                           return $ HscRecomp cgguts mod_summary
658

Simon Marlow's avatar
Simon Marlow committed
659 660 661
        -- XXX This is always False, because in one-shot mode the
        -- concept of stability does not exist.  The driver never
        -- passes SourceUnmodifiedAndStable in here.
662 663 664
        stable = case src_changed of
                     SourceUnmodifiedAndStable -> True
                     _                         -> False
665

666 667 668 669 670 671 672
    (recomp_reqd, mb_checked_iface)
        <- {-# SCC "checkOldIface" #-}
           checkOldIface hsc_env' mod_summary src_changed Nothing
    -- save the interface that comes back from checkOldIface.
    -- In one-shot mode we don't have the old iface until this
    -- point, when checkOldIface reads it from the disk.
    let mb_old_hash = fmap mi_iface_hash mb_checked_iface
673

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

692 693 694 695
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

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

704 705 706 707
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

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

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

734 735 736
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
737 738

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

--------------------------------------------------------------
746
-- Safe Haskell
747 748
--------------------------------------------------------------

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


769 770 771 772 773 774 775 776 777 778 779
-- 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.
780 781 782 783 784 785 786 787 788 789 790 791
--
-- 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
-- to allow users to set the `--fwarn-safe`, `--fwarn-unsafe` and
-- `--fwarn-trustworthy-safe` flags on Trustworthy and Unsafe modules so that a
-- 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.
792 793 794 795 796 797 798 799 800


-- | 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
801
    tcg_env' <- checkSafeImports dflags tcg_env
802
    checkRULES dflags tcg_env'
803

dterei's avatar
dterei committed
804
  where
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    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'

820 821 822
    warns dflags rules = listToBag $ map (warnRules dflags) rules
    warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
        mkPlainWarnMsg dflags loc $
823
            text "Rule \"" <> ftext (unLoc n) <> text "\" ignored" $+$
dterei's avatar
dterei committed
824
            text "User defined rules are disabled under Safe Haskell"
825

826 827 828 829 830 831
-- | Validate that safe imported modules are actually safe.  For modules in the
-- HomePackage (the package the module we are compiling in resides) this just
-- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules
-- that reside in another package we also must check that the external pacakge
-- is trusted. See the Note [Safe Haskell Trust Check] above for more
-- information.
832
--
833 834 835 836 837
-- 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].
838 839
checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags tcg_env
840
    = do
841 842 843
        imps <- mapM condense imports'
        let (safeImps, regImps) = partition (\(_,_,s) -> s) imps

844 845 846 847 848
        -- 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

849 850 851
        -- Check safe imports are correct
        safePkgs <- mapM checkSafe safeImps
        safeErrs <- getWarnings
dterei's avatar
dterei committed
852 853
        clearWarnings

854
        -- Check non-safe imports are correct if inferring safety
855
        -- See the Note [Safe Haskell Inference]
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
        (infErrs, infPkgs) <- case (safeInferOn dflags) of
          False -> return (emptyBag, [])
          True -> do infPkgs <- mapM checkSafe regImps
                     infErrs <- getWarnings
                     clearWarnings
                     return (infErrs, infPkgs)

        -- restore old errors
        logWarnings oldErrs

        case (isEmptyBag safeErrs) of
          -- Failed safe check
          False -> liftIO . throwIO . mkSrcErr $ safeErrs

          -- Passed safe check
          True -> do
            let infPassed = isEmptyBag infErrs
            tcg_env' <- case (not infPassed) of
              True  -> markUnsafeInfer tcg_env infErrs
              False -> return tcg_env
            when (packageTrustOn dflags) $ checkPkgTrust dflags pkgReqs
            let newTrust = pkgTrustReqs safePkgs infPkgs infPassed
            return tcg_env' { tcg_imports = impInfo `plusImportAvails` newTrust }
879

dterei's avatar
dterei committed
880
  where
881 882
    impInfo  = tcg_imports tcg_env     -- ImportAvails
    imports  = imp_mods impInfo        -- ImportedMods
dterei's avatar
dterei committed
883
    imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
884
    pkgReqs  = imp_trust_pkgs impInfo  -- [PackageKey]
dterei's avatar
dterei committed
885 886 887 888

    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
889
                            return (m, l, s)
dterei's avatar
dterei committed
890

dterei's avatar
dterei committed
891 892 893 894
    -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
    cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
    cond' v1@(m1,_,l1,s1) (_,_,_,s2)
        | s1 /= s2
895
        = throwErrors $ unitBag $ mkPlainErrMsg dflags l1
dterei's avatar
dterei committed
896 897 898 899
              (text "Module" <+> ppr m1 <+>
              (text $ "is imported both as a safe and unsafe import!"))
        | otherwise
        = return v1
Jan Stolarek's avatar
Jan Stolarek committed
900

901
    -- easier interface to work with
902 903 904 905 906 907 908 909 910 911 912
    checkSafe (m, l, _) = fst `fmap` hscCheckSafe' dflags m l

    -- what pkg's to add to our trust requirements
    pkgTrustReqs req inf infPassed | safeInferOn dflags
                                  && safeHaskell dflags == Sf_None && infPassed
                                   = emptyImportAvails {
                                       imp_trust_pkgs = catMaybes req ++ catMaybes inf
                                   }
    pkgTrustReqs _   _ _ | safeHaskell dflags == Sf_Unsafe
                         = emptyImportAvails
    pkgTrustReqs req _ _ = emptyImportAvails { imp_trust_pkgs = catMaybes req }
dterei's avatar
dterei committed
913

914 915
-- | Check that a module is safe to import.
--
dterei's avatar
dterei committed
916 917 918
-- We return True to indicate the import is safe and False otherwise
-- although in the False case an exception may be thrown first.
hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool
919 920
hscCheckSafe hsc_env m l = runHsc hsc_env $ do
    dflags <- getDynFlags
dterei's avatar
dterei committed
921 922 923 924
    pkgs <- snd `fmap` hscCheckSafe' dflags m l
    when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs
    errs <- getWarnings
    return $ isEmptyBag errs
925

dterei's avatar
dterei committed
926
-- | Return if a module is trusted and the pkgs it depends on to be trusted.
927
hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageKey])
dterei's avatar
dterei committed
928 929 930 931 932 933 934 935
hscGetSafe hsc_env m l = runHsc hsc_env $ do
    dflags       <- getDynFlags
    (self, pkgs) <- hscCheckSafe' dflags m l
    good         <- isEmptyBag `fmap` getWarnings
    clearWarnings -- don't want them printed...
    let pkgs' | Just p <- self = p:pkgs
              | otherwise      = pkgs
    return (good, pkgs')
Jan Stolarek's avatar
Jan Stolarek committed
936

dterei's avatar
dterei committed
937 938 939 940
-- | Is a module trusted? If not, throw or log errors depending on the type.
-- Return (regardless of trusted or not) if the trust type requires the modules
-- own package be trusted and a list of other packages required to be trusted
-- (these later ones haven't been checked) but the own package trust has been.
941
hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageKey, [PackageKey])
942
hscCheckSafe' dflags m l = do
dterei's avatar
dterei committed
943
    (tw, pkgs) <- isModSafe m l
944
    case tw of
dterei's avatar
dterei committed
945 946
        False              -> return (Nothing, pkgs)
        True | isHomePkg m -> return (Nothing, pkgs)
947
             | otherwise   -> return (Just $ modulePackageKey m, pkgs)
948
  where
949
    isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey])
dterei's avatar
dterei committed
950 951 952 953
    isModSafe m l = do
        iface <- lookup' m
        case iface of
            -- can't load iface to check trust!
954
            Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l
955 956
                         $ text "Can't load the interface file for" <+> ppr m
                           <> text ", to check that it can be safely imported"
dterei's avatar
dterei committed
957 958

            -- got iface, check trust
959
            Just iface' ->
dterei's avatar
dterei committed
960 961 962
                let trust = getSafeMode $ mi_trust iface'
                    trust_own_pkg = mi_trust_pkg iface'
                    -- check module is trusted
963
                    safeM = trust `elem` [Sf_Safe, Sf_Trustworthy]
dterei's avatar
dterei committed
964 965
                    -- check package is trusted
                    safeP = packageTrusted trust trust_own_pkg m
dterei's avatar
dterei committed
966 967
                    -- pkg trust reqs
                    pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface'
dterei's avatar
dterei committed
968
                    -- General errors we throw but Safe errors we log
969 970 971 972 973 974 975
                    errs = case (safeM, safeP) of
                        (True, True ) -> emptyBag
                        (True, False) -> pkgTrustErr
                        (False, _   ) -> modTrustErr
                in do
                    logWarnings errs
                    return (trust == Sf_Trustworthy, pkgRs)
dterei's avatar
dterei committed
976 977

                where
978
                    pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
979 980
                        sep [ ppr (moduleName m)
                                <> text ": Can't be safely imported!"
981
                            , text "The package (" <> ppr (modulePackageKey m)
982
                                <> text ") the module resides in isn't trusted."
983
                            ]
984
                    modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
985 986
                        sep [ ppr (moduleName m)
                                <> text ": Can't be safely imported!"
987
                            , text "The module itself isn't safe." ]
dterei's avatar
dterei committed
988

989 990 991 992
    -- | Check the package a module resides in is trusted. Safe compiled
    -- modules are trusted without requiring that their package is trusted. For
    -- trustworthy modules, modules in the home package are trusted but
    -- otherwise we check the package trust flag.
993
    packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
dterei's avatar
dterei committed
994 995
    packageTrusted Sf_None             _ _ = False -- shouldn't hit these cases
    packageTrusted Sf_Unsafe           _ _ = False -- prefer for completeness.
996
    packageTrusted _ _ _
997 998
        | not (packageTrustOn dflags)      = True
    packageTrusted Sf_Safe         False _ = True
999 1000
    packageTrusted _ _ m
        | isHomePkg m = True
1001
        | otherwise   = trusted $ getPackageDetails dflags (modulePackageKey m)
dterei's avatar
dterei committed
1002

1003 1004 1005 1006 1007 1008 1009
    lookup' :: Module -> Hsc (Maybe ModIface)
    lookup' m = do
        hsc_env <- getHscEnv
        hsc_eps <- liftIO $ hscEPS hsc_env
        let pkgIfaceT = eps_PIT hsc_eps
            homePkgT  = hsc_HPT hsc_env
            iface     = lookupIfaceByModule dflags homePkgT pkgIfaceT m
dterei's avatar
dterei committed
1010 1011 1012 1013 1014 1015 1016 1017
#ifdef GHCI
        -- the 'lookupIfaceByModule' method will always fail when calling from GHCi
        -- as the compiler hasn't filled in the various module tables
        -- so we need to call 'getModuleInterface' to load from disk
        iface' <- case iface of
            Just _  -> return iface
            Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m)
        return iface'
Jan Stolarek's avatar
Jan Stolarek committed
1018
#else
1019
        return iface
dterei's avatar
dterei committed
1020 1021
#endif

1022 1023 1024

    isHomePkg :: Module -> Bool
    isHomePkg m
1025
        | thisPackage dflags == modulePackageKey m = True
1026
        | otherwise                               = False
1027

1028
-- | Check the list of packages are trusted.
1029
checkPkgTrust :: DynFlags -> [PackageKey] -> Hsc ()
1030 1031 1032 1033 1034 1035 1036
checkPkgTrust dflags pkgs =
    case errors of
        [] -> return ()
        _  -> (liftIO . throwIO . mkSrcErr . listToBag) errors
    where
        errors = catMaybes $ map go pkgs
        go pkg
1037
            | trusted $ getPackageDetails dflags pkg
1038 1039
            = Nothing
            | otherwise
1040
            = Just $ mkErrMsg dflags noSrcSpan (pkgQual dflags)
1041 1042
                   $ text "The package (" <> ppr pkg <> text ") is required" <>
                     text " to be trusted but it isn't!"
1043

1044
-- | Set module to unsafe and (potentially) wipe trust information.
1045
--
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
-- Make sure to call this method to set a module to inferred unsafe, it should
-- be a central and single failure method. We only wipe the trust information
-- when we aren't in a specific Safe Haskell mode.
--
-- While we only use this for recording that a module was inferred unsafe, we
-- may call it on modules using Trustworthy or Unsafe flags so as to allow
-- warning flags for safety to function correctly. See Note [Safe Haskell
-- Inference].
markUnsafeInfer :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv
markUnsafeInfer tcg_env whyUnsafe = do
1056 1057 1058 1059
    dflags <- getDynFlags

    when (wopt Opt_WarnUnsafe dflags)
         (logWarnings $ unitBag $
1060
             mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags))
1061

1062
    liftIO $ writeIORef (tcg_safeInfer tcg_env) False
1063 1064 1065 1066 1067 1068
    -- NOTE: Only wipe trust when not in an explicity safe haskell mode. Other
    -- times inference may be on but we are in Trustworthy mode -- so we want
    -- to record safe-inference failed but not wipe the trust dependencies.
    case safeHaskell dflags == Sf_None of
      True  -> return $ tcg_env { tcg_imports = wiped_trust }
      False -> return tcg_env
1069 1070

  where
1071 1072
    wiped_trust   = (tcg_imports tcg_env) { imp_trust_pkgs = [] }
    pprMod        = ppr $ moduleName $ tcg_mod tcg_env
1073
    whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!"
1074
                         , text "Reason:"
1075
                         , nest 4 $ (vcat $ badFlags df) $+$
1076 1077
                                    (vcat $ pprErrMsgBagWithLoc whyUnsafe) $+$
                                    (vcat $ badInsts $ tcg_insts tcg_env)
dterei's avatar