HscMain.hs 78.3 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 10 11 12 13
-- /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
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
--
-------------------------------------------------------------------------------

33
module HscMain
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 43
    , hscCompileCmmFile

44 45 46
    , hscGenHardCode
    , hscInteractive

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

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

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

86 87
import GhcPrelude

88
import Data.Data hiding (Fixity, TyCon)
Alec Theriault's avatar
Alec Theriault committed
89
import Data.Maybe       ( fromJust )
Simon Marlow's avatar
Simon Marlow committed
90
import Id
91
import GHCi             ( addSptEntry )
92
import GHCi.RemoteTypes ( ForeignHValue )
93
import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
94
import Linker
95
import CoreTidy         ( tidyExpr )
96 97
import Type             ( Type )
import {- Kind parts of -} Type         ( Kind )
98
import CoreLint         ( lintInteractiveExpr )
99
import VarEnv           ( emptyTidyEnv )
100
import Panic
101
import ConLike
102
import Control.Concurrent
103

104 105
import Module
import Packages
Simon Marlow's avatar
Simon Marlow committed
106 107
import RdrName
import HsSyn
108
import HsDumpAst
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
xldenis's avatar
xldenis committed
117
import TcHsSyn          ( ZonkFlexi (DefaultFlexi) )
118
import NameCache        ( initNameCache )
119
import LoadIface        ( ifaceStats, initExternalPackageState )
120
import PrelInfo
Simon Marlow's avatar
Simon Marlow committed
121
import MkIface
122 123
import Desugar
import SimplCore
Simon Marlow's avatar
Simon Marlow committed
124
import TidyPgm
125
import CorePrep
126 127
import CoreToStg        ( coreToStg )
import qualified StgCmm ( codeGen )
128
import StgSyn
129
import StgFVs           ( annTopBindingsFreeVars )
130
import CostCentre
131
import ProfInit
132 133
import TyCon
import Name
134
import SimplStg         ( stg2stg )
135
import Cmm
136
import CmmParse         ( parseCmmFile )
137
import CmmBuildInfoTables
Edward Z. Yang's avatar
Edward Z. Yang committed
138
import CmmPipeline
139
import CmmInfo
140 141
import CodeOutput
import InstEnv
142
import FamInstEnv
Thomas Schilling's avatar
Thomas Schilling committed
143
import Fingerprint      ( Fingerprint )
144
import Hooks
Edward Z. Yang's avatar
Edward Z. Yang committed
145
import TcEnv
146
import PrelNames
147 148
import Plugins
import DynamicLoading   ( initializePlugins )
149

150
import DynFlags
151
import ErrUtils
John Ericson's avatar
John Ericson committed
152
import GHC.Platform ( platformOS, osSubsectionsViaSymbols )
153

154
import Outputable
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
155
import NameEnv
156
import HscStats         ( ppSourceStats )
157
import HscTypes
158
import FastString
159
import UniqSupply
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
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)
dterei's avatar
dterei committed
176

Alec Theriault's avatar
Alec Theriault committed
177 178
import HieAst           ( mkHieFile )
import HieTypes         ( getAsts, hie_asts )
179
import HieBin           ( readHieFile, writeHieFile , hie_file_result)
Alec Theriault's avatar
Alec Theriault committed
180 181
import HieDebug         ( diffFile, validateScopes )

Thomas Schilling's avatar
Thomas Schilling committed
182
#include "HsVersions.h"
183

184

dterei's avatar
dterei committed
185 186 187 188 189
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
190

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

212
-- -----------------------------------------------------------------------------
213

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

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

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

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

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

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

240 241 242 243 244 245 246 247 248
-- | 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)
249 250 251 252 253

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

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

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

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

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

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

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

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

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

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

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

-- internal version, that doesn't fail due to -Werror
329
hscParse' :: ModSummary -> Hsc HsParsedModule
Edward Z. Yang's avatar
Edward Z. Yang committed
330 331 332
hscParse' mod_summary
 | Just r <- ms_parsed_mod mod_summary = return r
 | otherwise = {-# SCC "Parser" #-}
333 334 335
    withTiming getDynFlags
               (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
dterei's avatar
dterei committed
359 360
            liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
                                   ppr rdr_module
361
            liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed_ast "Parser AST" $
362
                                   showAstData NoBlankSrcSpan rdr_module
dterei's avatar
dterei committed
363 364
            liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
                                   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
            let res = HsParsedModule {
394
                      hpm_module    = rdr_module,
Alan Zimmerman's avatar
Alan Zimmerman committed
395 396
                      hpm_src_files = srcs2,
                      hpm_annotations
Alec Theriault's avatar
Alec Theriault committed
397 398
                              = (M.fromListWith (++) $ annotations pst,
                                 M.fromList $ ((noSrcSpan,comment_q pst)
Alan Zimmerman's avatar
Alan Zimmerman committed
399
                                                 :(annotations_comments pst)))
400
                   }
Simon Marlow's avatar
Simon Marlow committed
401

402 403 404 405 406
            -- 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
407

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

414 415 416 417
    dflags <- getDynFlags
    liftIO $ dumpIfSet_dyn dflags Opt_D_dump_rn_ast "Renamer" $
                           showAstData NoBlankSrcSpan rn_info

Alec Theriault's avatar
Alec Theriault committed
418 419
    -- Create HIE files
    when (gopt Opt_WriteHie dflags) $ do
420 421 422
        -- 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
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
        let out_file = ml_hie_file $ ms_location mod_summary
        liftIO $ writeHieFile out_file hieFile

        -- Validate HIE files
        when (gopt Opt_ValidateHie dflags) $ do
            hs_env <- Hsc $ \e w -> return (e, w)
            liftIO $ do
              -- Validate Scopes
              case validateScopes $ getAsts $ hie_asts hieFile of
                  [] -> 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
439
              case diffFile hieFile (hie_file_result file') of
Alec Theriault's avatar
Alec Theriault committed
440 441 442 443 444 445
                [] ->
                  putMsg dflags $ text "Got no roundtrip errors"
                xs -> do
                  putMsg dflags $ text "Got roundtrip errors"
                  mapM_ (putMsg dflags) xs
    return rn_info
Simon Marlow's avatar
Simon Marlow committed
446

447 448 449 450 451 452

-- -----------------------------------------------------------------------------
-- | Rename and typecheck a module, additionally returning the renamed syntax
hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
                   -> IO (TcGblEnv, RenamedStuff)
hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
Alec Theriault's avatar
Alec Theriault committed
453 454 455
    tc_result <- hsc_typecheck True mod_summary (Just rdr_module)
    rn_info <- extract_renamed_stuff mod_summary tc_result
    return (tc_result, rn_info)
456

Alec Theriault's avatar
Alec Theriault committed
457
-- | Rename and typecheck a module, but don't return the renamed syntax
Edward Z. Yang's avatar
Edward Z. Yang committed
458 459 460 461
hscTypecheck :: Bool -- ^ Keep renamed source?
             -> ModSummary -> Maybe HsParsedModule
             -> Hsc TcGblEnv
hscTypecheck keep_rn mod_summary mb_rdr_module = do
Alec Theriault's avatar
Alec Theriault committed
462 463
    tc_result <- hsc_typecheck keep_rn mod_summary mb_rdr_module
    _ <- extract_renamed_stuff mod_summary tc_result
464 465
    return tc_result

Alec Theriault's avatar
Alec Theriault committed
466
hsc_typecheck :: Bool -- ^ Keep renamed source?
467 468
              -> ModSummary -> Maybe HsParsedModule
              -> Hsc TcGblEnv
Alec Theriault's avatar
Alec Theriault committed
469
hsc_typecheck keep_rn mod_summary mb_rdr_module = do
Edward Z. Yang's avatar
Edward Z. Yang committed
470 471 472 473
    hsc_env <- getHscEnv
    let hsc_src = ms_hsc_src mod_summary
        dflags = hsc_dflags hsc_env
        outer_mod = ms_mod mod_summary
474 475 476
        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
477 478
        src_filename  = ms_hspp_file mod_summary
        real_loc = realSrcLocSpan $ mkRealSrcLoc (mkFastString src_filename) 1 1
Alec Theriault's avatar
Alec Theriault committed
479
        keep_rn' = gopt Opt_WriteHie dflags || keep_rn
Edward Z. Yang's avatar
Edward Z. Yang committed
480 481
    MASSERT( moduleUnitId outer_mod == thisPackage dflags )
    if hsc_src == HsigFile && not (isHoleModule inner_mod)
482
        then ioMsgMaybe $ tcRnInstantiateSignature hsc_env outer_mod' real_loc
Edward Z. Yang's avatar
Edward Z. Yang committed
483 484 485 486
        else
         do hpm <- case mb_rdr_module of
                    Just hpm -> return hpm
                    Nothing -> hscParse' mod_summary
Alec Theriault's avatar
Alec Theriault committed
487
            tc_result0 <- tcRnModule' mod_summary keep_rn' hpm
Edward Z. Yang's avatar
Edward Z. Yang committed
488 489 490
            if hsc_src == HsigFile
                then do (iface, _, _) <- liftIO $ hscSimpleIface hsc_env tc_result0 Nothing
                        ioMsgMaybe $
491
                            tcRnMergeSignatures hsc_env hpm tc_result0 iface
Edward Z. Yang's avatar
Edward Z. Yang committed
492 493
                else return tc_result0

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

501 502 503 504 505 506 507 508
    -- -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

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

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

519
    -- end of the safe haskell line, how to respond to user?
520 521 522 523 524 525 526 527 528 529 530
    res <- 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
531 532 533
                     True
                       | safeHaskell dflags == Sf_Safe -> return ()
                       | otherwise -> (logWarnings $ unitBag $
534 535 536 537 538 539 540 541 542 543 544 545 546
                              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'

    -- apply plugins to the type checking result
547 548 549


    return res
550 551
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
552
    errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
553 554
    errTwthySafe t = quotes (pprMod t)
      <+> text "is marked as Trustworthy but has been inferred as safe!"
555 556
    warnMissingSafeHaskellMode = ppr (moduleName (ms_mod sum))
      <+> text "is missing Safe Haskell mode"
557

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

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

dterei's avatar
dterei committed
570 571 572 573
    -- 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
574

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

580

dterei's avatar
dterei committed
581 582 583 584 585 586 587
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
588 589 590 591
                   --------------------------------
                        The compilation proper
                   --------------------------------

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

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


624 625
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()

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

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

650
        skip iface = do
651
            liftIO $ msg UpToDate
652
            return $ Left iface
dterei's avatar
dterei committed
653

654
        compile mb_old_hash reason = do
655 656 657
            liftIO $ msg reason
            result <- genericHscFrontend mod_summary
            return $ Right (result, mb_old_hash)
dterei's avatar
dterei committed
658 659 660 661

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

663 664 665
    case m_tc_result of
         Just tc_result
          | not always_do_basic_recompilation_check ->
666
             return $ Right (FrontendTypecheck tc_result, Nothing)
667 668 669
         _ -> do
            (recomp_reqd, mb_checked_iface)
                <- {-# SCC "checkOldIface" #-}
670
                   liftIO $ checkOldIface hsc_env mod_summary
671 672 673 674 675 676 677 678
                                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
679 680 681 682 683 684 685 686 687 688 689 690 691
                    -- 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.
692 693 694 695 696 697 698 699 700 701
                    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 ->
702
                        return $ Right (FrontendTypecheck tc_result, mb_old_hash)
703

704
genericHscFrontend :: ModSummary -> Hsc FrontendResult
705 706 707
genericHscFrontend mod_summary =
  getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)

708 709 710
genericHscFrontend' :: ModSummary -> Hsc FrontendResult
genericHscFrontend' mod_summary
    = FrontendTypecheck `fmap` hscFileFrontEnd mod_summary
711

712 713 714 715
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

Austin Seipp's avatar
Austin Seipp committed
716
-- Compile Haskell/boot in OneShot mode.
717 718 719 720 721 722 723 724 725 726 727 728 729
hscIncrementalCompile :: Bool
                      -> Maybe TcGblEnv
                      -> Maybe Messager
                      -> HscEnv
                      -> ModSummary
                      -> SourceModified
                      -> Maybe ModIface
                      -> (Int,Int)
                      -- HomeModInfo does not contain linkable, since we haven't
                      -- code-genned yet
                      -> IO (HscStatus, HomeModInfo)
hscIncrementalCompile always_do_basic_recompilation_check m_tc_result
    mHscMessage hsc_env' mod_summary source_modified mb_old_iface mod_index
730
  = do
Matthew Pickering's avatar
Matthew Pickering committed
731 732 733
    dflags <- initializePlugins hsc_env' (hsc_dflags hsc_env')
    let hsc_env'' = hsc_env' { hsc_dflags = dflags }

dterei's avatar
dterei committed
734 735
    -- One-shot mode needs a knot-tying mutable variable for interface
    -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
736
    -- See also Note [hsc_type_env_var hack]
dterei's avatar
dterei committed
737 738
    type_env_var <- newIORef emptyNameEnv
    let mod = ms_mod mod_summary
Matthew Pickering's avatar
Matthew Pickering committed
739 740
        hsc_env | isOneShot (ghcMode (hsc_dflags hsc_env''))
                = hsc_env'' { hsc_type_env_var = Just (mod, type_env_var) }
741
                | otherwise
Matthew Pickering's avatar
Matthew Pickering committed
742
                = hsc_env''
743

744 745 746 747 748 749 750 751
    -- 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
752 753
        -- We didn't need to do any typechecking; the old interface
        -- file on disk was good enough.
754
        Left iface -> do
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
            -- Knot tying!  See Note [Knot-tying typecheckIface]
            hmi <- liftIO . fixIO $ \hmi' -> do
                let hsc_env' =
                        hsc_env {
                            hsc_HPT = addToHpt (hsc_HPT hsc_env)
                                        (ms_mod_name mod_summary) hmi'
                        }
                -- 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
                return HomeModInfo{
                    hm_details = details,
                    hm_iface = iface,
                    hm_linkable = Nothing }
            return (HscUpToDate, hmi)
        -- 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.)
776
        Right (FrontendTypecheck tc_result, mb_old_hash) ->
777
            finish mod_summary tc_result mb_old_hash
778 779 780 781 782

-- Runs the post-typechecking frontend (desugar and simplify),
-- and then generates and writes out the final interface. We want
-- to write the interface AFTER simplification so we can get
-- as up-to-date and good unfoldings and other info as possible
783
-- in the interface file.
784
finish :: ModSummary
785 786
       -> TcGblEnv
       -> Maybe Fingerprint
787
       -> Hsc (HscStatus, HomeModInfo)
788 789
finish summary tc_result mb_old_hash = do
  hsc_env <- getHscEnv
790 791 792 793 794 795 796 797 798 799 800 801
  let dflags = hsc_dflags hsc_env
      target = hscTarget dflags
      hsc_src = ms_hsc_src summary
      should_desugar =
        ms_mod summary /= gHC_PRIM && hsc_src == HsSrcFile
      mk_simple_iface = do
        let hsc_status =
              case (target, hsc_src) of
                (HscNothing, _) -> HscNotGeneratingCode
                (_, HsBootFile) -> HscUpdateBoot
                (_, HsigFile) -> HscUpdateSig
                _ -> panic "finish"
802
        (iface, no_change, details) <- liftIO $
803
          hscSimpleIface hsc_env tc_result mb_old_hash
804 805
        return (iface, no_change, details, hsc_status)
  (iface, no_change, details, hsc_status) <-
806 807 808 809 810 811 812 813 814 815 816 817
    -- 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.
    if should_desugar
      then do
        desugared_guts0 <- hscDesugar' (ms_location summary) tc_result
        if target == HscNothing
          -- We are not generating code, so we can skip simplification
          -- and generate a simple interface.
          then mk_simple_iface
          else do
818 819
            plugins <- liftIO $ readIORef (tcg_th_coreplugins tc_result)
            desugared_guts <- hscSimplify' plugins desugared_guts0
820
            (iface, no_change, details, cgguts) <-
821
              liftIO $ hscNormalIface hsc_env desugared_guts mb_old_hash
822
            return (iface, no_change, details, HscRecomp cgguts summary)
823
      else mk_simple_iface
824
  liftIO $ hscMaybeWriteIface dflags iface no_change summary
825 826 827 828
  return
    ( hsc_status
    , HomeModInfo
      {hm_details = details, hm_iface = iface, hm_linkable = Nothing})
829 830

hscMaybeWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO ()
831
hscMaybeWriteIface dflags iface no_change summary =
832 833 834 835 836 837
    let force_write_interface = gopt Opt_WriteInterface dflags
        write_interface = case hscTarget dflags of
                            HscNothing      -> False
                            HscInterpreted  -> False
                            _               -> True
    in when (write_interface || force_write_interface) $
838
            hscWriteIface dflags iface no_change summary
839

840 841 842 843
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

844
-- NB: this must be knot-tied appropriately, see hscIncrementalCompile
845 846
genModDetails :: HscEnv -> ModIface -> IO ModDetails
genModDetails hsc_env old_iface
847
  = do
dterei's avatar
dterei committed
848
    new_details <- {-# SCC "tcRnIface" #-}
849
                   initIfaceLoad hsc_env (typecheckIface old_iface)
850
    dumpIfaceStats hsc_env
dterei's avatar
dterei committed
851
    return new_details
852

853 854 855 856
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

857 858
oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
oneShotMsg hsc_env recomp =
dterei's avatar
dterei committed
859
    case recomp of
860
        UpToDate ->
861 862
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
863
        _ ->
864 865
            return ()

866 867
batchMsg :: Messager
batchMsg hsc_env mod_index recomp mod_summary =
dterei's avatar
dterei committed
868
    case recomp of
869 870 871
        MustCompile -> showMsg "Compiling " ""
        UpToDate
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  " ""
dterei's avatar
dterei committed
872
            | otherwise -> return ()
873
        RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
dterei's avatar
dterei committed
874
    where
Ian Lynagh's avatar
Ian Lynagh committed
875
        dflags = hsc_dflags hsc_env
876
        showMsg msg reason =
Ian Lynagh's avatar
Ian Lynagh committed
877
            compilationProgressMsg dflags $
878
            (showModuleIndex mod_index ++
Ian Lynagh's avatar
Ian Lynagh committed
879
            msg ++ showModMsg dflags (hscTarget dflags)
880