HscMain.lhs 50.9 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
3 4
%
\begin{code}
5
-- | Main API for compiling plain Haskell source code.
6
--
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
-- This module implements compilation of a Haskell source.  It is
-- /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
-- "interactive" mode (GHCi).  There are also entry points for
-- individual passes: parsing, typechecking/renaming, desugaring, and
-- simplification.
--
-- All the functions here take an 'HscEnv' as a parameter, but none of
-- them return a new one: 'HscEnv' is treated as an immutable value
-- from here on in (although it has mutable components, for the
-- caches).
--
-- Warning messages are dealt with consistently throughout this API:
-- during compilation warnings are collected, and before any function
-- in @HscMain@ returns, the warnings are either printed, or turned
-- into a real compialtion error if the @-Werror@ flag is enabled.
26
--
27
module HscMain
28 29 30 31 32 33
    ( 
    -- * Making an HscEnv
      newHscEnv

    -- * Compiling complete source files
    , Compiler
Thomas Schilling's avatar
Thomas Schilling committed
34
    , HscStatus' (..)
35
    , InteractiveStatus, HscStatus
36 37 38 39 40 41 42 43
    , hscCompileOneShot
    , hscCompileBatch
    , hscCompileNothing
    , hscCompileInteractive
    , hscCompileCmmFile
    , hscCompileCore

    -- * Running passes separately
Thomas Schilling's avatar
Thomas Schilling committed
44 45 46
    , hscParse
    , hscTypecheckRename
    , hscDesugar
Simon Marlow's avatar
Simon Marlow committed
47 48
    , makeSimpleIface
    , makeSimpleDetails
49 50 51 52 53 54 55 56 57 58 59 60 61
    , hscSimplify -- ToDo, shouldn't really export this

    -- ** Backends
    , hscOneShotBackendOnly
    , hscBatchBackendOnly
    , hscNothingBackendOnly
    , hscInteractiveBackendOnly

    -- * Support for interactive evaluation
    , hscParseIdentifier
    , hscTcRcLookupName
    , hscTcRnGetInfo
#ifdef GHCI
62
    , hscRnImportDecls
63 64
    , hscGetModuleExports
    , hscTcRnLookupRdrName
vivian's avatar
vivian committed
65 66
    , hscStmt, hscStmtWithLocation
    , hscTcExpr, hscImport, hscKcType
67 68 69
    , hscCompileCoreExpr
#endif

70
    ) where
71

72
#ifdef GHCI
73 74
import ByteCodeGen	( byteCodeGen, coreExprToBCOs )
import Linker		( HValue, linkExpr )
75
import CoreTidy		( tidyExpr )
76 77
import Type		( Type )
import TcType           ( tyVarsOfTypes )
78
import PrelNames	( iNTERACTIVE )
79
import {- Kind parts of -} Type		( Kind )
80
import Id      	     	( idType )
81
import CoreLint		( lintUnfolding )
82
import DsMeta		( templateHaskellNames )
83
import VarSet
84
import VarEnv		( emptyTidyEnv )
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
85
import Panic
86 87
#endif

88
import Id		( Id )
89 90
import Module
import Packages
Simon Marlow's avatar
Simon Marlow committed
91 92
import RdrName
import HsSyn
93
import CoreSyn
Ian Lynagh's avatar
Ian Lynagh committed
94
import StringBuffer
95
import Parser
96 97 98
import Lexer hiding (getDynFlags)
import SrcLoc
import TcRnDriver
99
import TcIface		( typecheckIface )
100
import TcRnMonad
101 102 103
import IfaceEnv		( initNameCache )
import LoadIface	( ifaceStats, initExternalPackageState )
import PrelInfo		( wiredInThings, basicKnownKeyNames )
Simon Marlow's avatar
Simon Marlow committed
104
import MkIface
105 106
import Desugar
import SimplCore
Simon Marlow's avatar
Simon Marlow committed
107
import TidyPgm
108
import CorePrep
109
import CoreToStg	( coreToStg )
110
import qualified StgCmm	( codeGen )
111 112
import StgSyn
import CostCentre
113 114
import ProfInit
import TyCon            ( TyCon, isDataTyCon )
115
import Name		( Name, NamedThing(..) )
116 117
import SimplStg		( stg2stg )
import CodeGen		( codeGen )
118
import OldCmm           ( Cmm )
119
import PprCmm		( pprCmms )
120
import CmmParse		( parseCmmFile )
121
import CmmBuildInfoTables
Edward Z. Yang's avatar
Edward Z. Yang committed
122
import CmmPipeline
123
import CmmInfo
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
124
import OptimizationFuel ( initOptFuelState )
125
import CmmCvt
126
import CmmContFlowOpt   ( runCmmContFlowOpts )
127
import CodeOutput
128
import NameEnv          ( emptyNameEnv )
129 130 131
import NameSet          ( emptyNameSet )
import InstEnv
import FamInstEnv       ( emptyFamInstEnv )
Thomas Schilling's avatar
Thomas Schilling committed
132
import Fingerprint      ( Fingerprint )
133

134
import DynFlags
135
import ErrUtils
136
import UniqSupply	( mkSplitUniqSupply )
137

138
import Outputable
139
import HscStats		( ppSourceStats )
140
import HscTypes
141
import MkExternalCore	( emitExternalCore )
142
import FastString
143
import UniqFM		( emptyUFM )
144
import UniqSupply       ( initUs_ )
145
import Bag
Thomas Schilling's avatar
Thomas Schilling committed
146
import Exception
147
-- import MonadUtils
Simon Marlow's avatar
Simon Marlow committed
148 149

import Control.Monad
150
-- import System.IO
Simon Marlow's avatar
Simon Marlow committed
151
import Data.IORef
152
\end{code}
Thomas Schilling's avatar
Thomas Schilling committed
153
#include "HsVersions.h"
154

155 156 157

%************************************************************************
%*									*
158 159 160 161 162
		Initialisation
%*									*
%************************************************************************

\begin{code}
163 164
newHscEnv :: DynFlags -> IO HscEnv
newHscEnv dflags
165
  = do 	{ eps_var <- newIORef initExternalPackageState
166 167 168
        ; us      <- mkSplitUniqSupply 'r'
        ; nc_var  <- newIORef (initNameCache us knownKeyNames)
        ; fc_var  <- newIORef emptyUFM
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
169 170
	; mlc_var <- newIORef emptyModuleEnv
        ; optFuel <- initOptFuelState
171
	; return (HscEnv { hsc_dflags = dflags,
172 173
			   hsc_targets = [],
			   hsc_mod_graph = [],
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
174 175 176 177 178 179 180
			   hsc_IC      = emptyInteractiveContext,
			   hsc_HPT     = emptyHomePackageTable,
			   hsc_EPS     = eps_var,
			   hsc_NC      = nc_var,
			   hsc_FC      = fc_var,
			   hsc_MLC     = mlc_var,
			   hsc_OptFuel = optFuel,
181
                           hsc_type_env_var = Nothing } ) }
Thomas Schilling's avatar
Thomas Schilling committed
182

183

184 185 186 187 188
knownKeyNames :: [Name]      -- Put here to avoid loops involving DsMeta,
                             -- where templateHaskellNames are defined
knownKeyNames
  = map getName wiredInThings 
    ++ basicKnownKeyNames
189
#ifdef GHCI
190
    ++ templateHaskellNames
191 192
#endif

193 194
-- -----------------------------------------------------------------------------
-- The Hsc monad: collecting warnings
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))

instance Monad Hsc where
  return a = Hsc $ \_ w -> return (a, w)
  Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
                                 case k a of
                                    Hsc k' -> k' e w1

instance MonadIO Hsc where
  liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)

runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env (Hsc hsc) = do
  (a, w) <- hsc hsc_env emptyBag
  printOrThrowWarnings (hsc_dflags hsc_env) w
  return a

getWarnings :: Hsc WarningMessages
getWarnings = Hsc $ \_ w -> return (w, w)

clearWarnings :: Hsc ()
clearWarnings = Hsc $ \_ _w -> return ((), emptyBag)

logWarnings :: WarningMessages -> Hsc ()
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)

getHscEnv :: Hsc HscEnv
getHscEnv = Hsc $ \e w -> return (e, w)

getDynFlags :: Hsc DynFlags
getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)

handleWarnings :: Hsc ()
handleWarnings = do
  dflags <- getDynFlags
  w <- getWarnings
  liftIO $ printOrThrowWarnings dflags w
  clearWarnings

-- | log warning in the monad, and if there are errors then
-- throw a SourceError exception.
logWarningsReportErrors :: Messages -> Hsc ()
logWarningsReportErrors (warns,errs) = do
  logWarnings warns
  when (not (isEmptyBag errs)) $ do
    liftIO $ throwIO $ mkSrcErr errs

-- | 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
-- and signal success via by wrapping the result in a 'Maybe' type.  This
-- 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
--     there should be warnings in the first result.  That is, if the action
--     failed, it must have been due to the warnings (i.e., @-Werror@).
ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
ioMsgMaybe ioA = do
  ((warns,errs), mb_r) <- liftIO $ ioA
  logWarnings warns
  case mb_r of
    Nothing -> liftIO $ throwIO (mkSrcErr errs)
    Just r  -> ASSERT( isEmptyBag errs ) return r

-- | like ioMsgMaybe, except that we ignore error messages and return
-- 'Nothing' instead.
ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
ioMsgMaybe' ioA = do
  ((warns,_errs), mb_r) <- liftIO $ ioA
  logWarnings warns
  return mb_r

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

#ifdef GHCI
hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
hscTcRnLookupRdrName hsc_env rdr_name = 
  runHsc hsc_env $ ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
#endif

hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
hscTcRcLookupName hsc_env name = 
  runHsc hsc_env $ ioMsgMaybe' $ tcRnLookupName hsc_env name
    -- 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.

hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [Instance]))
hscTcRnGetInfo hsc_env name =
  runHsc hsc_env $ ioMsgMaybe' $ tcRnGetInfo hsc_env name

#ifdef GHCI
hscGetModuleExports :: HscEnv -> Module -> IO (Maybe [AvailInfo])
hscGetModuleExports hsc_env mdl =
  runHsc hsc_env $ ioMsgMaybe' $ getModuleExports hsc_env mdl

-- -----------------------------------------------------------------------------
-- | Rename some import declarations

hscRnImportDecls
        :: HscEnv
        -> Module
        -> [LImportDecl RdrName]
        -> IO GlobalRdrEnv

309 310 311 312 313 314
-- It is important that we use tcRnImports instead of calling rnImports directly
-- because tcRnImports will force-load any orphan modules necessary, making extra
-- instances/family instances visible (GHC #4832)
hscRnImportDecls hsc_env this_mod import_decls
  = runHsc hsc_env $ ioMsgMaybe $ initTc hsc_env HsSrcFile False this_mod $
          fmap tcg_rdr_env $ tcRnImports hsc_env this_mod import_decls
315

316 317
#endif

318
-- -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
319
-- | parse a file, returning the abstract syntax
320 321 322 323 324 325 326 327 328 329

hscParse :: HscEnv -> ModSummary -> IO (Located (HsModule RdrName))
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary

-- internal version, that doesn't fail due to -Werror
hscParse' :: ModSummary -> Hsc (Located (HsModule RdrName))
hscParse' mod_summary
 = do
   dflags <- getDynFlags
   let 
Thomas Schilling's avatar
Thomas Schilling committed
330 331
       src_filename  = ms_hspp_file mod_summary
       maybe_src_buf = ms_hspp_buf  mod_summary
332

Thomas Schilling's avatar
Thomas Schilling committed
333 334 335 336 337 338 339 340 341 342 343
   --------------------------  Parser  ----------------
   liftIO $ showPass dflags "Parser"
   {-# SCC "Parser" #-} do

	-- sometimes we already have the buffer in memory, perhaps
	-- because we needed to parse the imports out of it, or get the
	-- module name.
   buf <- case maybe_src_buf of
            Just b  -> return b
            Nothing -> liftIO $ hGetStringBuffer src_filename

Ian Lynagh's avatar
Ian Lynagh committed
344
   let loc  = mkRealSrcLoc (mkFastString src_filename) 1 1
Thomas Schilling's avatar
Thomas Schilling committed
345

346
   case unP parseModule (mkPState dflags buf loc) of
Thomas Schilling's avatar
Thomas Schilling committed
347
     PFailed span err ->
348
         liftIO $ throwOneError (mkPlainErrMsg span err)
Thomas Schilling's avatar
Thomas Schilling committed
349 350

     POk pst rdr_module -> do
351 352 353 354 355 356
         logWarningsReportErrors (getMessages pst)
         liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
                                ppr rdr_module
         liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
                                ppSourceStats False rdr_module
         return rdr_module
Thomas Schilling's avatar
Thomas Schilling committed
357
          -- ToDo: free the string buffer later.
Simon Marlow's avatar
Simon Marlow committed
358

Thomas Schilling's avatar
Thomas Schilling committed
359 360 361
-- 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.
Simon Marlow's avatar
Simon Marlow committed
362 363
type RenamedStuff = 
        (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
364
                Maybe LHsDocString))
Simon Marlow's avatar
Simon Marlow committed
365

Thomas Schilling's avatar
Thomas Schilling committed
366
-- | Rename and typecheck a module, additionally returning the renamed syntax
367 368 369 370 371
hscTypecheckRename :: HscEnv -> ModSummary -> Located (HsModule RdrName)
                   -> IO (TcGblEnv, RenamedStuff)
hscTypecheckRename hsc_env mod_summary rdr_module
  = runHsc hsc_env $ do
      tc_result
Thomas Schilling's avatar
Thomas Schilling committed
372
          <- {-# SCC "Typecheck-Rename" #-}
373 374
              ioMsgMaybe $ 
                  tcRnModule hsc_env (ms_hsc_src mod_summary) True rdr_module
Thomas Schilling's avatar
Thomas Schilling committed
375

376 377 378
      let -- This 'do' is in the Maybe monad!
          rn_info = do decl <- tcg_rn_decls tc_result
                       let imports = tcg_rn_imports tc_result
379
                           exports = tcg_rn_exports tc_result
380
                           doc_hdr  = tcg_doc_hdr tc_result
381
                       return (decl,imports,exports,doc_hdr)
Thomas Schilling's avatar
Thomas Schilling committed
382

383
      return (tc_result, rn_info)
Simon Marlow's avatar
Simon Marlow committed
384 385

-- | Convert a typechecked module to Core
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
hscDesugar hsc_env mod_summary tc_result
  = runHsc hsc_env $ hscDesugar' mod_summary tc_result

hscDesugar' :: ModSummary -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_summary tc_result
 = do
      hsc_env <- getHscEnv
      r <- ioMsgMaybe $ 
             deSugar hsc_env (ms_location mod_summary) tc_result

      handleWarnings
                -- always check -Werror after desugaring, this is 
                -- the last opportunity for warnings to arise before
                -- the backend.
      return r
Simon Marlow's avatar
Simon Marlow committed
402 403 404 405 406 407

-- | Make a 'ModIface' from the results of typechecking.  Used when
-- not optimising, and the interface doesn't need to contain any
-- unfoldings or other cross-module optimisation info.
-- ToDo: the old interface is only needed to get the version numbers,
-- we should use fingerprint versions instead.
408
makeSimpleIface :: HscEnv -> 
Thomas Schilling's avatar
Thomas Schilling committed
409
                   Maybe ModIface -> TcGblEnv -> ModDetails
410 411 412 413 414
                -> IO (ModIface,Bool)
makeSimpleIface hsc_env maybe_old_iface tc_result details
  = runHsc hsc_env $
     ioMsgMaybe $ 
       mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) details tc_result
Simon Marlow's avatar
Simon Marlow committed
415 416 417

-- | Make a 'ModDetails' from the results of typechecking.  Used when
-- typechecking only, as opposed to full compilation.
418 419
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
Simon Marlow's avatar
Simon Marlow committed
420 421
\end{code}

422 423 424
%************************************************************************
%*									*
		The main compiler pipeline
425 426 427
%*									*
%************************************************************************

428 429 430 431 432 433
                   --------------------------------
                        The compilation proper
                   --------------------------------


It's the task of the compilation proper to compile Haskell, hs-boot and
dterei's avatar
dterei committed
434
core files to either byte-code, hard-code (C, asm, LLVM, ect) or to
435 436
nothing at all (the module is still parsed and type-checked. This
feature is mostly used by IDE's and the likes).
437 438 439 440 441
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
targets byte-code.
The modes are kept separate because of their different types and meanings.
442 443 444
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
445 446 447 448 449 450 451 452 453 454 455
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.

456 457 458
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.

459
\begin{code}
460

461
-- Status of a compilation to hard-code or nothing.
Thomas Schilling's avatar
Thomas Schilling committed
462
data HscStatus' a
463
    = HscNoRecomp
Thomas Schilling's avatar
Thomas Schilling committed
464
    | HscRecomp
465 466
       (Maybe FilePath)
            -- Has stub files.  This is a hack. We can't compile C files here
Thomas Schilling's avatar
Thomas Schilling committed
467 468 469 470 471 472 473 474
            -- since it's done in DriverPipeline. For now we just return True
            -- if we want the caller to compile them for us.
       a

-- This is a bit ugly.  Since we use a typeclass below and would like to avoid
-- functional dependencies, we have to parameterise the typeclass over the
-- result type.  Therefore we need to artificially distinguish some types.  We
-- do this by adding type tags which will simply be ignored by the caller.
475
type HscStatus         = HscStatus' ()
476 477
type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks))
    -- INVARIANT: result is @Nothing@ <=> input was a boot file
Thomas Schilling's avatar
Thomas Schilling committed
478

479 480 481
type OneShotResult     = HscStatus
type BatchResult       = (HscStatus, ModIface, ModDetails)
type NothingResult     = (HscStatus, ModIface, ModDetails)
Thomas Schilling's avatar
Thomas Schilling committed
482
type InteractiveResult = (InteractiveStatus, ModIface, ModDetails)
483 484

-- FIXME: The old interface and module index are only using in 'batch' and
David Himmelstrup's avatar
David Himmelstrup committed
485
--        'interactive' mode. They should be removed from 'oneshot' mode.
486
type Compiler result =  HscEnv
487 488 489 490
                     -> ModSummary
                     -> Bool                -- True <=> source unchanged
                     -> Maybe ModIface      -- Old interface, if available
                     -> Maybe (Int,Int)     -- Just (i,n) <=> module i of n (for msgs)
491
                     -> IO result
492

493 494 495
data HsCompiler a
  = HsCompiler {
    -- | Called when no recompilation is necessary.
496 497
    hscNoRecomp :: ModIface
                -> Hsc a,
498 499

    -- | Called to recompile the module.
500 501
    hscRecompile :: ModSummary -> Maybe Fingerprint
                 -> Hsc a,
502

503 504
    hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint
               -> Hsc a,
505

506
    -- | Code generation for Boot modules.
507 508
    hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint
                     -> Hsc a,
509 510

    -- | Code generation for normal modules.
511 512
    hscGenOutput :: ModGuts  -> ModSummary -> Maybe Fingerprint
                 -> Hsc a
513 514
  }

515 516
genericHscCompile :: HsCompiler a
                  -> (HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ())
Thomas Schilling's avatar
Thomas Schilling committed
517 518
                  -> HscEnv -> ModSummary -> Bool
                  -> Maybe ModIface -> Maybe (Int, Int)
519 520 521 522 523
                  -> IO a
genericHscCompile compiler hscMessage hsc_env
                  mod_summary source_unchanged
                  mb_old_iface0 mb_mod_index
 = do
Thomas Schilling's avatar
Thomas Schilling committed
524 525
     (recomp_reqd, mb_checked_iface)
         <- {-# SCC "checkOldIface" #-}
526 527
            checkOldIface hsc_env mod_summary 
                          source_unchanged mb_old_iface0
Thomas Schilling's avatar
Thomas Schilling committed
528 529 530 531 532 533
     -- 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 recomp_reqd
534 535
           -> do hscMessage hsc_env mb_mod_index False mod_summary
                 runHsc hsc_env $ hscNoRecomp compiler iface
Thomas Schilling's avatar
Thomas Schilling committed
536
       _otherwise
537 538
           -> do hscMessage hsc_env mb_mod_index True mod_summary
                 runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash
Thomas Schilling's avatar
Thomas Schilling committed
539

540 541
hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a
hscCheckRecompBackend compiler tc_result 
542 543
                   hsc_env mod_summary source_unchanged mb_old_iface _m_of_n
  = do
544 545
     (recomp_reqd, mb_checked_iface)
         <- {-# SCC "checkOldIface" #-}
546 547
            checkOldIface hsc_env mod_summary
                          source_unchanged mb_old_iface
548 549 550 551

     let mb_old_hash = fmap mi_iface_hash mb_checked_iface
     case mb_checked_iface of
       Just iface | not recomp_reqd
552 553 554
           -> runHsc hsc_env $ 
                 hscNoRecomp compiler
                             iface{ mi_globals = Just (tcg_rdr_env tc_result) }
555
       _otherwise
556 557
           -> runHsc hsc_env $
                 hscBackend compiler tc_result mod_summary mb_old_hash
558

559
genericHscRecompile :: HsCompiler a
560
                    -> ModSummary -> Maybe Fingerprint
561
                    -> Hsc a
562
genericHscRecompile compiler mod_summary mb_old_hash
Thomas Schilling's avatar
Thomas Schilling committed
563 564 565 566
  | ExtCoreFile <- ms_hsc_src mod_summary =
      panic "GHC does not currently support reading External Core files"
  | otherwise = do
      tc_result <- hscFileFrontEnd mod_summary
567 568
      hscBackend compiler tc_result mod_summary mb_old_hash

569
genericHscBackend :: HsCompiler a
570
                  -> TcGblEnv -> ModSummary -> Maybe Fingerprint
571
                  -> Hsc a
572 573 574 575
genericHscBackend compiler tc_result mod_summary mb_old_hash
  | HsBootFile <- ms_hsc_src mod_summary =
      hscGenBootOutput compiler tc_result mod_summary mb_old_hash
  | otherwise = do
576
      guts <- hscDesugar' mod_summary tc_result
577
      hscGenOutput compiler guts mod_summary mb_old_hash
Thomas Schilling's avatar
Thomas Schilling committed
578

579 580 581 582 583
compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a
compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ =
  runHsc hsc_env $
    hscBackend comp tcg ms' Nothing

584 585 586 587
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------

588 589 590 591
hscOneShotCompiler :: HsCompiler OneShotResult
hscOneShotCompiler =
  HsCompiler {

592
    hscNoRecomp = \_old_iface -> do
593 594
      hsc_env <- getHscEnv
      liftIO $ dumpIfaceStats hsc_env
595 596 597 598
      return HscNoRecomp

  , hscRecompile = genericHscRecompile hscOneShotCompiler

599
  , hscBackend = \ tc_result mod_summary mb_old_hash -> do
600 601
       dflags <- getDynFlags
       case hscTarget dflags of
602
         HscNothing -> return (HscRecomp Nothing ())
603
         _otherw    -> genericHscBackend hscOneShotCompiler
604
                                         tc_result mod_summary mb_old_hash
605

606 607 608
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
       (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface
       hscWriteIface iface changed mod_summary
609
       return (HscRecomp Nothing ())
610 611

  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
612 613
       guts <- hscSimplify' guts0
       (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface
614 615 616 617
       hscWriteIface iface changed mod_summary
       hasStub <- hscGenHardCode cgguts mod_summary
       return (HscRecomp hasStub ())
  }
618

Thomas Schilling's avatar
Thomas Schilling committed
619
-- Compile Haskell, boot and extCore in OneShot mode.
620
hscCompileOneShot :: Compiler OneShotResult
621 622
hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
  = do
623 624
       -- One-shot mode needs a knot-tying mutable variable for interface
       -- files.  See TcRnTypes.TcGblEnv.tcg_type_env_var.
625
      type_env_var <- newIORef emptyNameEnv
626 627 628 629 630 631 632 633
      let
         mod = ms_mod mod_summary
         hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
      ---
      genericHscCompile hscOneShotCompiler
                        oneShotMsg hsc_env' mod_summary src_changed
                        mb_old_iface mb_i_of_n

Thomas Schilling's avatar
Thomas Schilling committed
634

635 636 637
hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult
hscOneShotBackendOnly = compilerBackend hscOneShotCompiler

Thomas Schilling's avatar
Thomas Schilling committed
638 639
--------------------------------------------------------------

640 641 642
hscBatchCompiler :: HsCompiler BatchResult
hscBatchCompiler =
  HsCompiler {
Thomas Schilling's avatar
Thomas Schilling committed
643

644
    hscNoRecomp = \iface -> do
645 646
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
647

648
  , hscRecompile = genericHscRecompile hscBatchCompiler
Thomas Schilling's avatar
Thomas Schilling committed
649

650 651
  , hscBackend = genericHscBackend hscBatchCompiler

652
  , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do
653
       (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface
654
       hscWriteIface iface changed mod_summary
655
       return (HscRecomp Nothing (), iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
656

657
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
658 659
       guts <- hscSimplify' guts0
       (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface
660 661 662 663
       hscWriteIface iface changed mod_summary
       hasStub <- hscGenHardCode cgguts mod_summary
       return (HscRecomp hasStub (), iface, details)
  }
664

665
-- Compile Haskell, boot and extCore in batch mode.
666
hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails)
667
hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg
Thomas Schilling's avatar
Thomas Schilling committed
668

669 670 671
hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult
hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler

Thomas Schilling's avatar
Thomas Schilling committed
672 673
--------------------------------------------------------------

674 675 676
hscInteractiveCompiler :: HsCompiler InteractiveResult
hscInteractiveCompiler =
  HsCompiler {
677
    hscNoRecomp = \iface -> do
678 679
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
680

681
  , hscRecompile = genericHscRecompile hscInteractiveCompiler
Thomas Schilling's avatar
Thomas Schilling committed
682

683 684 685 686
  , hscBackend = genericHscBackend hscInteractiveCompiler

  , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do
       (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
687
       return (HscRecomp Nothing Nothing, iface, details)
Thomas Schilling's avatar
Thomas Schilling committed
688

689
  , hscGenOutput = \guts0 mod_summary mb_old_iface -> do
690 691
       guts <- hscSimplify' guts0
       (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface
692 693
       hscInteractive (iface, details, cgguts) mod_summary
  }
694 695 696

-- Compile Haskell, extCore to bytecode.
hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails)
697
hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg
Thomas Schilling's avatar
Thomas Schilling committed
698

699 700 701
hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult
hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler

Thomas Schilling's avatar
Thomas Schilling committed
702 703
--------------------------------------------------------------

704 705 706
hscNothingCompiler :: HsCompiler NothingResult
hscNothingCompiler =
  HsCompiler {
707
    hscNoRecomp = \iface -> do
708 709
       details <- genModDetails iface
       return (HscNoRecomp, iface, details)
Simon Marlow's avatar
Simon Marlow committed
710

711
  , hscRecompile = genericHscRecompile hscNothingCompiler
712

713
  , hscBackend = \tc_result _mod_summary mb_old_iface -> do
714
       handleWarnings
715
       (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface
716
       return (HscRecomp Nothing (), iface, details)
717

718 719 720
  , hscGenBootOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenBootOutput should not be called"

721 722 723
  , hscGenOutput = \_ _ _ ->
        panic "hscCompileNothing: hscGenOutput should not be called"
  }
724

725
-- Type-check Haskell and .hs-boot only (no external core)
726
hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails)
727
hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg
728

729 730 731
hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult
hscNothingBackendOnly = compilerBackend hscNothingCompiler

732 733 734 735
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------

736 737 738 739
genModDetails :: ModIface -> Hsc ModDetails
genModDetails old_iface
  = do
      hsc_env <- getHscEnv
Thomas Schilling's avatar
Thomas Schilling committed
740
      new_details <- {-# SCC "tcRnIface" #-}
741 742 743
                     liftIO $ initIfaceCheck hsc_env $
                              typecheckIface old_iface
      liftIO $ dumpIfaceStats hsc_env
Thomas Schilling's avatar
Thomas Schilling committed
744
      return new_details
745

746 747 748 749
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------

750 751
oneShotMsg :: HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ()
oneShotMsg hsc_env _mb_mod_index recomp _mod_summary =
752 753 754 755 756
         if recomp
            then return ()
            else compilationProgressMsg (hsc_dflags hsc_env) $
                     "compilation IS NOT required"

757 758 759
batchMsg :: HscEnv -> Maybe (Int,Int) -> Bool -> ModSummary -> IO ()
batchMsg hsc_env mb_mod_index recomp mod_summary
  = do
760 761
         let showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $
                           (showModuleIndex mb_mod_index ++
762
                            msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) recomp mod_summary)
763 764
         if recomp
            then showMsg "Compiling "
765
            else if verbosity (hsc_dflags hsc_env) >= 2
766 767
                    then showMsg "Skipping  "
                    else return ()
768

769 770 771
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
772 773

hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
hscFileFrontEnd mod_summary = do
    rdr_module <- hscParse' mod_summary
    hsc_env <- getHscEnv
    {-# SCC "Typecheck-Rename" #-}
        tcg_env <- ioMsgMaybe $
            tcRnModule hsc_env (ms_hsc_src mod_summary) False rdr_module
    dflags <- getDynFlags
    tcg_env' <- checkSafeImports dflags hsc_env tcg_env
    return tcg_env'

--------------------------------------------------------------
-- SafeHaskell
--------------------------------------------------------------

-- | 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.
checkSafeImports :: DynFlags -> HscEnv -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags hsc_env tcg_env
    | not (safeHaskellOn dflags)
    = return tcg_env

    | otherwise
    = do
        imps <- mapM condense imports'
        mapM_ checkSafe imps
        return tcg_env
    where
        imp_info = tcg_imports tcg_env     -- ImportAvails
        imports  = imp_mods imp_info       -- ImportedMods
        imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])

        condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
        condense (_, [])   = panic "HscMain.condense: Pattern match failure!"
        condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs
                                return (m, l, s)
        
        -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
        cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
        cond' v1@(m1,_,l1,s1) (_,_,_,s2)
            | s1 /= s2
            = liftIO $ throwIO $ mkSrcErr $ unitBag $ mkPlainErrMsg l1
                    (text "Module" <+> ppr m1 <+> (text $ "is imported"
                        ++ " both as a safe and unsafe import!"))

            | otherwise
            = return v1

        lookup' :: Module -> Hsc (Maybe ModIface)
        lookup' m = do
            hsc_eps <- liftIO $ hscEPS hsc_env
            let pkgIfaceT = eps_PIT hsc_eps
                homePkgT = hsc_HPT hsc_env
                iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
            return iface

        -- | Check the package a module resides in is trusted.
        -- Modules in the home package are trusted but otherwise
        -- we check the packages trust flag.
        packageTrusted :: Module -> Bool
        packageTrusted m
            | thisPackage dflags == modulePackageId m = True
            | otherwise = trusted $ getPackageDetails (pkgState dflags)
                                                      (modulePackageId m)

        -- Is a module a Safe importable? Return Nothing if True, or a String
        -- if it isn't containing the reason it isn't
        isModSafe :: Module -> SrcSpan -> Hsc (Maybe SDoc)
        isModSafe m l = do
            iface <- lookup' m
            case iface of
                -- can't load iface to check trust!
                Nothing -> liftIO $ throwIO $ mkSrcErr $ unitBag $ mkPlainErrMsg l
                            $ text "Can't load the interface file for" <+> ppr m <>
                              text ", to check that it can be safely imported"

                -- got iface, check trust
                Just iface' -> do
                    let trust = getSafeMode $ mi_trust iface'
                        -- check module is trusted
                        safeM = trust `elem` [Sf_Safe, Sf_Trustworthy,
                                            Sf_TrustworthyWithSafeLanguage]
                        -- check package is trusted
                        safeP = packageTrusted m
                    if safeM && safeP
                        then return Nothing
                        else return $ Just $ if safeM
                            then text "The package (" <> ppr (modulePackageId m) <>
                                 text ") the module resides in isn't trusted."
                            else text "The module itself isn't safe."

        checkSafe :: (Module, SrcSpan, IsSafeImport) -> Hsc ()
        checkSafe (_, _, False) = return ()
        checkSafe (m, l, True ) = do
            module_safe <- isModSafe m l
            case module_safe of
                Nothing -> return ()
                Just s  -> liftIO $ throwIO $ mkSrcErr $ unitBag $ mkPlainErrMsg l
                            $ text "Safe import of" <+> ppr m <+> text "can't be met!"
                                <+> s
877

878 879 880
--------------------------------------------------------------
-- Simplifiers
--------------------------------------------------------------
881

882 883 884 885 886 887 888 889
hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts

hscSimplify' :: ModGuts -> Hsc ModGuts
hscSimplify' ds_result
  = do hsc_env <- getHscEnv
       {-# SCC "Core2Core" #-}
         liftIO $ core2core hsc_env ds_result
890 891

--------------------------------------------------------------
892
-- Interface generators
893 894
--------------------------------------------------------------

895
hscSimpleIface :: TcGblEnv
Thomas Schilling's avatar
Thomas Schilling committed
896
               -> Maybe Fingerprint
897
               -> Hsc (ModIface, Bool, ModDetails)
Thomas Schilling's avatar
Thomas Schilling committed
898
hscSimpleIface tc_result mb_old_iface
899 900
  = do 
       hsc_env <- getHscEnv
Thomas Schilling's avatar
Thomas Schilling committed
901
       details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
Thomas Schilling's avatar
Thomas Schilling committed
902
       (new_iface, no_change)
903
           <- {-# SCC "MkFinalIface" #-}
904 905
              ioMsgMaybe $ 
                mkIfaceTc hsc_env mb_old_iface details tc_result
906
       -- And the answer is ...
Thomas Schilling's avatar
Thomas Schilling committed
907 908 909
       liftIO $ dumpIfaceStats hsc_env
       return (new_iface, no_change, details)

910
hscNormalIface :: ModGuts
Thomas Schilling's avatar
Thomas Schilling committed
911
               -> Maybe Fingerprint
912
               -> Hsc (ModIface, Bool, ModDetails, CgGuts)
Thomas Schilling's avatar
Thomas Schilling committed
913
hscNormalIface simpl_result mb_old_iface
914 915
  = do 
       hsc_env <- getHscEnv
916
       (cg_guts, details) <- {-# SCC "CoreTidy" #-}
Thomas Schilling's avatar
Thomas Schilling committed
917
                             liftIO $ tidyProgram hsc_env simpl_result
918 919 920 921 922 923

	    -- BUILD THE NEW ModIface and ModDetails
	    --	and emit external core if necessary
	    -- This has to happen *after* code gen so that the back-end
	    -- info has been set.  Not yet clear if it matters waiting
	    -- until after code output
924
       (new_iface, no_change)
Thomas Schilling's avatar
Thomas Schilling committed
925
	   <- {-# SCC "MkFinalIface" #-}
926 927 928 929
	      ioMsgMaybe $ 
                   mkIface hsc_env mb_old_iface details simpl_result

       -- Emit external core
930 931 932
       -- This should definitely be here and not after CorePrep,
       -- because CorePrep produces unqualified constructor wrapper declarations,
       -- so its output isn't valid External Core (without some preprocessing).
Thomas Schilling's avatar
Thomas Schilling committed
933 934
       liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts
       liftIO $ dumpIfaceStats hsc_env
935 936

 	    -- Return the prepared code.
937
       return (new_iface, no_change, details, cg_guts)
938

939
--------------------------------------------------------------
940
-- BackEnd combinators
941 942
--------------------------------------------------------------

943 944
hscWriteIface :: ModIface
              -> Bool
Thomas Schilling's avatar
Thomas Schilling committed
945
              -> ModSummary
946 947
              -> Hsc ()

Thomas Schilling's avatar
Thomas Schilling committed
948
hscWriteIface iface no_change mod_summary
949
    = do dflags <- getDynFlags
950
         unless no_change
951
           $ liftIO $ writeIfaceFile dflags (ms_location mod_summary) iface
Thomas Schilling's avatar
Thomas Schilling committed
952 953

-- | Compile to hard-code.
954
hscGenHardCode :: CgGuts -> ModSummary
955
               -> Hsc (Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
Thomas Schilling's avatar
Thomas Schilling committed
956
hscGenHardCode cgguts mod_summary
957 958 959
  = do
    hsc_env <- getHscEnv
    liftIO $ do
960
         let CgGuts{ -- This is the last use of the ModGuts in a compilation.
961 962 963 964
                     -- From now on, we just use the bits we need.
                     cg_module   = this_mod,
                     cg_binds    = core_binds,
                     cg_tycons   = tycons,
965
                     cg_foreign  = foreign_stubs0,
andy@galois.com's avatar
andy@galois.com committed
966
                     cg_dep_pkgs = dependencies,
967
                     cg_hpc_info = hpc_info } = cgguts
968 969 970 971 972 973 974 975 976 977 978 979 980 981
             dflags = hsc_dflags hsc_env
             location = ms_location mod_summary
             data_tycons = filter isDataTyCon tycons
             -- cg_tycons includes newtypes, for the benefit of External Core,
             -- but we don't generate any code for newtypes

         -------------------
         -- PREPARE FOR CODE GENERATION
         -- Do saturation and convert to A-normal form
         prepd_binds <- {-# SCC "CorePrep" #-}
                        corePrepPgm dflags core_binds data_tycons ;
         -----------------  Convert to STG ------------------
         (stg_binds, cost_centre_info)
             <- {-# SCC "CoreToStg" #-}
Simon Marlow's avatar
Simon Marlow committed
982
                myCoreToStg dflags this_mod prepd_binds	
983

984 985 986
         let prof_init = profilingInitCode this_mod cost_centre_info
             foreign_stubs = foreign_stubs0 `appendStubC` prof_init

987
         ------------------  Code generation ------------------
988 989
         
         cmms <- if dopt Opt_TryNewCodeGen dflags
990
                 then do cmms <- tryNewCodeGen hsc_env this_mod data_tycons
991
                                 cost_centre_info
992
                                 stg_binds hpc_info
993
                         return cmms
994