1 -------------------------------------------------------------------------------
3 -- | Main API for compiling plain Haskell source code.
5 -- This module implements compilation of a Haskell source. It is
6 -- /not/ concerned with preprocessing of source files; this is handled
7 -- in "DriverPipeline".
9 -- There are various entry points depending on what mode we're in:
10 -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
11 -- "interactive" mode (GHCi). There are also entry points for
12 -- individual passes: parsing, typechecking/renaming, desugaring, and
15 -- All the functions here take an 'HscEnv' as a parameter, but none of
16 -- them return a new one: 'HscEnv' is treated as an immutable value
17 -- from here on in (although it has mutable components, for the
20 -- Warning messages are dealt with consistently throughout this API:
21 -- during compilation warnings are collected, and before any function
22 -- in @HscMain@ returns, the warnings are either printed, or turned
23 -- into a real compialtion error if the @-Werror@ flag is enabled.
25 -- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
27 -------------------------------------------------------------------------------
34 -- * Compiling complete source files
37 , InteractiveStatus
, HscStatus
41 , hscCompileInteractive
45 -- * Running passes separately
51 , hscSimplify
-- ToDo, shouldn't really export this
54 , hscOneShotBackendOnly
56 , hscNothingBackendOnly
57 , hscInteractiveBackendOnly
59 -- * Support for interactive evaluation
64 , hscGetModuleInterface
66 , hscTcRnLookupRdrName
67 , hscStmt
, hscStmtWithLocation
68 , hscDecls
, hscDeclsWithLocation
69 , hscTcExpr
, hscImport
, hscKcType
75 import ByteCodeGen
( byteCodeGen
, coreExprToBCOs
)
77 import CoreTidy
( tidyExpr
)
80 import {- Kind parts of -} Type
( Kind
)
81 import CoreLint
( lintUnfolding
)
82 import DsMeta
( templateHaskellNames
)
84 import VarEnv
( emptyTidyEnv
)
99 import TcIface
( typecheckIface
)
101 import IfaceEnv
( initNameCache
)
102 import LoadIface
( ifaceStats
, initExternalPackageState
)
109 import CoreToStg
( coreToStg
)
110 import qualified StgCmm
( codeGen
)
116 import SimplStg
( stg2stg
)
117 import CodeGen
( codeGen
)
118 import OldCmm
as Old
( CmmGroup
)
119 import PprCmm
( pprCmms
)
120 import CmmParse
( parseCmmFile
)
121 import CmmBuildInfoTables
124 import OptimizationFuel
( initOptFuelState
)
127 import NameEnv
( emptyNameEnv
)
128 import NameSet
( emptyNameSet
)
131 import Fingerprint
( Fingerprint
)
135 import UniqSupply
( mkSplitUniqSupply
)
138 import HscStats
( ppSourceStats
)
140 import MkExternalCore
( emitExternalCore
)
142 import UniqFM
( emptyUFM
)
143 import UniqSupply
( initUs_
)
151 import System
.FilePath as FilePath
152 import System
.Directory
154 #include
"HsVersions.h"
157 {- **********************************************************************
161 %********************************************************************* -}
163 newHscEnv
:: DynFlags
-> IO HscEnv
164 newHscEnv dflags
= do
165 eps_var
<- newIORef initExternalPackageState
166 us
<- mkSplitUniqSupply
'r
'
167 nc_var
<- newIORef
(initNameCache us knownKeyNames
)
168 fc_var
<- newIORef emptyUFM
169 mlc_var
<- newIORef emptyModuleEnv
170 optFuel
<- initOptFuelState
171 safe_var
<- newIORef
True
172 return HscEnv
{ hsc_dflags
= dflags
,
175 hsc_IC
= emptyInteractiveContext
,
176 hsc_HPT
= emptyHomePackageTable
,
181 hsc_OptFuel
= optFuel
,
182 hsc_type_env_var
= Nothing
,
183 hsc_safeInf
= safe_var
}
186 knownKeyNames
:: [Name
] -- Put here to avoid loops involving DsMeta,
187 knownKeyNames
= -- where templateHaskellNames are defined
188 map getName wiredInThings
189 ++ basicKnownKeyNames
191 ++ templateHaskellNames
194 -- -----------------------------------------------------------------------------
195 -- The Hsc monad: Passing an enviornment and warning state
197 newtype Hsc a
= Hsc
(HscEnv
-> WarningMessages
-> IO (a
, WarningMessages
))
199 instance Monad Hsc
where
200 return a
= Hsc
$ \_ w
-> return (a
, w
)
201 Hsc m
>>= k
= Hsc
$ \e w
-> do (a
, w1
) <- m e w
205 instance MonadIO Hsc
where
206 liftIO io
= Hsc
$ \_ w
-> do a
<- io
; return (a
, w
)
208 runHsc
:: HscEnv
-> Hsc a
-> IO a
209 runHsc hsc_env
(Hsc hsc
) = do
210 (a
, w
) <- hsc hsc_env emptyBag
211 printOrThrowWarnings
(hsc_dflags hsc_env
) w
214 getWarnings
:: Hsc WarningMessages
215 getWarnings
= Hsc
$ \_ w
-> return (w
, w
)
217 clearWarnings
:: Hsc
()
218 clearWarnings
= Hsc
$ \_ _
-> return ((), emptyBag
)
220 logWarnings
:: WarningMessages
-> Hsc
()
221 logWarnings w
= Hsc
$ \_ w0
-> return ((), w0 `unionBags` w
)
223 getHscEnv
:: Hsc HscEnv
224 getHscEnv
= Hsc
$ \e w
-> return (e
, w
)
226 instance HasDynFlags Hsc
where
227 getDynFlags
= Hsc
$ \e w
-> return (hsc_dflags e
, w
)
229 handleWarnings
:: Hsc
()
231 dflags
<- getDynFlags
233 liftIO
$ printOrThrowWarnings dflags w
236 -- | log warning in the monad, and if there are errors then
237 -- throw a SourceError exception.
238 logWarningsReportErrors
:: Messages
-> Hsc
()
239 logWarningsReportErrors
(warns
,errs
) = do
241 when (not $ isEmptyBag errs
) $ throwErrors errs
243 -- | Throw some errors.
244 throwErrors
:: ErrorMessages
-> Hsc a
245 throwErrors
= liftIO
. throwIO
. mkSrcErr
247 -- | Deal with errors and warnings returned by a compilation step
249 -- In order to reduce dependencies to other parts of the compiler, functions
250 -- outside the "main" parts of GHC return warnings and errors as a parameter
251 -- and signal success via by wrapping the result in a 'Maybe' type. This
252 -- function logs the returned warnings and propagates errors as exceptions
253 -- (of type 'SourceError').
255 -- This function assumes the following invariants:
257 -- 1. If the second result indicates success (is of the form 'Just x'),
258 -- there must be no error messages in the first result.
260 -- 2. If there are no error messages, but the second result indicates failure
261 -- there should be warnings in the first result. That is, if the action
262 -- failed, it must have been due to the warnings (i.e., @-Werror@).
263 ioMsgMaybe
:: IO (Messages
, Maybe a
) -> Hsc a
265 ((warns
,errs
), mb_r
) <- liftIO
$ ioA
268 Nothing
-> throwErrors errs
269 Just r
-> ASSERT
( isEmptyBag errs
) return r
271 -- | like ioMsgMaybe, except that we ignore error messages and return
272 -- 'Nothing' instead.
273 ioMsgMaybe
' :: IO (Messages
, Maybe a
) -> Hsc
(Maybe a
)
275 ((warns
,_errs
), mb_r
) <- liftIO
$ ioA
279 -- -----------------------------------------------------------------------------
280 -- | Lookup things in the compiler's environment
283 hscTcRnLookupRdrName
:: HscEnv
-> RdrName
-> IO [Name
]
284 hscTcRnLookupRdrName hsc_env rdr_name
=
285 runHsc hsc_env
$ ioMsgMaybe
$ tcRnLookupRdrName hsc_env rdr_name
288 hscTcRcLookupName
:: HscEnv
-> Name
-> IO (Maybe TyThing
)
289 hscTcRcLookupName hsc_env name
=
290 runHsc hsc_env
$ ioMsgMaybe
' $ tcRnLookupName hsc_env name
291 -- ignore errors: the only error we're likely to get is
292 -- "name not found", and the Maybe in the return type
293 -- is used to indicate that.
295 hscTcRnGetInfo
:: HscEnv
-> Name
-> IO (Maybe (TyThing
, Fixity
, [Instance
]))
296 hscTcRnGetInfo hsc_env name
=
297 runHsc hsc_env
$ ioMsgMaybe
' $ tcRnGetInfo hsc_env name
300 hscGetModuleInterface
:: HscEnv
-> Module
-> IO ModIface
301 hscGetModuleInterface hsc_env
mod =
302 runHsc hsc_env
$ ioMsgMaybe
$ getModuleInterface hsc_env
mod
304 -- -----------------------------------------------------------------------------
305 -- | Rename some import declarations
306 hscRnImportDecls
:: HscEnv
-> [LImportDecl RdrName
] -> IO GlobalRdrEnv
307 hscRnImportDecls hsc_env import_decls
=
308 runHsc hsc_env
$ ioMsgMaybe
$ tcRnImportDecls hsc_env import_decls
311 -- -----------------------------------------------------------------------------
312 -- | parse a file, returning the abstract syntax
314 hscParse
:: HscEnv
-> ModSummary
-> IO HsParsedModule
315 hscParse hsc_env mod_summary
= runHsc hsc_env
$ hscParse
' mod_summary
317 -- internal version, that doesn't fail due to -Werror
318 hscParse
' :: ModSummary
-> Hsc HsParsedModule
319 hscParse
' mod_summary
= do
320 dflags
<- getDynFlags
321 let src_filename
= ms_hspp_file mod_summary
322 maybe_src_buf
= ms_hspp_buf mod_summary
324 -------------------------- Parser ----------------
325 liftIO
$ showPass dflags
"Parser"
326 {-# SCC "Parser" #-} do
328 -- sometimes we already have the buffer in memory, perhaps
329 -- because we needed to parse the imports out of it, or get the
331 buf
<- case maybe_src_buf
of
333 Nothing
-> liftIO
$ hGetStringBuffer src_filename
335 let loc
= mkRealSrcLoc
(mkFastString src_filename
) 1 1
337 case unP parseModule
(mkPState dflags buf loc
) of
339 liftIO
$ throwOneError
(mkPlainErrMsg span err
)
341 POk pst rdr_module
-> do
342 logWarningsReportErrors
(getMessages pst
)
343 liftIO
$ dumpIfSet_dyn dflags Opt_D_dump_parsed
"Parser" $
345 liftIO
$ dumpIfSet_dyn dflags Opt_D_source_stats
"Source Statistics" $
346 ppSourceStats
False rdr_module
348 -- To get the list of extra source files, we take the list
349 -- that the parser gave us,
350 -- - eliminate files beginning with '<'. gcc likes to use
351 -- pseudo-filenames like "<built-in>" and "<command-line>"
352 -- - normalise them (elimiante differences between ./f and f)
353 -- - filter out the preprocessed source file
354 -- - filter out anything beginning with tmpdir
355 -- - remove duplicates
356 -- - filter out the .hs/.lhs source filename if we have one
358 let n_hspp
= FilePath.normalise src_filename
359 srcs0
= nub $ filter (not . (tmpDir dflags `
isPrefixOf`
))
360 $ filter (not . (== n_hspp
))
361 $ map FilePath.normalise
362 $ filter (not . (== '<') . head)
365 srcs1
= case ml_hs_file
(ms_location mod_summary
) of
366 Just f
-> filter (/= FilePath.normalise f
) srcs0
369 -- sometimes we see source files from earlier
370 -- preprocessing stages that cannot be found, so just
372 srcs2
<- liftIO
$ filterM doesFileExist srcs1
374 return HsParsedModule
{
375 hpm_module
= rdr_module
,
376 hpm_src_files
= srcs2
379 -- XXX: should this really be a Maybe X? Check under which circumstances this
380 -- can become a Nothing and decide whether this should instead throw an
381 -- exception/signal an error.
383 (Maybe (HsGroup Name
, [LImportDecl Name
], Maybe [LIE Name
],
386 -- | Rename and typecheck a module, additionally returning the renamed syntax
387 hscTypecheckRename
:: HscEnv
-> ModSummary
-> HsParsedModule
388 -> IO (TcGblEnv
, RenamedStuff
)
389 hscTypecheckRename hsc_env mod_summary rdr_module
= runHsc hsc_env
$ do
390 tc_result
<- {-# SCC "Typecheck-Rename" #-}
392 tcRnModule hsc_env
(ms_hsc_src mod_summary
)
395 -- This 'do' is in the Maybe monad!
396 let rn_info
= do decl
<- tcg_rn_decls tc_result
397 let imports
= tcg_rn_imports tc_result
398 exports
= tcg_rn_exports tc_result
399 doc_hdr
= tcg_doc_hdr tc_result
400 return (decl
,imports
,exports
,doc_hdr
)
402 return (tc_result
, rn_info
)
404 -- | Convert a typechecked module to Core
405 hscDesugar
:: HscEnv
-> ModSummary
-> TcGblEnv
-> IO ModGuts
406 hscDesugar hsc_env mod_summary tc_result
=
407 runHsc hsc_env
$ hscDesugar
' (ms_location mod_summary
) tc_result
409 hscDesugar
' :: ModLocation
-> TcGblEnv
-> Hsc ModGuts
410 hscDesugar
' mod_location tc_result
= do
413 {-# SCC "deSugar" #-}
414 deSugar hsc_env mod_location tc_result
416 -- always check -Werror after desugaring, this is the last opportunity for
417 -- warnings to arise before the backend.
421 -- | Make a 'ModIface' from the results of typechecking. Used when
422 -- not optimising, and the interface doesn't need to contain any
423 -- unfoldings or other cross-module optimisation info.
424 -- ToDo: the old interface is only needed to get the version numbers,
425 -- we should use fingerprint versions instead.
426 makeSimpleIface
:: HscEnv
-> Maybe ModIface
-> TcGblEnv
-> ModDetails
427 -> IO (ModIface
,Bool)
428 makeSimpleIface hsc_env maybe_old_iface tc_result details
=
429 runHsc hsc_env
$ ioMsgMaybe
$
430 mkIfaceTc hsc_env
(fmap mi_iface_hash maybe_old_iface
) details tc_result
432 -- | Make a 'ModDetails' from the results of typechecking. Used when
433 -- typechecking only, as opposed to full compilation.
434 makeSimpleDetails
:: HscEnv
-> TcGblEnv
-> IO ModDetails
435 makeSimpleDetails hsc_env tc_result
= mkBootModDetailsTc hsc_env tc_result
438 {- **********************************************************************
440 The main compiler pipeline
442 %********************************************************************* -}
445 --------------------------------
446 The compilation proper
447 --------------------------------
449 It's the task of the compilation proper to compile Haskell, hs-boot and core
450 files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
451 (the module is still parsed and type-checked. This feature is mostly used by
452 IDE's and the likes). Compilation can happen in either 'one-shot', 'batch',
453 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch'
454 mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
457 The modes are kept separate because of their different types and meanings:
459 * In 'one-shot' mode, we're only compiling a single file and can therefore
460 discard the new ModIface and ModDetails. This is also the reason it only
461 targets hard-code; compiling to byte-code or nothing doesn't make sense when
462 we discard the result.
464 * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
465 and ModDetails. 'Batch' mode doesn't target byte-code since that require us to
466 return the newly compiled byte-code.
468 * 'Nothing' mode has exactly the same type as 'batch' mode but they're still
469 kept separate. This is because compiling to nothing is fairly special: We
470 don't output any interface files, we don't run the simplifier and we don't
473 * 'Interactive' mode is similar to 'batch' mode except that we return the
474 compiled byte-code together with the ModIface and ModDetails.
476 Trying to compile a hs-boot file to byte-code will result in a run-time error.
477 This is the only thing that isn't caught by the type-system.
481 -- | Status of a compilation to hard-code or nothing.
485 (Maybe FilePath) -- Has stub files. This is a hack. We can't compile
486 -- C files here since it's done in DriverPipeline.
487 -- For now we just return True if we want the caller
488 -- to compile them for us.
491 -- This is a bit ugly. Since we use a typeclass below and would like to avoid
492 -- functional dependencies, we have to parameterise the typeclass over the
493 -- result type. Therefore we need to artificially distinguish some types. We do
494 -- this by adding type tags which will simply be ignored by the caller.
495 type HscStatus
= HscStatus
' ()
496 type InteractiveStatus
= HscStatus
' (Maybe (CompiledByteCode
, ModBreaks
))
497 -- INVARIANT: result is @Nothing@ <=> input was a boot file
499 type OneShotResult
= HscStatus
500 type BatchResult
= (HscStatus
, ModIface
, ModDetails
)
501 type NothingResult
= (HscStatus
, ModIface
, ModDetails
)
502 type InteractiveResult
= (InteractiveStatus
, ModIface
, ModDetails
)
504 -- ToDo: The old interface and module index are only using in 'batch' and
505 -- 'interactive' mode. They should be removed from 'oneshot' mode.
506 type Compiler result
= HscEnv
509 -> Maybe ModIface
-- Old interface, if available
510 -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs)
513 data HsCompiler a
= HsCompiler
{
514 -- | Called when no recompilation is necessary.
515 hscNoRecomp
:: ModIface
518 -- | Called to recompile the module.
519 hscRecompile
:: ModSummary
-> Maybe Fingerprint
522 hscBackend
:: TcGblEnv
-> ModSummary
-> Maybe Fingerprint
525 -- | Code generation for Boot modules.
526 hscGenBootOutput
:: TcGblEnv
-> ModSummary
-> Maybe Fingerprint
529 -- | Code generation for normal modules.
530 hscGenOutput
:: ModGuts
-> ModSummary
-> Maybe Fingerprint
534 genericHscCompile
:: HsCompiler a
535 -> (HscEnv
-> Maybe (Int,Int) -> RecompReason
-> ModSummary
-> IO ())
536 -> HscEnv
-> ModSummary
-> SourceModified
537 -> Maybe ModIface
-> Maybe (Int, Int)
539 genericHscCompile compiler hscMessage hsc_env
540 mod_summary source_modified
541 mb_old_iface0 mb_mod_index
543 (recomp_reqd
, mb_checked_iface
)
544 <- {-# SCC "checkOldIface" #-}
545 checkOldIface hsc_env mod_summary
546 source_modified mb_old_iface0
547 -- save the interface that comes back from checkOldIface.
548 -- In one-shot mode we don't have the old iface until this
549 -- point, when checkOldIface reads it from the disk.
550 let mb_old_hash
= fmap mi_iface_hash mb_checked_iface
553 hscMessage hsc_env mb_mod_index RecompNotRequired mod_summary
554 runHsc hsc_env
$ hscNoRecomp compiler iface
557 hscMessage hsc_env mb_mod_index reason mod_summary
558 runHsc hsc_env
$ hscRecompile compiler mod_summary mb_old_hash
560 stable
= case source_modified
of
561 SourceUnmodifiedAndStable
-> True
564 -- If the module used TH splices when it was last compiled,
565 -- then the recompilation check is not accurate enough (#481)
566 -- and we must ignore it. However, if the module is stable
567 -- (none of the modules it depends on, directly or indirectly,
568 -- changed), then we *can* skip recompilation. This is why
569 -- the SourceModified type contains SourceUnmodifiedAndStable,
570 -- and it's pretty important: otherwise ghc --make would
571 -- always recompile TH modules, even if nothing at all has
572 -- changed. Stability is just the same check that make is
573 -- doing for us in one-shot mode.
575 case mb_checked_iface
of
576 Just iface |
not recomp_reqd
->
577 if mi_used_th iface
&& not stable
578 then compile RecompForcedByTH
581 compile RecompRequired
583 hscCheckRecompBackend
:: HsCompiler a
-> TcGblEnv
-> Compiler a
584 hscCheckRecompBackend compiler tc_result hsc_env mod_summary
585 source_modified mb_old_iface _m_of_n
587 (recomp_reqd
, mb_checked_iface
)
588 <- {-# SCC "checkOldIface" #-}
589 checkOldIface hsc_env mod_summary
590 source_modified mb_old_iface
592 let mb_old_hash
= fmap mi_iface_hash mb_checked_iface
593 case mb_checked_iface
of
594 Just iface |
not recomp_reqd
597 iface
{ mi_globals
= Just
(tcg_rdr_env tc_result
) }
600 hscBackend compiler tc_result mod_summary mb_old_hash
602 genericHscRecompile
:: HsCompiler a
603 -> ModSummary
-> Maybe Fingerprint
605 genericHscRecompile compiler mod_summary mb_old_hash
606 | ExtCoreFile
<- ms_hsc_src mod_summary
=
607 panic
"GHC does not currently support reading External Core files"
609 tc_result
<- hscFileFrontEnd mod_summary
610 hscBackend compiler tc_result mod_summary mb_old_hash
612 genericHscBackend
:: HsCompiler a
613 -> TcGblEnv
-> ModSummary
-> Maybe Fingerprint
615 genericHscBackend compiler tc_result mod_summary mb_old_hash
616 | HsBootFile
<- ms_hsc_src mod_summary
=
617 hscGenBootOutput compiler tc_result mod_summary mb_old_hash
619 guts
<- hscDesugar
' (ms_location mod_summary
) tc_result
620 hscGenOutput compiler guts mod_summary mb_old_hash
622 compilerBackend
:: HsCompiler a
-> TcGblEnv
-> Compiler a
623 compilerBackend comp tcg hsc_env ms
' _ _mb_old_iface _
=
624 runHsc hsc_env
$ hscBackend comp tcg ms
' Nothing
626 --------------------------------------------------------------
628 --------------------------------------------------------------
630 hscOneShotCompiler
:: HsCompiler OneShotResult
631 hscOneShotCompiler
= HsCompiler
{
633 hscNoRecomp
= \_old_iface
-> do
635 liftIO
$ dumpIfaceStats hsc_env
638 , hscRecompile
= genericHscRecompile hscOneShotCompiler
640 , hscBackend
= \tc_result mod_summary mb_old_hash
-> do
641 dflags
<- getDynFlags
642 case hscTarget dflags
of
643 HscNothing
-> return (HscRecomp Nothing
())
644 _otherw
-> genericHscBackend hscOneShotCompiler
645 tc_result mod_summary mb_old_hash
647 , hscGenBootOutput
= \tc_result mod_summary mb_old_iface
-> do
648 (iface
, changed
, _
) <- hscSimpleIface tc_result mb_old_iface
649 hscWriteIface iface changed mod_summary
650 return (HscRecomp Nothing
())
652 , hscGenOutput
= \guts0 mod_summary mb_old_iface
-> do
653 guts
<- hscSimplify
' guts0
654 (iface
, changed
, _details
, cgguts
) <- hscNormalIface guts mb_old_iface
655 hscWriteIface iface changed mod_summary
656 hasStub
<- hscGenHardCode cgguts mod_summary
657 return (HscRecomp hasStub
())
660 -- Compile Haskell, boot and extCore in OneShot mode.
661 hscCompileOneShot
:: Compiler OneShotResult
662 hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n
664 -- One-shot mode needs a knot-tying mutable variable for interface
665 -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
666 type_env_var
<- newIORef emptyNameEnv
667 let mod = ms_mod mod_summary
668 hsc_env
' = hsc_env
{ hsc_type_env_var
= Just
(mod, type_env_var
) }
670 genericHscCompile hscOneShotCompiler
671 oneShotMsg hsc_env
' mod_summary src_changed
672 mb_old_iface mb_i_of_n
674 hscOneShotBackendOnly
:: TcGblEnv
-> Compiler OneShotResult
675 hscOneShotBackendOnly
= compilerBackend hscOneShotCompiler
677 --------------------------------------------------------------
679 hscBatchCompiler
:: HsCompiler BatchResult
680 hscBatchCompiler
= HsCompiler
{
682 hscNoRecomp
= \iface
-> do
683 details
<- genModDetails iface
684 return (HscNoRecomp
, iface
, details
)
686 , hscRecompile
= genericHscRecompile hscBatchCompiler
688 , hscBackend
= genericHscBackend hscBatchCompiler
690 , hscGenBootOutput
= \tc_result mod_summary mb_old_iface
-> do
691 (iface
, changed
, details
) <- hscSimpleIface tc_result mb_old_iface
692 hscWriteIface iface changed mod_summary
693 return (HscRecomp Nothing
(), iface
, details
)
695 , hscGenOutput
= \guts0 mod_summary mb_old_iface
-> do
696 guts
<- hscSimplify
' guts0
697 (iface
, changed
, details
, cgguts
) <- hscNormalIface guts mb_old_iface
698 hscWriteIface iface changed mod_summary
699 hasStub
<- hscGenHardCode cgguts mod_summary
700 return (HscRecomp hasStub
(), iface
, details
)
703 -- | Compile Haskell, boot and extCore in batch mode.
704 hscCompileBatch
:: Compiler
(HscStatus
, ModIface
, ModDetails
)
705 hscCompileBatch
= genericHscCompile hscBatchCompiler batchMsg
707 hscBatchBackendOnly
:: TcGblEnv
-> Compiler BatchResult
708 hscBatchBackendOnly
= hscCheckRecompBackend hscBatchCompiler
710 --------------------------------------------------------------
712 hscInteractiveCompiler
:: HsCompiler InteractiveResult
713 hscInteractiveCompiler
= HsCompiler
{
714 hscNoRecomp
= \iface
-> do
715 details
<- genModDetails iface
716 return (HscNoRecomp
, iface
, details
)
718 , hscRecompile
= genericHscRecompile hscInteractiveCompiler
720 , hscBackend
= genericHscBackend hscInteractiveCompiler
722 , hscGenBootOutput
= \tc_result _mod_summary mb_old_iface
-> do
723 (iface
, _changed
, details
) <- hscSimpleIface tc_result mb_old_iface
724 return (HscRecomp Nothing Nothing
, iface
, details
)
726 , hscGenOutput
= \guts0 mod_summary mb_old_iface
-> do
727 guts
<- hscSimplify
' guts0
728 (iface
, _changed
, details
, cgguts
) <- hscNormalIface guts mb_old_iface
729 hscInteractive
(iface
, details
, cgguts
) mod_summary
732 -- Compile Haskell, extCore to bytecode.
733 hscCompileInteractive
:: Compiler
(InteractiveStatus
, ModIface
, ModDetails
)
734 hscCompileInteractive
= genericHscCompile hscInteractiveCompiler batchMsg
736 hscInteractiveBackendOnly
:: TcGblEnv
-> Compiler InteractiveResult
737 hscInteractiveBackendOnly
= compilerBackend hscInteractiveCompiler
739 --------------------------------------------------------------
741 hscNothingCompiler
:: HsCompiler NothingResult
742 hscNothingCompiler
= HsCompiler
{
743 hscNoRecomp
= \iface
-> do
744 details
<- genModDetails iface
745 return (HscNoRecomp
, iface
, details
)
747 , hscRecompile
= genericHscRecompile hscNothingCompiler
749 , hscBackend
= \tc_result _mod_summary mb_old_iface
-> do
751 (iface
, _changed
, details
) <- hscSimpleIface tc_result mb_old_iface
752 return (HscRecomp Nothing
(), iface
, details
)
754 , hscGenBootOutput
= \_ _ _
->
755 panic
"hscCompileNothing: hscGenBootOutput should not be called"
757 , hscGenOutput
= \_ _ _
->
758 panic
"hscCompileNothing: hscGenOutput should not be called"
761 -- Type-check Haskell and .hs-boot only (no external core)
762 hscCompileNothing
:: Compiler
(HscStatus
, ModIface
, ModDetails
)
763 hscCompileNothing
= genericHscCompile hscNothingCompiler batchMsg
765 hscNothingBackendOnly
:: TcGblEnv
-> Compiler NothingResult
766 hscNothingBackendOnly
= compilerBackend hscNothingCompiler
768 --------------------------------------------------------------
770 --------------------------------------------------------------
772 genModDetails
:: ModIface
-> Hsc ModDetails
773 genModDetails old_iface
776 new_details
<- {-# SCC "tcRnIface" #-}
777 liftIO
$ initIfaceCheck hsc_env
(typecheckIface old_iface
)
778 liftIO
$ dumpIfaceStats hsc_env
781 --------------------------------------------------------------
782 -- Progress displayers.
783 --------------------------------------------------------------
785 data RecompReason
= RecompNotRequired | RecompRequired | RecompForcedByTH
788 oneShotMsg
:: HscEnv
-> Maybe (Int,Int) -> RecompReason
-> ModSummary
-> IO ()
789 oneShotMsg hsc_env _mb_mod_index recomp _mod_summary
=
792 compilationProgressMsg
(hsc_dflags hsc_env
) $
793 "compilation IS NOT required"
797 batchMsg
:: HscEnv
-> Maybe (Int,Int) -> RecompReason
-> ModSummary
-> IO ()
798 batchMsg hsc_env mb_mod_index recomp mod_summary
=
800 RecompRequired
-> showMsg
"Compiling "
802 | verbosity
(hsc_dflags hsc_env
) >= 2 -> showMsg
"Skipping "
803 |
otherwise -> return ()
804 RecompForcedByTH
-> showMsg
"Compiling [TH] "
807 compilationProgressMsg
(hsc_dflags hsc_env
) $
808 (showModuleIndex mb_mod_index
++
809 msg
++ showModMsg
(hscTarget
(hsc_dflags hsc_env
))
810 (recomp
== RecompRequired
) mod_summary
)
812 --------------------------------------------------------------
814 --------------------------------------------------------------
816 hscFileFrontEnd
:: ModSummary
-> Hsc TcGblEnv
817 hscFileFrontEnd mod_summary
= do
818 hpm
<- hscParse
' mod_summary
820 dflags
<- getDynFlags
822 {-# SCC "Typecheck-Rename" #-}
824 tcRnModule hsc_env
(ms_hsc_src mod_summary
) False hpm
825 tcSafeOK
<- liftIO
$ readIORef
(tcg_safeInfer tcg_env
)
827 -- end of the Safe Haskell line, how to respond to user?
828 if not (safeHaskellOn dflags
) ||
(safeInferOn dflags
&& not tcSafeOK
)
830 -- if safe haskell off or safe infer failed, wipe trust
831 then wipeTrust tcg_env emptyBag
833 -- module safe, throw warning if needed
835 tcg_env
' <- hscCheckSafeImports tcg_env
836 safe
<- liftIO
$ hscGetSafeInf hsc_env
837 when (safe
&& wopt Opt_WarnSafe dflags
)
838 (logWarnings
$ unitBag
$
839 mkPlainWarnMsg
(warnSafeOnLoc dflags
) $ errSafe tcg_env
')
842 pprMod t
= ppr
$ moduleName
$ tcg_mod t
843 errSafe t
= text
"Warning:" <+> quotes
(pprMod t
)
844 <+> text
"has been infered as safe!"
846 --------------------------------------------------------------
848 --------------------------------------------------------------
850 -- Note [Safe Haskell Trust Check]
851 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
852 -- Safe Haskell checks that an import is trusted according to the following
853 -- rules for an import of module M that resides in Package P:
855 -- * If M is recorded as Safe and all its trust dependencies are OK
856 -- then M is considered safe.
857 -- * If M is recorded as Trustworthy and P is considered trusted and
858 -- all M's trust dependencies are OK then M is considered safe.
860 -- By trust dependencies we mean that the check is transitive. So if
861 -- a module M that is Safe relies on a module N that is trustworthy,
862 -- importing module M will first check (according to the second case)
863 -- that N is trusted before checking M is trusted.
865 -- This is a minimal description, so please refer to the user guide
866 -- for more details. The user guide is also considered the authoritative
867 -- source in this matter, not the comments or code.
870 -- Note [Safe Haskell Inference]
871 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
872 -- Safe Haskell does Safe inference on modules that don't have any specific
873 -- safe haskell mode flag. The basic aproach to this is:
874 -- * When deciding if we need to do a Safe language check, treat
875 -- an unmarked module as having -XSafe mode specified.
876 -- * For checks, don't throw errors but return them to the caller.
877 -- * Caller checks if there are errors:
878 -- * For modules explicitly marked -XSafe, we throw the errors.
879 -- * For unmarked modules (inference mode), we drop the errors
880 -- and mark the module as being Unsafe.
883 -- | Check that the safe imports of the module being compiled are valid.
884 -- If not we either issue a compilation error if the module is explicitly
885 -- using Safe Haskell, or mark the module as unsafe if we're in safe
887 hscCheckSafeImports
:: TcGblEnv
-> Hsc TcGblEnv
888 hscCheckSafeImports tcg_env
= do
890 dflags
<- getDynFlags
891 tcg_env
' <- checkSafeImports dflags hsc_env tcg_env
892 case safeLanguageOn dflags
of
894 -- we nuke user written RULES in -XSafe
895 logWarnings
$ warns
(tcg_rules tcg_env
')
896 return tcg_env
' { tcg_rules
= [] }
898 -- user defined RULES, so not safe or already unsafe
899 | safeInferOn dflags
&& not (null $ tcg_rules tcg_env
') ||
900 safeHaskell dflags
== Sf_None
901 -> wipeTrust tcg_env
' $ warns
(tcg_rules tcg_env
')
903 -- trustworthy OR safe infered with no RULES
908 warns rules
= listToBag
$ map warnRules rules
909 warnRules
(L loc
(HsRule n _ _ _ _ _ _
)) =
911 text
"Rule \"" <> ftext n
<> text
"\" ignored" $+$
912 text
"User defined rules are disabled under Safe Haskell"
914 -- | Validate that safe imported modules are actually safe.
915 -- For modules in the HomePackage (the package the module we
916 -- are compiling in resides) this just involves checking its
917 -- trust type is 'Safe' or 'Trustworthy'. For modules that
918 -- reside in another package we also must check that the
919 -- external pacakge is trusted. See the Note [Safe Haskell
920 -- Trust Check] above for more information.
922 -- The code for this is quite tricky as the whole algorithm
923 -- is done in a few distinct phases in different parts of the
924 -- code base. See RnNames.rnImportDecl for where package trust
925 -- dependencies for a module are collected and unioned.
926 -- Specifically see the Note [RnNames . Tracking Trust Transitively]
927 -- and the Note [RnNames . Trust Own Package].
928 checkSafeImports
:: DynFlags
-> HscEnv
-> TcGblEnv
-> Hsc TcGblEnv
929 checkSafeImports dflags hsc_env tcg_env
931 -- We want to use the warning state specifically for detecting if safe
932 -- inference has failed, so store and clear any existing warnings.
933 oldErrs
<- getWarnings
936 imps
<- mapM condense imports
'
937 pkgs
<- mapM checkSafe imps
939 -- grab any safe haskell specific errors and restore old warnings
944 -- See the Note [ Safe Haskell Inference]
945 case (not $ isEmptyBag errs
) of
949 -- did we fail safe inference or fail -XSafe?
950 case safeInferOn dflags
of
951 True -> wipeTrust tcg_env errs
952 False -> liftIO
. throwIO
. mkSrcErr
$ errs
956 when (packageTrustOn dflags
) $ checkPkgTrust pkg_reqs
957 -- add in trusted package requirements for this module
958 let new_trust
= emptyImportAvails
{ imp_trust_pkgs
= catMaybes pkgs
}
959 return tcg_env
{ tcg_imports
= imp_info `plusImportAvails` new_trust
}
962 imp_info
= tcg_imports tcg_env
-- ImportAvails
963 imports
= imp_mods imp_info
-- ImportedMods
964 imports
' = moduleEnvToList imports
-- (Module, [ImportedModsVal])
965 pkg_reqs
= imp_trust_pkgs imp_info
-- [PackageId]
967 condense
:: (Module
, [ImportedModsVal
]) -> Hsc
(Module
, SrcSpan
, IsSafeImport
)
968 condense
(_
, []) = panic
"HscMain.condense: Pattern match failure!"
969 condense
(m
, x
:xs
) = do (_
,_
,l
,s
) <- foldlM cond
' x xs
970 -- we turn all imports into safe ones when
971 -- inference mode is on.
972 let s
' = if safeInferOn dflags
then True else s
975 -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
976 cond
' :: ImportedModsVal
-> ImportedModsVal
-> Hsc ImportedModsVal
977 cond
' v1
@(m1
,_
,l1
,s1
) (_
,_
,_
,s2
)
979 = throwErrors
$ unitBag
$ mkPlainErrMsg l1
980 (text
"Module" <+> ppr m1
<+>
981 (text
$ "is imported both as a safe and unsafe import!"))
985 lookup' :: Module
-> Hsc
(Maybe ModIface
)
987 hsc_eps
<- liftIO
$ hscEPS hsc_env
988 let pkgIfaceT
= eps_PIT hsc_eps
989 homePkgT
= hsc_HPT hsc_env
990 iface
= lookupIfaceByModule dflags homePkgT pkgIfaceT m
993 isHomePkg
:: Module
-> Bool
995 | thisPackage dflags
== modulePackageId m
= True
998 -- | Check the package a module resides in is trusted.
999 -- Safe compiled modules are trusted without requiring
1000 -- that their package is trusted. For trustworthy modules,
1001 -- modules in the home package are trusted but otherwise
1002 -- we check the package trust flag.
1003 packageTrusted
:: SafeHaskellMode
-> Bool -> Module
-> Bool
1004 packageTrusted _ _ _
1005 |
not (packageTrustOn dflags
) = True
1006 packageTrusted Sf_Safe
False _
= True
1007 packageTrusted Sf_SafeInfered
False _
= True
1008 packageTrusted _ _ m
1009 | isHomePkg m
= True
1010 |
otherwise = trusted
$ getPackageDetails
(pkgState dflags
)
1013 -- Is a module trusted? Return Nothing if True, or a String
1014 -- if it isn't, containing the reason it isn't. Also return
1015 -- if the module trustworthy (true) or safe (false) so we know
1016 -- if we should check if the package itself is trusted in the
1018 isModSafe
:: Module
-> SrcSpan
-> Hsc
(Bool)
1022 -- can't load iface to check trust!
1023 Nothing
-> throwErrors
$ unitBag
$ mkPlainErrMsg l
1024 $ text
"Can't load the interface file for" <+> ppr m
<>
1025 text
", to check that it can be safely imported"
1027 -- got iface, check trust
1029 let trust
= getSafeMode
$ mi_trust iface
'
1030 trust_own_pkg
= mi_trust_pkg iface
'
1031 -- check module is trusted
1032 safeM
= trust `
elem`
[Sf_SafeInfered
, Sf_Safe
, Sf_Trustworthy
]
1033 -- check package is trusted
1034 safeP
= packageTrusted trust trust_own_pkg m
1035 case (safeM
, safeP
) of
1036 -- General errors we throw but Safe errors we log
1037 (True, True ) -> return $ trust
== Sf_Trustworthy
1038 (True, False) -> liftIO
. throwIO
$ pkgTrustErr
1039 (False, _
) -> logWarnings modTrustErr
>> return (trust
== Sf_Trustworthy
)
1042 pkgTrustErr
= mkSrcErr
$ unitBag
$ mkPlainErrMsg l
$ ppr m
1043 <+> text
"can't be safely imported!" <+> text
"The package ("
1044 <> ppr
(modulePackageId m
)
1045 <> text
") the module resides in isn't trusted."
1046 modTrustErr
= unitBag
$ mkPlainErrMsg l
$ ppr m
1047 <+> text
"can't be safely imported!"
1048 <+> text
"The module itself isn't safe."
1050 -- Here we check the transitive package trust requirements are OK still.
1051 checkPkgTrust
:: [PackageId
] -> Hsc
()
1052 checkPkgTrust pkgs
=
1055 _
-> (liftIO
. throwIO
. mkSrcErr
. listToBag
) errors
1057 errors
= catMaybes $ map go pkgs
1059 | trusted
$ getPackageDetails
(pkgState dflags
) pkg
1062 = Just
$ mkPlainErrMsg noSrcSpan
1063 $ text
"The package (" <> ppr pkg
<> text
") is required"
1064 <> text
" to be trusted but it isn't!"
1066 checkSafe
:: (Module
, SrcSpan
, IsSafeImport
) -> Hsc
(Maybe PackageId
)
1067 checkSafe
(_
, _
, False) = return Nothing
1068 checkSafe
(m
, l
, True ) = do
1071 where pkg
False = Nothing
1072 pkg
True | isHomePkg m
= Nothing
1073 |
otherwise = Just
(modulePackageId m
)
1075 -- | Set module to unsafe and wipe trust information.
1077 -- Make sure to call this method to set a module to infered unsafe,
1078 -- it should be a central and single failure method.
1079 wipeTrust
:: TcGblEnv
-> WarningMessages
-> Hsc TcGblEnv
1080 wipeTrust tcg_env whyUnsafe
= do
1082 dflags
<- getDynFlags
1084 when (wopt Opt_WarnUnsafe dflags
)
1085 (logWarnings
$ unitBag
$
1086 mkPlainWarnMsg
(warnUnsafeOnLoc dflags
) whyUnsafe
')
1088 liftIO
$ hscSetSafeInf env
False
1089 return $ tcg_env
{ tcg_imports
= wiped_trust
}
1092 wiped_trust
= (tcg_imports tcg_env
) { imp_trust_pkgs
= [] }
1093 pprMod
= ppr
$ moduleName
$ tcg_mod tcg_env
1094 whyUnsafe
' = vcat
[ text
"Warning:" <+> quotes pprMod
1095 <+> text
"has been infered as unsafe!"
1097 , nest
4 (vcat
$ pprErrMsgBag whyUnsafe
) ]
1100 --------------------------------------------------------------
1102 --------------------------------------------------------------
1104 hscSimplify
:: HscEnv
-> ModGuts
-> IO ModGuts
1105 hscSimplify hsc_env modguts
= runHsc hsc_env
$ hscSimplify
' modguts
1107 hscSimplify
' :: ModGuts
-> Hsc ModGuts
1108 hscSimplify
' ds_result
= do
1109 hsc_env
<- getHscEnv
1110 {-# SCC "Core2Core" #-}
1111 liftIO
$ core2core hsc_env ds_result
1113 --------------------------------------------------------------
1114 -- Interface generators
1115 --------------------------------------------------------------
1117 hscSimpleIface
:: TcGblEnv
1118 -> Maybe Fingerprint
1119 -> Hsc
(ModIface
, Bool, ModDetails
)
1120 hscSimpleIface tc_result mb_old_iface
= do
1121 hsc_env
<- getHscEnv
1122 details
<- liftIO
$ mkBootModDetailsTc hsc_env tc_result
1123 (new_iface
, no_change
)
1124 <- {-# SCC "MkFinalIface" #-}
1126 mkIfaceTc hsc_env mb_old_iface details tc_result
1127 -- And the answer is ...
1128 liftIO
$ dumpIfaceStats hsc_env
1129 return (new_iface
, no_change
, details
)
1131 hscNormalIface
:: ModGuts
1132 -> Maybe Fingerprint
1133 -> Hsc
(ModIface
, Bool, ModDetails
, CgGuts
)
1134 hscNormalIface simpl_result mb_old_iface
= do
1135 hsc_env
<- getHscEnv
1136 (cg_guts
, details
) <- {-# SCC "CoreTidy" #-}
1137 liftIO
$ tidyProgram hsc_env simpl_result
1139 -- BUILD THE NEW ModIface and ModDetails
1140 -- and emit external core if necessary
1141 -- This has to happen *after* code gen so that the back-end
1142 -- info has been set. Not yet clear if it matters waiting
1143 -- until after code output
1144 (new_iface
, no_change
)
1145 <- {-# SCC "MkFinalIface" #-}
1147 mkIface hsc_env mb_old_iface details simpl_result
1149 -- Emit external core
1150 -- This should definitely be here and not after CorePrep,
1151 -- because CorePrep produces unqualified constructor wrapper declarations,
1152 -- so its output isn't valid External Core (without some preprocessing).
1153 liftIO
$ emitExternalCore
(hsc_dflags hsc_env
) cg_guts
1154 liftIO
$ dumpIfaceStats hsc_env
1156 -- Return the prepared code.
1157 return (new_iface
, no_change
, details
, cg_guts
)
1159 --------------------------------------------------------------
1160 -- BackEnd combinators
1161 --------------------------------------------------------------
1163 hscWriteIface
:: ModIface
-> Bool -> ModSummary
-> Hsc
()
1164 hscWriteIface iface no_change mod_summary
= do
1165 dflags
<- getDynFlags
1167 {-# SCC "writeIface" #-}
1168 liftIO
$ writeIfaceFile dflags
(ms_location mod_summary
) iface
1170 -- | Compile to hard-code.
1171 hscGenHardCode
:: CgGuts
-> ModSummary
1172 -> Hsc
(Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
1173 hscGenHardCode cgguts mod_summary
= do
1174 hsc_env
<- getHscEnv
1176 let CgGuts
{ -- This is the last use of the ModGuts in a compilation.
1177 -- From now on, we just use the bits we need.
1178 cg_module
= this_mod
,
1179 cg_binds
= core_binds
,
1181 cg_foreign
= foreign_stubs0
,
1182 cg_dep_pkgs
= dependencies
,
1183 cg_hpc_info
= hpc_info
} = cgguts
1184 dflags
= hsc_dflags hsc_env
1185 platform
= targetPlatform dflags
1186 location
= ms_location mod_summary
1187 data_tycons
= filter isDataTyCon tycons
1188 -- cg_tycons includes newtypes, for the benefit of External Core,
1189 -- but we don't generate any code for newtypes
1192 -- PREPARE FOR CODE GENERATION
1193 -- Do saturation and convert to A-normal form
1194 prepd_binds
<- {-# SCC "CorePrep" #-}
1195 corePrepPgm dflags core_binds data_tycons
;
1196 ----------------- Convert to STG ------------------
1197 (stg_binds
, cost_centre_info
)
1198 <- {-# SCC "CoreToStg" #-}
1199 myCoreToStg dflags this_mod prepd_binds
1201 let prof_init
= profilingInitCode platform this_mod cost_centre_info
1202 foreign_stubs
= foreign_stubs0 `appendStubC` prof_init
1204 ------------------ Code generation ------------------
1206 cmms
<- if dopt Opt_TryNewCodeGen dflags
1207 then {-# SCC "NewCodeGen" #-}
1208 tryNewCodeGen hsc_env this_mod data_tycons
1211 else {-# SCC "CodeGen" #-}
1212 codeGen dflags this_mod data_tycons
1216 ------------------ Code output -----------------------
1217 rawcmms
<- {-# SCC "cmmToRawCmm" #-}
1218 cmmToRawCmm platform cmms
1219 dumpIfSet_dyn dflags Opt_D_dump_raw_cmm
"Raw Cmm" (pprPlatform platform rawcmms
)
1220 (_stub_h_exists
, stub_c_exists
)
1221 <- {-# SCC "codeOutput" #-}
1222 codeOutput dflags this_mod location foreign_stubs
1223 dependencies rawcmms
1224 return stub_c_exists
1226 hscInteractive
:: (ModIface
, ModDetails
, CgGuts
)
1228 -> Hsc
(InteractiveStatus
, ModIface
, ModDetails
)
1230 hscInteractive
(iface
, details
, cgguts
) mod_summary
= do
1231 dflags
<- getDynFlags
1232 let CgGuts
{ -- This is the last use of the ModGuts in a compilation.
1233 -- From now on, we just use the bits we need.
1234 cg_module
= this_mod
,
1235 cg_binds
= core_binds
,
1237 cg_foreign
= foreign_stubs
,
1238 cg_modBreaks
= mod_breaks
} = cgguts
1240 location
= ms_location mod_summary
1241 data_tycons
= filter isDataTyCon tycons
1242 -- cg_tycons includes newtypes, for the benefit of External Core,
1243 -- but we don't generate any code for newtypes
1246 -- PREPARE FOR CODE GENERATION
1247 -- Do saturation and convert to A-normal form
1248 prepd_binds
<- {-# SCC "CorePrep" #-}
1249 liftIO
$ corePrepPgm dflags core_binds data_tycons
;
1250 ----------------- Generate byte code ------------------
1251 comp_bc
<- liftIO
$ byteCodeGen dflags this_mod prepd_binds
1252 data_tycons mod_breaks
1253 ------------------ Create f-x-dynamic C-side stuff ---
1254 (_istub_h_exists
, istub_c_exists
)
1255 <- liftIO
$ outputForeignStubs dflags this_mod
1256 location foreign_stubs
1257 return (HscRecomp istub_c_exists
(Just
(comp_bc
, mod_breaks
))
1260 hscInteractive _ _
= panic
"GHC not compiled with interpreter"
1263 ------------------------------
1265 hscCompileCmmFile
:: HscEnv
-> FilePath -> IO ()
1266 hscCompileCmmFile hsc_env filename
= runHsc hsc_env
$ do
1267 let dflags
= hsc_dflags hsc_env
1268 cmm
<- ioMsgMaybe
$ parseCmmFile dflags filename
1270 rawCmms
<- cmmToRawCmm
(targetPlatform dflags
) [cmm
]
1271 _
<- codeOutput dflags no_mod no_loc NoStubs
[] rawCmms
1274 no_mod
= panic
"hscCmmFile: no_mod"
1275 no_loc
= ModLocation
{ ml_hs_file
= Just filename
,
1276 ml_hi_file
= panic
"hscCmmFile: no hi file",
1277 ml_obj_file
= panic
"hscCmmFile: no obj file" }
1279 -------------------- Stuff for new code gen ---------------------
1281 tryNewCodeGen
:: HscEnv
-> Module
-> [TyCon
]
1283 -> [(StgBinding
,[(Id
,[Id
])])]
1285 -> IO [Old
.CmmGroup
]
1286 tryNewCodeGen hsc_env this_mod data_tycons
1287 cost_centre_info stg_binds hpc_info
= do
1288 let dflags
= hsc_dflags hsc_env
1289 platform
= targetPlatform dflags
1290 prog
<- StgCmm
.codeGen dflags this_mod data_tycons
1291 cost_centre_info stg_binds hpc_info
1292 dumpIfSet_dyn dflags Opt_D_dump_cmmz
"Cmm produced by new codegen"
1293 (pprCmms platform prog
)
1295 -- We are building a single SRT for the entire module, so
1296 -- we must thread it through all the procedures as we cps-convert them.
1297 us
<- mkSplitUniqSupply
'S
'
1298 let initTopSRT
= initUs_ us emptySRT
1299 (topSRT
, prog
) <- foldM (cmmPipeline hsc_env
) (initTopSRT
, []) prog
1301 let prog
' = map cmmOfZgraph
(srtToData topSRT
: prog
)
1302 dumpIfSet_dyn dflags Opt_D_dump_cmmz
"Output Cmm" (pprPlatform platform prog
')
1305 myCoreToStg
:: DynFlags
-> Module
-> CoreProgram
1306 -> IO ( [(StgBinding
,[(Id
,[Id
])])] -- output program
1307 , CollectedCCs
) -- cost centre info (declared and used)
1308 myCoreToStg dflags this_mod prepd_binds
= do
1310 <- {-# SCC "Core2Stg" #-}
1311 coreToStg dflags prepd_binds
1313 (stg_binds2
, cost_centre_info
)
1314 <- {-# SCC "Stg2Stg" #-}
1315 stg2stg dflags this_mod stg_binds
1317 return (stg_binds2
, cost_centre_info
)
1320 {- **********************************************************************
1322 \subsection{Compiling a do-statement}
1324 %********************************************************************* -}
1327 When the UnlinkedBCOExpr is linked you get an HValue of type
1329 When you run it you get a list of HValues that should be
1330 the same length as the list of names; add them to the ClosureEnv.
1332 A naked expression returns a singleton Name [it].
1334 What you type The IO [HValue] that hscStmt returns
1335 ------------- ------------------------------------
1336 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
1339 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
1342 expr (of IO type) ==> expr >>= \ v -> return [v]
1343 [NB: result not printed] bindings: [it]
1346 expr (of non-IO type,
1347 result showable) ==> let v = expr in print v >> return [v]
1350 expr (of non-IO type,
1351 result not showable) ==> error
1355 -- | Compile a stmt all the way to an HValue, but don't run it
1357 -> String -- ^ The statement
1358 -> IO (Maybe ([Id
], HValue
)) -- ^ 'Nothing' <==> empty statement
1359 -- (or comment only), but no parse error
1360 hscStmt hsc_env stmt
= hscStmtWithLocation hsc_env stmt
"<interactive>" 1
1362 -- | Compile a stmt all the way to an HValue, but don't run it
1363 hscStmtWithLocation
:: HscEnv
1364 -> String -- ^ The statement
1365 -> String -- ^ The source
1366 -> Int -- ^ Starting line
1367 -> IO (Maybe ([Id
], HValue
)) -- ^ 'Nothing' <==> empty statement
1368 -- (or comment only), but no parse error
1369 hscStmtWithLocation hsc_env stmt source linenumber
= runHsc hsc_env
$ do
1370 maybe_stmt
<- hscParseStmtWithLocation source linenumber stmt
1372 Nothing
-> return Nothing
1375 Just parsed_stmt
-> do
1376 -- Rename and typecheck it
1377 let icontext
= hsc_IC hsc_env
1378 (ids
, tc_expr
) <- ioMsgMaybe
$
1379 tcRnStmt hsc_env icontext parsed_stmt
1381 let rdr_env
= ic_rn_gbl_env icontext
1382 type_env
= mkTypeEnvWithImplicits
(ic_tythings icontext
)
1383 ds_expr
<- ioMsgMaybe
$
1384 deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr
1387 -- Then code-gen, and link it
1388 let src_span
= srcLocSpan interactiveSrcLoc
1389 hsc_env
<- getHscEnv
1390 hval
<- liftIO
$ hscCompileCoreExpr hsc_env src_span ds_expr
1392 return $ Just
(ids
, hval
)
1394 -- | Compile a decls
1396 -> String -- ^ The statement
1397 -> IO ([TyThing
], InteractiveContext
)
1398 hscDecls hsc_env str
= hscDeclsWithLocation hsc_env str
"<interactive>" 1
1400 -- | Compile a decls
1401 hscDeclsWithLocation
:: HscEnv
1402 -> String -- ^ The statement
1403 -> String -- ^ The source
1404 -> Int -- ^ Starting line
1405 -> IO ([TyThing
], InteractiveContext
)
1406 hscDeclsWithLocation hsc_env str source linenumber
= runHsc hsc_env
$ do
1407 L _
(HsModule
{ hsmodDecls
= decls
}) <-
1408 hscParseThingWithLocation source linenumber parseModule str
1410 {- Rename and typecheck it -}
1411 let icontext
= hsc_IC hsc_env
1412 tc_gblenv
<- ioMsgMaybe
$ tcRnDeclsi hsc_env icontext decls
1414 {- Grab the new instances -}
1415 -- We grab the whole environment because of the overlapping that may have
1416 -- been done. See the notes at the definition of InteractiveContext
1417 -- (ic_instances) for more details.
1418 let finsts
= famInstEnvElts
$ tcg_fam_inst_env tc_gblenv
1419 insts
= instEnvElts
$ tcg_inst_env tc_gblenv
1422 -- We use a basically null location for iNTERACTIVE
1423 let iNTERACTIVELoc
= ModLocation
{ ml_hs_file
= Nothing
,
1424 ml_hi_file
= undefined,
1425 ml_obj_file
= undefined}
1426 ds_result
<- hscDesugar
' iNTERACTIVELoc tc_gblenv
1429 simpl_mg
<- liftIO
$ hscSimplify hsc_env ds_result
1432 (tidy_cg
, _mod_details
) <- liftIO
$ tidyProgram hsc_env simpl_mg
1434 let dflags
= hsc_dflags hsc_env
1435 !CgGuts
{ cg_module
= this_mod
,
1436 cg_binds
= core_binds
,
1438 cg_modBreaks
= mod_breaks
} = tidy_cg
1439 data_tycons
= filter isDataTyCon tycons
1441 {- Prepare For Code Generation -}
1442 -- Do saturation and convert to A-normal form
1443 prepd_binds
<- {-# SCC "CorePrep" #-}
1444 liftIO
$ corePrepPgm dflags core_binds data_tycons
1446 {- Generate byte code -}
1447 cbc
<- liftIO
$ byteCodeGen dflags this_mod
1448 prepd_binds data_tycons mod_breaks
1450 let src_span
= srcLocSpan interactiveSrcLoc
1451 hsc_env
<- getHscEnv
1452 liftIO
$ linkDecls hsc_env src_span cbc
1454 let tcs
= filter (not . isImplicitTyCon
) $ (mg_tcs simpl_mg
)
1456 ext_vars
= filter (isExternalName
. idName
) $
1457 bindersOfBinds core_binds
1459 (sys_vars
, user_vars
) = partition is_sys_var ext_vars
1460 is_sys_var
id = isDFunId
id
1461 || isRecordSelector
id
1462 ||
isJust (isClassOpId_maybe
id)
1463 -- we only need to keep around the external bindings
1464 -- (as decided by TidyPgm), since those are the only ones
1465 -- that might be referenced elsewhere.
1467 tythings
= map AnId user_vars
1470 let ictxt1
= extendInteractiveContext icontext tythings
1471 ictxt
= ictxt1
{ ic_sys_vars
= sys_vars
++ ic_sys_vars ictxt1
,
1472 ic_instances
= (insts
, finsts
) }
1474 return (tythings
, ictxt
)
1476 hscImport
:: HscEnv
-> String -> IO (ImportDecl RdrName
)
1477 hscImport hsc_env str
= runHsc hsc_env
$ do
1478 (L _
(HsModule
{hsmodImports
=is
})) <-
1479 hscParseThing parseModule str
1481 [i
] -> return (unLoc i
)
1482 _
-> liftIO
$ throwOneError
$
1483 mkPlainErrMsg noSrcSpan
$
1484 ptext
(sLit
"parse error in import declaration")
1486 -- | Typecheck an expression (but don't run it)
1488 -> String -- ^ The expression
1490 hscTcExpr hsc_env expr
= runHsc hsc_env
$ do
1491 maybe_stmt
<- hscParseStmt expr
1493 Just
(L _
(ExprStmt expr _ _ _
)) ->
1494 ioMsgMaybe
$ tcRnExpr hsc_env
(hsc_IC hsc_env
) expr
1496 throwErrors
$ unitBag
$ mkPlainErrMsg noSrcSpan
1497 (text
"not an expression:" <+> quotes
(text expr
))
1499 -- | Find the kind of a type
1502 -> Bool -- ^ Normalise the type
1503 -> String -- ^ The type as a string
1504 -> IO (Type
, Kind
) -- ^ Resulting type (possibly normalised) and kind
1505 hscKcType hsc_env normalise str
= runHsc hsc_env
$ do
1506 ty
<- hscParseType str
1507 ioMsgMaybe
$ tcRnType hsc_env
(hsc_IC hsc_env
) normalise ty
1509 hscParseStmt
:: String -> Hsc
(Maybe (LStmt RdrName
))
1510 hscParseStmt
= hscParseThing parseStmt
1512 hscParseStmtWithLocation
:: String -> Int -> String
1513 -> Hsc
(Maybe (LStmt RdrName
))
1514 hscParseStmtWithLocation source linenumber stmt
=
1515 hscParseThingWithLocation source linenumber parseStmt stmt
1517 hscParseType
:: String -> Hsc
(LHsType RdrName
)
1518 hscParseType
= hscParseThing parseType
1521 hscParseIdentifier
:: HscEnv
-> String -> IO (Located RdrName
)
1522 hscParseIdentifier hsc_env str
=
1523 runHsc hsc_env
$ hscParseThing parseIdentifier str
1525 hscParseThing
:: (Outputable thing
) => Lexer
.P thing
-> String -> Hsc thing
1526 hscParseThing
= hscParseThingWithLocation
"<interactive>" 1
1528 hscParseThingWithLocation
:: (Outputable thing
) => String -> Int
1529 -> Lexer
.P thing
-> String -> Hsc thing
1530 hscParseThingWithLocation source linenumber parser str
1531 = {-# SCC "Parser" #-} do
1532 dflags
<- getDynFlags
1533 liftIO
$ showPass dflags
"Parser"
1535 let buf
= stringToStringBuffer str
1536 loc
= mkRealSrcLoc
(fsLit source
) linenumber
1
1538 case unP parser
(mkPState dflags buf loc
) of
1539 PFailed span err
-> do
1540 let msg
= mkPlainErrMsg span err
1541 throwErrors
$ unitBag msg
1544 logWarningsReportErrors
(getMessages pst
)
1545 liftIO
$ dumpIfSet_dyn dflags Opt_D_dump_parsed
"Parser" (ppr thing
)
1548 hscCompileCore
:: HscEnv
-> Bool -> ModSummary
-> CoreProgram
-> IO ()
1549 hscCompileCore hsc_env simplify mod_summary binds
= runHsc hsc_env
$ do
1550 guts
<- maybe_simplify
(mkModGuts
(ms_mod mod_summary
) binds
)
1551 (iface
, changed
, _details
, cgguts
) <- hscNormalIface guts Nothing
1552 hscWriteIface iface changed mod_summary
1553 _
<- hscGenHardCode cgguts mod_summary
1557 maybe_simplify mod_guts | simplify
= hscSimplify
' mod_guts
1558 |
otherwise = return mod_guts
1560 -- Makes a "vanilla" ModGuts.
1561 mkModGuts
:: Module
-> CoreProgram
-> ModGuts
1562 mkModGuts
mod binds
=
1567 mg_deps
= noDependencies
,
1568 mg_dir_imps
= emptyModuleEnv
,
1569 mg_used_names
= emptyNameSet
,
1571 mg_rdr_env
= emptyGlobalRdrEnv
,
1572 mg_fix_env
= emptyFixityEnv
,
1579 mg_foreign
= NoStubs
,
1580 mg_warns
= NoWarnings
,
1582 mg_hpc_info
= emptyHpcInfo
False,
1583 mg_modBreaks
= emptyModBreaks
,
1584 mg_vect_info
= noVectInfo
,
1585 mg_inst_env
= emptyInstEnv
,
1586 mg_fam_inst_env
= emptyFamInstEnv
,
1587 mg_trust_pkg
= False,
1588 mg_dependent_files
= []
1592 {- **********************************************************************
1594 Desugar, simplify, convert to bytecode, and link an expression
1596 %********************************************************************* -}
1599 hscCompileCoreExpr
:: HscEnv
-> SrcSpan
-> CoreExpr
-> IO HValue
1600 hscCompileCoreExpr hsc_env srcspan ds_expr
1602 = throwIO
(InstallationError
"You can't call hscCompileCoreExpr in a profiled compiler")
1603 -- Otherwise you get a seg-fault when you run it
1606 let dflags
= hsc_dflags hsc_env
1607 let lint_on
= dopt Opt_DoCoreLinting dflags
1610 simpl_expr
<- simplifyExpr dflags ds_expr
1612 {- Tidy it (temporary, until coreSat does cloning) -}
1613 let tidy_expr
= tidyExpr emptyTidyEnv simpl_expr
1615 {- Prepare for codegen -}
1616 prepd_expr
<- corePrepExpr dflags tidy_expr
1618 {- Lint if necessary -}
1619 -- ToDo: improve SrcLoc
1621 let ictxt
= hsc_IC hsc_env
1622 te
= mkTypeEnvWithImplicits
(ic_tythings ictxt
++ map AnId
(ic_sys_vars ictxt
))
1623 tyvars
= varSetElems
$ tyThingsTyVars
$ typeEnvElts
$ te
1624 vars
= typeEnvIds te
1625 in case lintUnfolding noSrcLoc
(tyvars
++ vars
) prepd_expr
of
1626 Just err
-> pprPanic
"hscCompileCoreExpr" err
1627 Nothing
-> return ()
1629 {- Convert to BCOs -}
1630 bcos
<- coreExprToBCOs dflags iNTERACTIVE prepd_expr
1633 hval
<- linkExpr hsc_env srcspan bcos
1639 {- **********************************************************************
1641 Statistics on reading interfaces
1643 %********************************************************************* -}
1645 dumpIfaceStats
:: HscEnv
-> IO ()
1646 dumpIfaceStats hsc_env
= do
1647 eps
<- readIORef
(hsc_EPS hsc_env
)
1648 dumpIfSet
(dump_if_trace || dump_rn_stats
)
1649 "Interface statistics"
1652 dflags
= hsc_dflags hsc_env
1653 dump_rn_stats
= dopt Opt_D_dump_rn_stats dflags
1654 dump_if_trace
= dopt Opt_D_dump_if_trace dflags
1657 {- **********************************************************************
1659 Progress Messages: Module i of n
1661 %********************************************************************* -}
1663 showModuleIndex
:: Maybe (Int, Int) -> String
1664 showModuleIndex Nothing
= ""
1665 showModuleIndex
(Just
(i
,n
)) = "[" ++ padded
++ " of " ++ n_str
++ "] "
1669 padded
= replicate (length n_str
- length i_str
) ' ' ++ i_str