HscMain.hs 70.7 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 62
    -- * Support for interactive evaluation
    , hscParseIdentifier
    , hscTcRcLookupName
    , hscTcRnGetInfo
#ifdef GHCI
dterei's avatar
dterei committed
63
    , hscIsGHCiMonad
64
    , hscGetModuleInterface
65
    , hscRnImportDecls
66
    , hscTcRnLookupRdrName
67
    , hscStmt, hscStmtWithLocation, hscParsedStmt
68
    , hscDecls, hscDeclsWithLocation
69
    , hscTcExpr, TcRnExprMode(..), hscImport, hscKcType
70
    , hscParseExpr
71
    , hscCompileCoreExpr
72 73
    -- * Low-level exports for hooks
    , hscCompileCoreExpr'
74
#endif
Edsko de Vries's avatar
Edsko de Vries committed
75 76
      -- We want to make sure that we export enough to be able to redefine
      -- hscFileFrontEnd in client code
77
    , hscParse', hscSimplify', hscDesugar', tcRnModule'
Edsko de Vries's avatar
Edsko de Vries committed
78
    , getHscEnv
79 80 81
    , hscSimpleIface', hscNormalIface'
    , oneShotMsg
    , hscFileFrontEnd, genericHscFrontend, dumpIfaceStats
82
    ) where
83

84
#ifdef GHCI
Simon Marlow's avatar
Simon Marlow committed
85
import Id
86
import GHCi.RemoteTypes ( ForeignHValue )
87
import ByteCodeGen      ( byteCodeGen, coreExprToBCOs )
88
import Linker
89
import CoreTidy         ( tidyExpr )
90 91
import Type             ( Type )
import {- Kind parts of -} Type         ( Kind )
92
import CoreLint         ( lintInteractiveExpr )
93
import VarEnv           ( emptyTidyEnv )
94
import Panic
95
import ConLike
96
import Control.Concurrent
97 98
#endif

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

140
import DynFlags
141
import ErrUtils
142

143
import Outputable
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
144 145
import UniqFM
import NameEnv
146
import HscStats         ( ppSourceStats )
147
import HscTypes
148
import FastString
149
import UniqSupply
150
import Bag
Thomas Schilling's avatar
Thomas Schilling committed
151
import Exception
152 153 154
import qualified Stream
import Stream (Stream)

155
import Util
Simon Marlow's avatar
Simon Marlow committed
156

157
import Data.List
Simon Marlow's avatar
Simon Marlow committed
158 159
import Control.Monad
import Data.IORef
160
import System.FilePath as FilePath
161
import System.Directory
162
import System.IO (fixIO)
Alan Zimmerman's avatar
Alan Zimmerman committed
163
import qualified Data.Map as Map
dterei's avatar
dterei committed
164

Thomas Schilling's avatar
Thomas Schilling committed
165
#include "HsVersions.h"
166

167

dterei's avatar
dterei committed
168 169 170 171 172
{- **********************************************************************
%*                                                                      *
                Initialisation
%*                                                                      *
%********************************************************************* -}
173

174
newHscEnv :: DynFlags -> IO HscEnv
175
newHscEnv dflags = do
dterei's avatar
dterei committed
176 177
    eps_var <- newIORef initExternalPackageState
    us      <- mkSplitUniqSupply 'r'
178
    nc_var  <- newIORef (initNameCache us allKnownKeyNames)
179
    fc_var  <- newIORef emptyModuleEnv
180
#ifdef GHCI
181
    iserv_mvar <- newMVar Nothing
182
#endif
183 184 185 186 187 188 189 190 191 192 193 194 195
    return HscEnv {  hsc_dflags       = dflags
                  ,  hsc_targets      = []
                  ,  hsc_mod_graph    = []
                  ,  hsc_IC           = emptyInteractiveContext dflags
                  ,  hsc_HPT          = emptyHomePackageTable
                  ,  hsc_EPS          = eps_var
                  ,  hsc_NC           = nc_var
                  ,  hsc_FC           = fc_var
                  ,  hsc_type_env_var = Nothing
#ifdef GHCI
                  , hsc_iserv        = iserv_mvar
#endif
                  }
Thomas Schilling's avatar
Thomas Schilling committed
196

197

198
allKnownKeyNames :: [Name]      -- Put here to avoid loops involving DsMeta,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212
allKnownKeyNames                -- where templateHaskellNames are defined
  | debugIsOn
  , not (isNullUFM badNamesEnv)
  = panic ("badAllKnownKeyNames:\n" ++ badNamesStr)
       -- NB: We can't use ppr here, because this is sometimes evaluated in a
       -- context where there are no DynFlags available, leading to a cryptic
       -- "<<details unavailable>>" error. (This seems to happen only in the
       -- stage 2 compiler, for reasons I [Richard] have no clue of.)

  | otherwise
  = all_names
  where
    all_names = knownKeyNames
                ++ templateHaskellNames
213

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
214 215 216
    namesEnv      = foldl (\m n -> extendNameEnv_Acc (:) singleton m n n)
                          emptyUFM all_names
    badNamesEnv   = filterNameEnv (\ns -> length ns > 1) namesEnv
niteria's avatar
niteria committed
217 218 219
    badNamesPairs = nonDetUFMToList badNamesEnv
      -- It's OK to use nonDetUFMToList here because the ordering only affects
      -- the message when we get a panic
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
220 221 222 223 224 225 226 227 228 229
    badNamesStrs  = map pairToStr badNamesPairs
    badNamesStr   = unlines badNamesStrs

    pairToStr (uniq, ns) = "        " ++
                           show uniq ++
                           ": [" ++
                           intercalate ", " (map (occNameString . nameOccName) ns) ++
                           "]"


230
-- -----------------------------------------------------------------------------
231

232
getWarnings :: Hsc WarningMessages
dterei's avatar
dterei committed
233
getWarnings = Hsc $ \_ w -> return (w, w)
234 235

clearWarnings :: Hsc ()
dterei's avatar
dterei committed
236
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
237 238

logWarnings :: WarningMessages -> Hsc ()
dterei's avatar
dterei committed
239
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
240 241

getHscEnv :: Hsc HscEnv
dterei's avatar
dterei committed
242
getHscEnv = Hsc $ \e w -> return (e, w)
243 244 245

handleWarnings :: Hsc ()
handleWarnings = do
dterei's avatar
dterei committed
246 247 248 249
    dflags <- getDynFlags
    w <- getWarnings
    liftIO $ printOrThrowWarnings dflags w
    clearWarnings
250 251 252 253 254

-- | 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
255 256
    logWarnings warns
    when (not $ isEmptyBag errs) $ throwErrors errs
257 258 259 260

-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
261 262 263 264 265

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

-- | 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
290 291 292
    ((warns,_errs), mb_r) <- liftIO $ ioA
    logWarnings warns
    return mb_r
293 294 295 296 297

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

#ifdef GHCI
298
hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name]
299 300
hscTcRnLookupRdrName hsc_env0 rdr_name
  = runInteractiveHsc hsc_env0 $
301 302
    do { hsc_env <- getHscEnv
       ; ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name }
303 304 305
#endif

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
306 307 308
hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe' $ tcRnLookupName hsc_env name
dterei's avatar
dterei committed
309 310 311
      -- 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.
312

313
hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
314 315 316 317
hscTcRnGetInfo hsc_env0 name
  = runInteractiveHsc hsc_env0 $
    do { hsc_env <- getHscEnv
       ; ioMsgMaybe' $ tcRnGetInfo hsc_env name }
318 319

#ifdef GHCI
dterei's avatar
dterei committed
320
hscIsGHCiMonad :: HscEnv -> String -> IO Name
Edsko de Vries's avatar
Edsko de Vries committed
321
hscIsGHCiMonad hsc_env name
322
  = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name
dterei's avatar
dterei committed
323

324
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
325 326 327
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ getModuleInterface hsc_env mod
328 329 330

-- -----------------------------------------------------------------------------
-- | Rename some import declarations
331
hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
332 333 334
hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
  hsc_env <- getHscEnv
  ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
335 336
#endif

337
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
338
-- | parse a file, returning the abstract syntax
339

340
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
341 342 343
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
344
hscParse' :: ModSummary -> Hsc HsParsedModule
345 346 347 348
hscParse' mod_summary = {-# SCC "Parser" #-}
    withTiming getDynFlags
               (text "Parser"<+>brackets (ppr $ ms_mod mod_summary))
               (const ()) $ do
dterei's avatar
dterei committed
349 350 351
    dflags <- getDynFlags
    let src_filename  = ms_hspp_file mod_summary
        maybe_src_buf = ms_hspp_buf  mod_summary
352

dterei's avatar
dterei committed
353
    --------------------------  Parser  ----------------
354 355 356
    -- 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
357 358 359
    buf <- case maybe_src_buf of
               Just b  -> return b
               Nothing -> liftIO $ hGetStringBuffer src_filename
360

dterei's avatar
dterei committed
361
    let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
362

dterei's avatar
dterei committed
363 364
    case unP parseModule (mkPState dflags buf loc) of
        PFailed span err ->
Ian Lynagh's avatar
Ian Lynagh committed
365
            liftIO $ throwOneError (mkPlainErrMsg dflags span err)
366

dterei's avatar
dterei committed
367
        POk pst rdr_module -> do
368
            logWarningsReportErrors (getMessages pst dflags)
dterei's avatar
dterei committed
369 370 371 372
            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
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

            -- 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
388
                            $ filter (not . (isPrefixOf "<"))
389 390 391 392 393 394
                            $ map unpackFS
                            $ srcfiles pst
                srcs1 = case ml_hs_file (ms_location mod_summary) of
                          Just f  -> filter (/= FilePath.normalise f) srcs0
                          Nothing -> srcs0

395 396 397 398 399
            -- sometimes we see source files from earlier
            -- preprocessing stages that cannot be found, so just
            -- filter them out:
            srcs2 <- liftIO $ filterM doesFileExist srcs1

400 401
            return HsParsedModule {
                      hpm_module    = rdr_module,
Alan Zimmerman's avatar
Alan Zimmerman committed
402 403 404 405 406
                      hpm_src_files = srcs2,
                      hpm_annotations
                              = (Map.fromListWith (++) $ annotations pst,
                                 Map.fromList $ ((noSrcSpan,comment_q pst)
                                                 :(annotations_comments pst)))
407
                   }
Simon Marlow's avatar
Simon Marlow committed
408

Thomas Schilling's avatar
Thomas Schilling committed
409 410 411
-- 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
412
type RenamedStuff =
Simon Marlow's avatar
Simon Marlow committed
413
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
414
                Maybe LHsDocString))
Simon Marlow's avatar
Simon Marlow committed
415

Thomas Schilling's avatar
Thomas Schilling committed
416
-- | Rename and typecheck a module, additionally returning the renamed syntax
417
hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
418
                   -> IO (TcGblEnv, RenamedStuff)
dterei's avatar
dterei committed
419
hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
420
    tc_result <- tcRnModule' hsc_env mod_summary True rdr_module
Thomas Schilling's avatar
Thomas Schilling committed
421

422 423 424 425 426 427
        -- This 'do' is in the Maybe monad!
    let rn_info = do decl <- tcg_rn_decls tc_result
                     let imports = tcg_rn_imports tc_result
                         exports = tcg_rn_exports tc_result
                         doc_hdr = tcg_doc_hdr tc_result
                     return (decl,imports,exports,doc_hdr)
Thomas Schilling's avatar
Thomas Schilling committed
428

429
    return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
430

431 432 433 434 435 436 437 438
-- 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

439 440 441
    -- 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)
442
    dflags   <- getDynFlags
443
    let allSafeOK = safeInferred dflags && tcSafeOK
444

445 446 447
    -- 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
448
        then markUnsafeInfer tcg_res whyUnsafe
449

450
        -- module (could be) safe, throw warning if needed
451 452
        else do
            tcg_res' <- hscCheckSafeImports tcg_res
453
            safe <- liftIO $ fst <$> readIORef (tcg_safeInfer tcg_res')
454 455
            when safe $ do
              case wopt Opt_WarnSafe dflags of
456 457 458 459
                True -> (logWarnings $ unitBag $
                         makeIntoWarning (Reason Opt_WarnSafe) $
                         mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $
                         errSafe tcg_res')
460 461
                False | safeHaskell dflags == Sf_Trustworthy &&
                        wopt Opt_WarnTrustworthySafe dflags ->
462 463 464 465
                        (logWarnings $ unitBag $
                         makeIntoWarning (Reason Opt_WarnTrustworthySafe) $
                         mkPlainWarnMsg dflags (trustworthyOnLoc dflags) $
                         errTwthySafe tcg_res')
466
                False -> return ()
467 468 469
            return tcg_res'
  where
    pprMod t  = ppr $ moduleName $ tcg_mod t
470
    errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
471 472
    errTwthySafe t = quotes (pprMod t)
      <+> text "is marked as Trustworthy but has been inferred as safe!"
473

Simon Marlow's avatar
Simon Marlow committed
474
-- | Convert a typechecked module to Core
475
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
476
hscDesugar hsc_env mod_summary tc_result =
Ian Lynagh's avatar
Ian Lynagh committed
477
    runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
478

Ian Lynagh's avatar
Ian Lynagh committed
479 480
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
dterei's avatar
dterei committed
481
    hsc_env <- getHscEnv
Simon Marlow's avatar
Simon Marlow committed
482 483
    r <- ioMsgMaybe $
      {-# SCC "deSugar" #-}
Ian Lynagh's avatar
Ian Lynagh committed
484
      deSugar hsc_env mod_location tc_result
485

dterei's avatar
dterei committed
486 487 488 489
    -- 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
490

dterei's avatar
dterei committed
491
-- | Make a 'ModDetails' from the results of typechecking. Used when
Simon Marlow's avatar
Simon Marlow committed
492
-- typechecking only, as opposed to full compilation.
493 494
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
Simon Marlow's avatar
Simon Marlow committed
495

496

dterei's avatar
dterei committed
497 498 499 500 501 502 503
{- **********************************************************************
%*                                                                      *
                The main compiler pipeline
%*                                                                      *
%********************************************************************* -}

{-
504 505 506 507
                   --------------------------------
                        The compilation proper
                   --------------------------------

dterei's avatar
dterei committed
508 509 510 511 512 513
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
514
targets byte-code.
dterei's avatar
dterei committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

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


540 541
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
-- | 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
557
  always_do_basic_recompilation_check m_tc_result
558
  mHscMessage mod_summary source_modified mb_old_iface mod_index
559
    = do
560
    hsc_env <- getHscEnv
561 562 563 564

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

566
        skip iface = do
567
            liftIO $ msg UpToDate
568
            return $ Left iface
dterei's avatar
dterei committed
569

570
        compile mb_old_hash reason = do
571 572 573
            liftIO $ msg reason
            result <- genericHscFrontend mod_summary
            return $ Right (result, mb_old_hash)
dterei's avatar
dterei committed
574 575 576 577

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

579 580 581
    case m_tc_result of
         Just tc_result
          | not always_do_basic_recompilation_check ->
582
             return $ Right (FrontendTypecheck tc_result, Nothing)
583 584 585
         _ -> do
            (recomp_reqd, mb_checked_iface)
                <- {-# SCC "checkOldIface" #-}
586
                   liftIO $ checkOldIface hsc_env mod_summary
587 588 589 590 591 592 593 594
                                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
595 596 597 598 599 600 601 602 603 604 605 606 607
                    -- 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.
608 609 610 611 612 613 614 615 616 617
                    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 ->
618
                        return $ Right (FrontendTypecheck tc_result, mb_old_hash)
619

620
genericHscFrontend :: ModSummary -> Hsc FrontendResult
621 622 623
genericHscFrontend mod_summary =
  getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)

624 625 626
genericHscFrontend' :: ModSummary -> Hsc FrontendResult
genericHscFrontend' mod_summary
    = FrontendTypecheck `fmap` hscFileFrontEnd mod_summary
627

628 629 630 631
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

Austin Seipp's avatar
Austin Seipp committed
632
-- Compile Haskell/boot in OneShot mode.
633 634 635 636 637 638 639 640 641 642 643 644 645
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
646
  = do
dterei's avatar
dterei committed
647 648
    -- One-shot mode needs a knot-tying mutable variable for interface
    -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
649
    -- See also Note [hsc_type_env_var hack]
dterei's avatar
dterei committed
650 651
    type_env_var <- newIORef emptyNameEnv
    let mod = ms_mod mod_summary
652
        hsc_env = hsc_env'{ hsc_type_env_var = Just (mod, type_env_var) }
653

654 655 656 657 658 659
    -- 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
    let dflags = hsc_dflags hsc_env
660

661 662 663
    e <- hscIncrementalFrontend always_do_basic_recompilation_check m_tc_result mHscMessage
            mod_summary source_modified mb_old_iface mod_index
    case e of
664 665
        -- We didn't need to do any typechecking; the old interface
        -- file on disk was good enough.
666
        Left iface -> do
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
            -- 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.)
688 689
        Right (FrontendTypecheck tc_result, mb_old_hash) -> do
            (status, hmi, no_change) <-
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
                    if hscTarget dflags /= HscNothing &&
                       ms_hsc_src mod_summary == HsSrcFile
                       then finish              hsc_env mod_summary tc_result mb_old_hash
                       else finishTypecheckOnly hsc_env mod_summary tc_result mb_old_hash
            liftIO $ hscMaybeWriteIface dflags (hm_iface hmi) no_change mod_summary
            return (status, hmi)

-- Generates and writes out the final interface for a typecheck.
finishTypecheckOnly :: HscEnv
              -> ModSummary
              -> TcGblEnv
              -> Maybe Fingerprint
              -> Hsc (HscStatus, HomeModInfo, Bool)
finishTypecheckOnly hsc_env summary tc_result mb_old_hash = do
    let dflags = hsc_dflags hsc_env
    (iface, changed, details) <- liftIO $ hscSimpleIface hsc_env tc_result mb_old_hash
    let hsc_status =
          case (hscTarget dflags, ms_hsc_src summary) of
            (HscNothing, _) -> HscNotGeneratingCode
            (_, HsBootFile) -> HscUpdateBoot
710
            (_, HsigFile) -> HscUpdateSig
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
            _ -> panic "finishTypecheckOnly"
    return (hsc_status,
            HomeModInfo{ hm_details  = details,
                         hm_iface    = iface,
                         hm_linkable = Nothing },
            changed)

-- 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
-- in the interface file.  This is only ever run for HsSrcFile,
-- and NOT for HscNothing.
finish :: HscEnv
       -> ModSummary
       -> TcGblEnv
       -> Maybe Fingerprint
       -> Hsc (HscStatus, HomeModInfo, Bool)
finish hsc_env summary tc_result mb_old_hash = do
    let dflags = hsc_dflags hsc_env
    MASSERT( ms_hsc_src summary == HsSrcFile )
    MASSERT( hscTarget dflags /= HscNothing )
    guts0 <- hscDesugar' (ms_location summary) tc_result
    guts <- hscSimplify' guts0
    (iface, changed, details, cgguts) <- liftIO $ hscNormalIface hsc_env guts mb_old_hash

    return (HscRecomp cgguts summary,
            HomeModInfo{ hm_details  = details,
                         hm_iface    = iface,
                         hm_linkable = Nothing },
            changed)

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
752

753 754 755 756
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

757
-- NB: this must be knot-tied appropriately, see hscIncrementalCompile
758 759
genModDetails :: HscEnv -> ModIface -> IO ModDetails
genModDetails hsc_env old_iface
760
  = do
dterei's avatar
dterei committed
761
    new_details <- {-# SCC "tcRnIface" #-}
762
                   initIfaceLoad hsc_env (typecheckIface old_iface)
763
    dumpIfaceStats hsc_env
dterei's avatar
dterei committed
764
    return new_details
765

766 767 768 769
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

770 771
oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
oneShotMsg hsc_env recomp =
dterei's avatar
dterei committed
772
    case recomp of
773
        UpToDate ->
774 775
            compilationProgressMsg (hsc_dflags hsc_env) $
                   "compilation IS NOT required"
776
        _ ->
777 778
            return ()

779 780
batchMsg :: Messager
batchMsg hsc_env mod_index recomp mod_summary =
dterei's avatar
dterei committed
781
    case recomp of
782 783 784
        MustCompile -> showMsg "Compiling " ""
        UpToDate
            | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping  " ""
dterei's avatar
dterei committed
785
            | otherwise -> return ()
786
        RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
dterei's avatar
dterei committed
787
    where
Ian Lynagh's avatar
Ian Lynagh committed
788
        dflags = hsc_dflags hsc_env
789
        showMsg msg reason =
Ian Lynagh's avatar
Ian Lynagh committed
790
            compilationProgressMsg dflags $
791
            (showModuleIndex mod_index ++
Ian Lynagh's avatar
Ian Lynagh committed
792
            msg ++ showModMsg dflags (hscTarget dflags)
793 794
                              (recompileRequired recomp) mod_summary)
                ++ reason
795

796 797 798
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
799

800 801
-- | Given a 'ModSummary', parses and typechecks it, returning the
-- 'TcGblEnv' resulting from type-checking.
802
hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
803
hscFileFrontEnd mod_summary = do
804
    hpm <- hscParse' mod_summary
805
    hsc_env <- getHscEnv
806 807
    tcg_env <- tcRnModule' hsc_env mod_summary False hpm
    return tcg_env
808 809

--------------------------------------------------------------
810
-- Safe Haskell
811 812
--------------------------------------------------------------

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
-- 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.


833 834 835
-- Note [Safe Haskell Inference]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Safe Haskell does Safe inference on modules that don't have any specific
Gabor Greif's avatar
Gabor Greif committed
836
-- safe haskell mode flag. The basic approach to this is:
837 838 839 840 841 842 843
--   * 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.
844 845 846
--
-- 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
847 848
-- to allow users to set the `-Wsafe`, `-Wunsafe` and
-- `-Wtrustworthy-safe` flags on Trustworthy and Unsafe modules so that a
849 850 851 852 853 854 855
-- 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.
856 857 858 859 860 861 862 863 864


-- | 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
865
    tcg_env' <- checkSafeImports dflags tcg_env
866
    checkRULES dflags tcg_env'
867

dterei's avatar
dterei committed
868
  where
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    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
884 885 886
    warns dflags rules = listToBag $ map (warnRules dflags) rules
    warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
        mkPlainWarnMsg dflags loc $
887
            text "Rule \"" <> ftext (snd $ unLoc n) <> text "\" ignored" $+$
dterei's avatar
dterei committed
888
            text "User defined rules are disabled under Safe Haskell"
889

890 891 892 893 894 895
-- | 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.
896
--
897 898 899 900 901
-- 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].
902 903
checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags tcg_env
904
    = do
905 906 907
        imps <- mapM condense imports'
        let (safeImps, regImps) = partition (\(_,_,s) -> s) imps

908 909 910 911 912
        -- 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

913 914 915
        -- Check safe imports are correct
        safePkgs <- mapM checkSafe safeImps
        safeErrs <- getWarnings
dterei's avatar
dterei committed
916 917
        clearWarnings

918
        -- Check non-safe imports are correct if inferring safety
919
        -- See the Note [Safe Haskell Inference]
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
        (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 }
943

dterei's avatar
dterei committed
944
  where
945 946
    impInfo  = tcg_imports tcg_env     -- ImportAvails
    imports  = imp_mods impInfo        -- ImportedMods
dterei's avatar
dterei committed
947
    imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
948
    pkgReqs  = imp_trust_pkgs impInfo  -- [UnitId]
dterei's avatar
dterei committed
949 950 951

    condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
    condense (_, [])   = panic "HscMain.condense: Pattern match failure!"
952 953
    condense (m, x:xs) = do imv <- foldlM cond' x xs
                            return (m, imv_span imv, imv_is_safe imv)