HscMain.hs 73.9 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
    , hscStmt, hscStmtWithLocation, hscParsedStmt
67
    , hscDecls, hscDeclsWithLocation
68
    , hscTcExpr, TcRnExprMode(..), hscImport, hscKcType
69
    , hscParseExpr
70
    , hscCompileCoreExpr
71 72
    -- * Low-level exports for hooks
    , hscCompileCoreExpr'
Edsko de Vries's avatar
Edsko de Vries committed
73 74
      -- We want to make sure that we export enough to be able to redefine
      -- hscFileFrontEnd in client code
75
    , hscParse', hscSimplify', hscDesugar', tcRnModule'
Edsko de Vries's avatar
Edsko de Vries committed
76
    , getHscEnv
77 78 79
    , hscSimpleIface', hscNormalIface'
    , oneShotMsg
    , hscFileFrontEnd, genericHscFrontend, dumpIfaceStats
Edward Z. Yang's avatar
Edward Z. Yang committed
80 81
    , ioMsgMaybe
    , showModuleIndex
82
    , hscAddSptEntries
83
    ) where
84

85 86
import GhcPrelude

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

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

147
import DynFlags
148
import ErrUtils
149
import Platform ( platformOS, osSubsectionsViaSymbols )
150

151
import Outputable
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
152
import NameEnv
153
import HscStats         ( ppSourceStats )
154
import HscTypes
155
import FastString
156
import UniqSupply
157
import Bag
Thomas Schilling's avatar
Thomas Schilling committed
158
import Exception
159 160 161
import qualified Stream
import Stream (Stream)

162
import Util
Simon Marlow's avatar
Simon Marlow committed
163

164
import Data.List
Simon Marlow's avatar
Simon Marlow committed
165 166
import Control.Monad
import Data.IORef
167
import System.FilePath as FilePath
168
import System.Directory
169
import System.IO (fixIO)
Alan Zimmerman's avatar
Alan Zimmerman committed
170
import qualified Data.Map as Map
171 172
import qualified Data.Set as S
import Data.Set (Set)
dterei's avatar
dterei committed
173

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

176

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

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

202
-- -----------------------------------------------------------------------------
203

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

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

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

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

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

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

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

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

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

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

269
hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name]
270 271
hscTcRnLookupRdrName hsc_env0 rdr_name
  = runInteractiveHsc hsc_env0 $
272 273
    do { hsc_env <- getHscEnv
       ; ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name }
274 275

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

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

dterei's avatar
dterei committed
290
hscIsGHCiMonad :: HscEnv -> String -> IO Name
Edsko de Vries's avatar
Edsko de Vries committed
291
hscIsGHCiMonad hsc_env name
292
  = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name
dterei's avatar
dterei committed
293

294
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
295 296 297
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ getModuleInterface hsc_env mod
298 299 300

-- -----------------------------------------------------------------------------
-- | Rename some import declarations
301
hscRnImportDecls :: HscEnv -> [LImportDecl GhcPs] -> IO GlobalRdrEnv
302 303 304
hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
305

306
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
307
-- | parse a file, returning the abstract syntax
308

309
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
310 311 312
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
313
hscParse' :: ModSummary -> Hsc HsParsedModule
Edward Z. Yang's avatar
Edward Z. Yang committed
314 315 316
hscParse' mod_summary
 | Just r <- ms_parsed_mod mod_summary = return r
 | otherwise = {-# SCC "Parser" #-}
317 318 319
    withTiming getDynFlags
               (text "Parser"<+>brackets (ppr $ ms_mod mod_summary))
               (const ()) $ do
dterei's avatar
dterei committed
320 321 322
    dflags <- getDynFlags
    let src_filename  = ms_hspp_file mod_summary
        maybe_src_buf = ms_hspp_buf  mod_summary
323

dterei's avatar
dterei committed
324
    --------------------------  Parser  ----------------
325 326 327
    -- 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
328 329 330
    buf <- case maybe_src_buf of
               Just b  -> return b
               Nothing -> liftIO $ hGetStringBuffer src_filename
331

dterei's avatar
dterei committed
332
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
Edward Z. Yang's avatar
Edward Z. Yang committed
333 334 335
    let parseMod | HsigFile == ms_hsc_src mod_summary
                 = parseSignature
                 | otherwise = parseModule
336

Edward Z. Yang's avatar
Edward Z. Yang committed
337
    case unP parseMod (mkPState dflags buf loc) of
338 339 340
        PFailed warnFn span err -> do
            logWarningsReportErrors (warnFn dflags)
            handleWarnings
Ian Lynagh's avatar
Ian Lynagh committed
341
            liftIO $ throwOneError (mkPlainErrMsg dflags span err)
342

dterei's avatar
dterei committed
343
        POk pst rdr_module -> do
344
            logWarningsReportErrors (getMessages pst dflags)
dterei's avatar
dterei committed
345 346
            liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
                                   ppr rdr_module
347
            liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed_ast "Parser AST" $
348
                                   showAstData NoBlankSrcSpan rdr_module
dterei's avatar
dterei committed
349 350
            liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
                                   ppSourceStats False rdr_module
351 352 353 354 355

            -- 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
356
            --   - normalise them (eliminate differences between ./f and f)
357 358 359 360 361 362 363 364 365
            --   - 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
366
                            $ filter (not . isPrefixOf "<")
367 368 369 370 371 372
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

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

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

387 388 389 390 391
            -- 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
392

393 394 395 396
-- -----------------------------------------------------------------------------
-- | If the renamed source has been kept, extract it. Dump it if requested.
extract_renamed_stuff :: TcGblEnv -> Hsc (TcGblEnv, RenamedStuff)
extract_renamed_stuff tc_result = do
397
    let rn_info = getRenamedStuff tc_result
Thomas Schilling's avatar
Thomas Schilling committed
398

399 400 401 402
    dflags <- getDynFlags
    liftIO $ dumpIfSet_dyn dflags Opt_D_dump_rn_ast "Renamer" $
                           showAstData NoBlankSrcSpan rn_info

403
    return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
404

405 406 407 408 409 410

-- -----------------------------------------------------------------------------
-- | 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
411 412
      tc_result <- hscTypecheck True mod_summary (Just rdr_module)
      extract_renamed_stuff tc_result
413

Edward Z. Yang's avatar
Edward Z. Yang committed
414 415 416 417
hscTypecheck :: Bool -- ^ Keep renamed source?
             -> ModSummary -> Maybe HsParsedModule
             -> Hsc TcGblEnv
hscTypecheck keep_rn mod_summary mb_rdr_module = do
418 419 420 421 422 423 424 425 426
    tc_result <- hscTypecheck' keep_rn mod_summary mb_rdr_module
    _ <- extract_renamed_stuff tc_result
    return tc_result


hscTypecheck' :: Bool -- ^ Keep renamed source?
              -> ModSummary -> Maybe HsParsedModule
              -> Hsc TcGblEnv
hscTypecheck' keep_rn mod_summary mb_rdr_module = do
Edward Z. Yang's avatar
Edward Z. Yang committed
427 428 429 430
    hsc_env <- getHscEnv
    let hsc_src = ms_hsc_src mod_summary
        dflags = hsc_dflags hsc_env
        outer_mod = ms_mod mod_summary
431 432 433
        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
434 435 436 437
        src_filename  = ms_hspp_file mod_summary
        real_loc = realSrcLocSpan $ mkRealSrcLoc (mkFastString src_filename) 1 1
    MASSERT( moduleUnitId outer_mod == thisPackage dflags )
    if hsc_src == HsigFile && not (isHoleModule inner_mod)
438
        then ioMsgMaybe $ tcRnInstantiateSignature hsc_env outer_mod' real_loc
Edward Z. Yang's avatar
Edward Z. Yang committed
439 440 441 442
        else
         do hpm <- case mb_rdr_module of
                    Just hpm -> return hpm
                    Nothing -> hscParse' mod_summary
443
            tc_result0 <- tcRnModule' mod_summary keep_rn hpm
Edward Z. Yang's avatar
Edward Z. Yang committed
444 445 446
            if hsc_src == HsigFile
                then do (iface, _, _) <- liftIO $ hscSimpleIface hsc_env tc_result0 Nothing
                        ioMsgMaybe $
447
                            tcRnMergeSignatures hsc_env hpm tc_result0 iface
Edward Z. Yang's avatar
Edward Z. Yang committed
448 449
                else return tc_result0

450
-- wrapper around tcRnModule to handle safe haskell extras
451
tcRnModule' :: ModSummary -> Bool -> HsParsedModule
452
            -> Hsc TcGblEnv
453 454
tcRnModule' sum save_rn_syntax mod = do
    hsc_env <- getHscEnv
455 456
    dflags   <- getDynFlags

457 458
    tcg_res <- {-# SCC "Typecheck-Rename" #-}
               ioMsgMaybe $
459
                   tcRnModule hsc_env sum
460
                     save_rn_syntax mod
461

462 463 464
    -- 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)
465
    let allSafeOK = safeInferred dflags && tcSafeOK
466

467
    -- end of the safe haskell line, how to respond to user?
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
    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
                     True -> (logWarnings $ unitBag $
                              makeIntoWarning (Reason Opt_WarnSafe) $
                              mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $
                              errSafe tcg_res')
                     False | safeHaskell dflags == Sf_Trustworthy &&
                             wopt Opt_WarnTrustworthySafe dflags ->
                             (logWarnings $ unitBag $
                              makeIntoWarning (Reason Opt_WarnTrustworthySafe) $
                              mkPlainWarnMsg dflags (trustworthyOnLoc dflags) $
                              errTwthySafe tcg_res')
                     False -> return ()
                 return tcg_res'

    -- apply plugins to the type checking result
493 494 495


    return res
496 497
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
498
    errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
499 500
    errTwthySafe t = quotes (pprMod t)
      <+> text "is marked as Trustworthy but has been inferred as safe!"
501

Simon Marlow's avatar
Simon Marlow committed
502
-- | Convert a typechecked module to Core
503
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
504
hscDesugar hsc_env mod_summary tc_result =
Ian Lynagh's avatar
Ian Lynagh committed
505
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
506

Ian Lynagh's avatar
Ian Lynagh committed
507 508
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
dterei's avatar
dterei committed
509
    hsc_env <- getHscEnv
Simon Marlow's avatar
Simon Marlow committed
510 511
    r <- ioMsgMaybe $
      {-# SCC "deSugar" #-}
Ian Lynagh's avatar
Ian Lynagh committed
512
      deSugar hsc_env mod_location tc_result
513

dterei's avatar
dterei committed
514 515 516 517
    -- 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
518

dterei's avatar
dterei committed
519
-- | Make a 'ModDetails' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
520
-- typechecking only, as opposed to full compilation.
521 522
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
Simon Marlow's avatar
Simon Marlow committed
523

524

dterei's avatar
dterei committed
525 526 527 528 529 530 531
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
532 533 534 535
                   --------------------------------
                        The compilation proper
                   --------------------------------

dterei's avatar
dterei committed
536
It's the task of the compilation proper to compile Haskell, hs-boot and core
Gabor Greif's avatar
Gabor Greif committed
537
files to either byte-code, hard-code (C, asm, LLVM, etc.) or to nothing at all
dterei's avatar
dterei committed
538 539 540 541
(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
542
targets byte-code.
dterei's avatar
dterei committed
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567

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


568 569
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
-- | 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
585
  always_do_basic_recompilation_check m_tc_result
586
  mHscMessage mod_summary source_modified mb_old_iface mod_index
587
    = do
588
    hsc_env <- getHscEnv
589 590 591 592

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

594
        skip iface = do
595
            liftIO $ msg UpToDate
596
            return $ Left iface
dterei's avatar
dterei committed
597

598
        compile mb_old_hash reason = do
599 600 601
            liftIO $ msg reason
            result <- genericHscFrontend mod_summary
            return $ Right (result, mb_old_hash)
dterei's avatar
dterei committed
602 603 604 605

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

607 608 609
    case m_tc_result of
         Just tc_result
          | not always_do_basic_recompilation_check ->
610
             return $ Right (FrontendTypecheck tc_result, Nothing)
611 612 613
         _ -> do
            (recomp_reqd, mb_checked_iface)
                <- {-# SCC "checkOldIface" #-}
614
                   liftIO $ checkOldIface hsc_env mod_summary
615 616 617 618 619 620 621 622
                                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
623 624 625 626 627 628 629 630 631 632 633 634 635
                    -- 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.
636 637 638 639 640 641 642 643 644 645
                    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 ->
646
                        return $ Right (FrontendTypecheck tc_result, mb_old_hash)
647

648
genericHscFrontend :: ModSummary -> Hsc FrontendResult
649 650 651
genericHscFrontend mod_summary =
  getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)

652 653 654
genericHscFrontend' :: ModSummary -> Hsc FrontendResult
genericHscFrontend' mod_summary
    = FrontendTypecheck `fmap` hscFileFrontEnd mod_summary
655

656 657 658 659
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

Austin Seipp's avatar
Austin Seipp committed
660
-- Compile Haskell/boot in OneShot mode.
661 662 663 664 665 666 667 668 669 670 671 672 673
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
674
  = do
Matthew Pickering's avatar
Matthew Pickering committed
675 676 677
    dflags <- initializePlugins hsc_env' (hsc_dflags hsc_env')
    let hsc_env'' = hsc_env' { hsc_dflags = dflags }

dterei's avatar
dterei committed
678 679
    -- One-shot mode needs a knot-tying mutable variable for interface
    -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
680
    -- See also Note [hsc_type_env_var hack]
dterei's avatar
dterei committed
681 682
    type_env_var <- newIORef emptyNameEnv
    let mod = ms_mod mod_summary
Matthew Pickering's avatar
Matthew Pickering committed
683 684
        hsc_env | isOneShot (ghcMode (hsc_dflags hsc_env''))
                = hsc_env'' { hsc_type_env_var = Just (mod, type_env_var) }
685
                | otherwise
Matthew Pickering's avatar
Matthew Pickering committed
686
                = hsc_env''
687

688 689 690 691 692 693 694 695
    -- 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
696 697
        -- We didn't need to do any typechecking; the old interface
        -- file on disk was good enough.
698
        Left iface -> do
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
            -- 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.)
720
        Right (FrontendTypecheck tc_result, mb_old_hash) ->
721
            finish mod_summary tc_result mb_old_hash
722 723 724 725 726

-- 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
727
-- in the interface file.
728
finish :: ModSummary
729 730
       -> TcGblEnv
       -> Maybe Fingerprint
731
       -> Hsc (HscStatus, HomeModInfo)
732 733
finish summary tc_result mb_old_hash = do
  hsc_env <- getHscEnv
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
  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"
        (iface, changed, details) <- liftIO $
          hscSimpleIface hsc_env tc_result mb_old_hash
        return (iface, changed, details, hsc_status)
  (iface, changed, details, hsc_status) <-
    -- 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
762 763
            plugins <- liftIO $ readIORef (tcg_th_coreplugins tc_result)
            desugared_guts <- hscSimplify' plugins desugared_guts0
764 765 766 767 768 769 770 771 772
            (iface, changed, details, cgguts) <-
              liftIO $ hscNormalIface hsc_env desugared_guts mb_old_hash
            return (iface, changed, details, HscRecomp cgguts summary)
      else mk_simple_iface
  liftIO $ hscMaybeWriteIface dflags iface changed summary
  return
    ( hsc_status
    , HomeModInfo
      {hm_details = details, hm_iface = iface, hm_linkable = Nothing})
773 774 775 776 777 778 779 780 781 782

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

784 785 786 787
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

788
-- NB: this must be knot-tied appropriately, see hscIncrementalCompile
789 790
genModDetails :: HscEnv -> ModIface -> IO ModDetails
genModDetails hsc_env old_iface
791
  = do
dterei's avatar
dterei committed
792
    new_details <- {-# SCC "tcRnIface" #-}
793
                   initIfaceLoad hsc_env (typecheckIface old_iface)
794
    dumpIfaceStats hsc_env
dterei's avatar
dterei committed
795
    return new_details
796

797 798 799 800
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

801 802
oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
oneShotMsg hsc_env recomp =
dterei's avatar
dterei committed
803
    case recomp of
804
        UpToDate ->
805 806
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
807
        _ ->
808 809
            return ()

810 811
batchMsg :: Messager
batchMsg hsc_env mod_index recomp mod_summary =
dterei's avatar
dterei committed
812
    case recomp of
813 814 815
        MustCompile -> showMsg "Compiling " ""
        UpToDate
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  " ""
dterei's avatar
dterei committed
816
            | otherwise -> return ()
817
        RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
dterei's avatar
dterei committed
818
    where
Ian Lynagh's avatar
Ian Lynagh committed
819
        dflags = hsc_dflags hsc_env
820
        showMsg msg reason =
Ian Lynagh's avatar
Ian Lynagh committed
821
            compilationProgressMsg dflags $
822
            (showModuleIndex mod_index ++
Ian Lynagh's avatar
Ian Lynagh committed
823
            msg ++ showModMsg dflags (hscTarget dflags)
824 825
                              (recompileRequired recomp) mod_summary)
                ++ reason
826

827 828 829
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
830

831 832
-- | Given a 'ModSummary', parses and typechecks it, returning the
-- 'TcGblEnv' resulting from type-checking.
833
hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
Edward Z. Yang's avatar
Edward Z. Yang committed
834
hscFileFrontEnd mod_summary = hscTypecheck False mod_summary Nothing
835 836

--------------------------------------------------------------
837
-- Safe Haskell
838 839
--------------------------------------------------------------

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


860 861 862
-- Note [Safe Haskell Inference]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Safe Haskell does Safe inference on modules that don't have any specific
Gabor Greif's avatar
Gabor Greif committed
863
-- safe haskell mode flag. The basic approach to this is:
864 865 866 867 868 869 870
--   * 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.
871 872 873
--
-- 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
874 875
-- to allow users to set the `-Wsafe`, `-Wunsafe` and
-- `-Wtrustworthy-safe` flags on Trustworthy and Unsafe modules so that a
876 877 878 879 880 881 882
-- 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.
883 884 885 886 887 888 889 890 891


-- | 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
892
    tcg_env' <- checkSafeImports tcg_env
893
    checkRULES dflags tcg_env'
894

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

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

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

918 919 920
-- | Validate that safe imported modules are actually safe.  For modules in the
-- HomePackage (the package the module we are compiling in resides) this just
-- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules
Gabor Greif's avatar
Gabor Greif committed
921
-- that reside in another package we also must check that the external package