1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
12 defaultCleanupHandler,
15 Ghc, GhcT, GhcMonad(..),
16 runGhc, runGhcT, initGhcMonad,
17 gcatch, gbracket, gfinally,
19 printExceptionAndWarnings,
23 -- * Flags and settings
24 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
25 GhcMode(..), GhcLink(..), defaultObjectTarget,
32 Target(..), TargetId(..), Phase,
39 -- * Loading\/compiling the program
41 load, LoadHowMuch(..),
42 SuccessFlag(..), succeeded, failed,
43 defaultWarnErrLogger, WarnErrLogger,
44 workingDirectoryChanged,
45 parseModule, typecheckModule, desugarModule, loadModule,
46 ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
47 TypecheckedSource, ParsedSource, RenamedSource, -- ditto
48 TypecheckedMod, ParsedMod,
49 moduleInfo, renamedSource, typecheckedSource,
50 parsedSource, coreModule,
51 compileToCoreModule, compileToCoreSimplified,
55 -- * Inspecting the module structure of the program
56 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
61 -- * Inspecting modules
68 modInfoIsExportedName,
72 mkPrintUnqualifiedForModule,
74 -- * Querying the environment
78 PrintUnqualified, alwaysQualify,
80 -- * Interactive evaluation
81 getBindings, getPrintUnqual,
85 setContext, getContext,
95 runStmt, parseImportDecl, SingleStep(..),
97 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
98 resumeHistory, resumeHistoryIx),
99 History(historyBreakInfo, historyEnclosingDecls),
100 GHC.getHistorySpan, getHistoryModule,
103 InteractiveEval.back,
104 InteractiveEval.forward,
107 InteractiveEval.compileExpr, HValue, dynCompileExpr,
108 GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
110 ModBreaks(..), BreakIndex,
111 BreakInfo(breakInfo_number, breakInfo_module),
112 BreakArray, setBreakOn, setBreakOff, getBreak,
116 -- * Abstract syntax elements
122 Module, mkModule, pprModule, moduleName, modulePackageId,
123 ModuleName, mkModuleName, moduleNameString,
127 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
129 RdrName(Qual,Unqual),
133 isImplicitId, isDeadBinder,
134 isExportedId, isLocalId, isGlobalId,
136 isPrimOpId, isFCallId, isClassOpId_maybe,
137 isDataConWorkId, idDataCon,
138 isBottomingId, isDictonaryId,
139 recordSelectorFieldLabel,
141 -- ** Type constructors
143 tyConTyVars, tyConDataCons, tyConArity,
144 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
146 synTyConDefn, synTyConType, synTyConResKind,
152 -- ** Data constructors
154 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
155 dataConIsInfix, isVanillaDataCon, dataConUserType,
157 StrictnessMark(..), isMarkedStrict,
161 classMethods, classSCTheta, classTvsFds,
166 instanceDFunId, pprInstance, pprInstanceHdr,
168 -- ** Types and Kinds
169 Type, splitForAllTys, funResultTy,
170 pprParendType, pprTypeApp,
173 ThetaType, pprForAll, pprThetaArrow,
179 module HsSyn, -- ToDo: remove extraneous bits
183 defaultFixity, maxPrecedence,
187 -- ** Source locations
189 mkSrcLoc, isGoodSrcLoc, noSrcLoc,
190 srcLocFile, srcLocLine, srcLocCol,
192 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
193 srcSpanStart, srcSpanEnd,
195 srcSpanStartLine, srcSpanEndLine,
196 srcSpanStartCol, srcSpanEndCol,
201 -- *** Constructing Located
202 noLoc, mkGeneralLocated,
204 -- *** Deconstructing Located
207 -- *** Combining and comparing Located values
208 eqLocated, cmpLocated, combineLocs, addCLoc,
209 leftmost_smallest, leftmost_largest, rightmost,
213 GhcException(..), showGhcException,
215 -- * Token stream manipulations
217 getTokenStream, getRichTokenStream,
218 showRichTokenStream, addSourceToTokens,
220 -- * Pure interface to the parser
231 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
232 * what StaticFlags should we expose, if any?
235 #include "HsVersions.h"
238 import Linker ( HValue )
241 import InteractiveEval
246 import DriverPipeline ( compile' )
252 import qualified HsSyn -- hack as we want to reexport the whole module
253 import HsSyn hiding ((<.>))
255 import Coercion ( synTyConResKind )
256 import TcType hiding( typeKind )
259 import TysPrim ( alphaTyVars )
264 import Name hiding ( varName )
265 -- import OccName ( parenSymOcc )
268 import CoreSyn ( CoreBind )
270 import DriverPhases ( Phase(..), isHaskellSrcFilename )
274 import StaticFlagParser
275 import qualified StaticFlags
276 import SysTools ( initSysTools, cleanTempFiles,
282 import Bag ( unitBag )
289 import Maybes ( expectJust )
291 import qualified Parser
294 import System.Directory ( doesFileExist, getCurrentDirectory )
296 import Data.List ( find )
297 import Data.Typeable ( Typeable )
298 import Data.Word ( Word8 )
300 import System.Exit ( exitWith, ExitCode(..) )
301 import System.Time ( getClockTime )
304 import System.FilePath
306 import Prelude hiding (init)
309 -- %************************************************************************
311 -- Initialisation: exception handlers
313 -- %************************************************************************
316 -- | Install some default exception handlers and run the inner computation.
317 -- Unless you want to handle exceptions yourself, you should wrap this around
318 -- the top level of your program. The default handlers output the error
319 -- message(s) to stderr and exit cleanly.
320 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a
321 defaultErrorHandler dflags inner =
322 -- top-level exception handler: any unrecognised exception is a compiler bug.
323 ghandle (\exception -> liftIO $ do
325 case fromException exception of
326 -- an IO exception probably isn't our fault, so don't panic
327 Just (ioe :: IOException) ->
328 fatalErrorMsg dflags (text (show ioe))
329 _ -> case fromException exception of
330 Just UserInterrupt -> exitWith (ExitFailure 1)
331 Just StackOverflow ->
332 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
333 _ -> case fromException exception of
334 Just (ex :: ExitCode) -> throw ex
337 (text (show (Panic (show exception))))
338 exitWith (ExitFailure 1)
341 -- error messages propagated as exceptions
346 PhaseFailed _ code -> exitWith code
347 Signal _ -> exitWith (ExitFailure 1)
348 _ -> do fatalErrorMsg dflags (text (show ge))
349 exitWith (ExitFailure 1)
353 -- | Install a default cleanup handler to remove temporary files deposited by
354 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
355 -- want to override the error handling, but still get the ordinary cleanup
357 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
358 DynFlags -> m a -> m a
359 defaultCleanupHandler dflags inner =
360 -- make sure we clean up after ourselves
363 cleanTempFiles dflags
366 -- exceptions will be blocked while we clean the temporary files,
367 -- so there shouldn't be any difficulty if we receive further
371 -- %************************************************************************
375 -- %************************************************************************
377 -- | Run function for the 'Ghc' monad.
379 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
380 -- to this function will create a new session which should not be shared among
383 -- Any errors not handled inside the 'Ghc' action are propagated as IO
386 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
387 -> Ghc a -- ^ The action to perform.
389 runGhc mb_top_dir ghc = do
390 ref <- newIORef undefined
391 let session = Session ref
392 flip unGhc session $ do
393 initGhcMonad mb_top_dir
395 -- XXX: unregister interrupt handlers here?
397 -- | Run function for 'GhcT' monad transformer.
399 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
400 -- to this function will create a new session which should not be shared among
403 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
404 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
405 -> GhcT m a -- ^ The action to perform.
407 runGhcT mb_top_dir ghct = do
408 ref <- liftIO $ newIORef undefined
409 let session = Session ref
410 flip unGhcT session $ do
411 initGhcMonad mb_top_dir
414 -- | Initialise a GHC session.
416 -- If you implement a custom 'GhcMonad' you must call this function in the
417 -- monad run function. It will initialise the session variable and clear all
420 -- The first argument should point to the directory where GHC's library files
421 -- reside. More precisely, this should be the output of @ghc --print-libdir@
422 -- of the version of GHC the module using this API is compiled with. For
423 -- portability, you should use the @ghc-paths@ package, available at
424 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
426 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
427 initGhcMonad mb_top_dir = do
429 liftIO $ installSignalHandlers
431 liftIO $ StaticFlags.initStaticOpts
433 dflags0 <- liftIO $ initDynFlags defaultDynFlags
434 dflags <- liftIO $ initSysTools mb_top_dir dflags0
435 env <- liftIO $ newHscEnv dflags
439 -- %************************************************************************
443 -- %************************************************************************
445 -- | Updates the DynFlags in a Session. This also reads
446 -- the package database (unless it has already been read),
447 -- and prepares the compilers knowledge about packages. It
448 -- can be called again to load new packages: just add new
449 -- package flags to (packageFlags dflags).
451 -- Returns a list of new packages that may need to be linked in using
452 -- the dynamic linker (see 'linkPackages') as a result of new package
453 -- flags. If you are not doing linking or doing static linking, you
454 -- can ignore the list of packages returned.
456 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
457 setSessionDynFlags dflags = do
458 (dflags', preload) <- liftIO $ initPackages dflags
459 modifySession (\h -> h{ hsc_dflags = dflags' })
464 -- %************************************************************************
466 -- Setting, getting, and modifying the targets
468 -- %************************************************************************
470 -- ToDo: think about relative vs. absolute file paths. And what
471 -- happens when the current directory changes.
473 -- | Sets the targets for this session. Each target may be a module name
474 -- or a filename. The targets correspond to the set of root modules for
475 -- the program\/library. Unloading the current program is achieved by
476 -- setting the current set of targets to be empty, followed by 'load'.
477 setTargets :: GhcMonad m => [Target] -> m ()
478 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
480 -- | Returns the current set of targets
481 getTargets :: GhcMonad m => m [Target]
482 getTargets = withSession (return . hsc_targets)
484 -- | Add another target.
485 addTarget :: GhcMonad m => Target -> m ()
487 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
490 removeTarget :: GhcMonad m => TargetId -> m ()
491 removeTarget target_id
492 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
494 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
496 -- | Attempts to guess what Target a string refers to. This function
497 -- implements the @--make@/GHCi command-line syntax for filenames:
499 -- - if the string looks like a Haskell source filename, then interpret it
502 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
505 -- - otherwise interpret the string as a module name
507 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
508 guessTarget str (Just phase)
509 = return (Target (TargetFile str (Just phase)) True Nothing)
510 guessTarget str Nothing
511 | isHaskellSrcFilename file
512 = return (target (TargetFile file Nothing))
514 = do exists <- liftIO $ doesFileExist hs_file
516 then return (target (TargetFile hs_file Nothing))
518 exists <- liftIO $ doesFileExist lhs_file
520 then return (target (TargetFile lhs_file Nothing))
522 if looksLikeModuleName file
523 then return (target (TargetModule (mkModuleName file)))
526 (ProgramError (showSDoc $
527 text "target" <+> quotes (text file) <+>
528 text "is not a module name or a source file"))
531 | '*':rest <- str = (rest, False)
532 | otherwise = (str, True)
534 hs_file = file <.> "hs"
535 lhs_file = file <.> "lhs"
537 target tid = Target tid obj_allowed Nothing
540 -- | Inform GHC that the working directory has changed. GHC will flush
541 -- its cache of module locations, since it may no longer be valid.
543 -- Note: Before changing the working directory make sure all threads running
544 -- in the same session have stopped. If you change the working directory,
545 -- you should also unload the current program (set targets to empty,
546 -- followed by load).
547 workingDirectoryChanged :: GhcMonad m => m ()
548 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
551 -- %************************************************************************
553 -- Running phases one at a time
555 -- %************************************************************************
557 class ParsedMod m where
558 modSummary :: m -> ModSummary
559 parsedSource :: m -> ParsedSource
561 class ParsedMod m => TypecheckedMod m where
562 renamedSource :: m -> Maybe RenamedSource
563 typecheckedSource :: m -> TypecheckedSource
564 moduleInfo :: m -> ModuleInfo
565 tm_internals :: m -> (TcGblEnv, ModDetails)
566 -- ToDo: improvements that could be made here:
567 -- if the module succeeded renaming but not typechecking,
568 -- we can still get back the GlobalRdrEnv and exports, so
569 -- perhaps the ModuleInfo should be split up into separate
572 class TypecheckedMod m => DesugaredMod m where
573 coreModule :: m -> ModGuts
575 -- | The result of successful parsing.
577 ParsedModule { pm_mod_summary :: ModSummary
578 , pm_parsed_source :: ParsedSource }
580 instance ParsedMod ParsedModule where
581 modSummary m = pm_mod_summary m
582 parsedSource m = pm_parsed_source m
584 -- | The result of successful typechecking. It also contains the parser
586 data TypecheckedModule =
587 TypecheckedModule { tm_parsed_module :: ParsedModule
588 , tm_renamed_source :: Maybe RenamedSource
589 , tm_typechecked_source :: TypecheckedSource
590 , tm_checked_module_info :: ModuleInfo
591 , tm_internals_ :: (TcGblEnv, ModDetails)
594 instance ParsedMod TypecheckedModule where
595 modSummary m = modSummary (tm_parsed_module m)
596 parsedSource m = parsedSource (tm_parsed_module m)
598 instance TypecheckedMod TypecheckedModule where
599 renamedSource m = tm_renamed_source m
600 typecheckedSource m = tm_typechecked_source m
601 moduleInfo m = tm_checked_module_info m
602 tm_internals m = tm_internals_ m
604 -- | The result of successful desugaring (i.e., translation to core). Also
605 -- contains all the information of a typechecked module.
606 data DesugaredModule =
607 DesugaredModule { dm_typechecked_module :: TypecheckedModule
608 , dm_core_module :: ModGuts
611 instance ParsedMod DesugaredModule where
612 modSummary m = modSummary (dm_typechecked_module m)
613 parsedSource m = parsedSource (dm_typechecked_module m)
615 instance TypecheckedMod DesugaredModule where
616 renamedSource m = renamedSource (dm_typechecked_module m)
617 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
618 moduleInfo m = moduleInfo (dm_typechecked_module m)
619 tm_internals m = tm_internals_ (dm_typechecked_module m)
621 instance DesugaredMod DesugaredModule where
622 coreModule m = dm_core_module m
624 type ParsedSource = Located (HsModule RdrName)
625 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
627 type TypecheckedSource = LHsBinds Id
630 -- - things that aren't in the output of the typechecker right now:
634 -- - type/data/newtype declarations
635 -- - class declarations
637 -- - extra things in the typechecker's output:
638 -- - default methods are turned into top-level decls.
639 -- - dictionary bindings
641 -- | Return the 'ModSummary' of a module with the given name.
643 -- The module must be part of the module graph (see 'hsc_mod_graph' and
644 -- 'ModuleGraph'). If this is not the case, this function will throw a
647 -- This function ignores boot modules and requires that there is only one
648 -- non-boot module with the given name.
649 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
650 getModSummary mod = do
651 mg <- liftM hsc_mod_graph getSession
652 case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
653 [] -> throw $ mkApiErr (text "Module not part of module graph")
655 multiple -> throw $ mkApiErr (text "getModSummary is ambiguous: " <+> ppr multiple)
659 -- Throws a 'SourceError' on parse error.
660 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
662 hsc_env <- getSession
663 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
664 rdr_module <- liftIO $ hscParse hsc_env_tmp ms
665 return (ParsedModule ms rdr_module)
667 -- | Typecheck and rename a parsed module.
669 -- Throws a 'SourceError' if either fails.
670 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
671 typecheckModule pmod = do
672 let ms = modSummary pmod
673 hsc_env <- getSession
674 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
675 (tc_gbl_env, rn_info)
676 <- liftIO $ hscTypecheckRename hsc_env_tmp ms (parsedSource pmod)
677 details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env
680 tm_internals_ = (tc_gbl_env, details),
681 tm_parsed_module = pmod,
682 tm_renamed_source = rn_info,
683 tm_typechecked_source = tcg_binds tc_gbl_env,
684 tm_checked_module_info =
686 minf_type_env = md_types details,
687 minf_exports = availsToNameSet $ md_exports details,
688 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
689 minf_instances = md_insts details
691 ,minf_modBreaks = emptyModBreaks
695 -- | Desugar a typechecked module.
696 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
697 desugarModule tcm = do
698 let ms = modSummary tcm
699 let (tcg, _) = tm_internals tcm
700 hsc_env <- getSession
701 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
702 guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg
705 dm_typechecked_module = tcm,
706 dm_core_module = guts
709 -- | Load a module. Input doesn't need to be desugared.
711 -- A module must be loaded before dependent modules can be typechecked. This
712 -- always includes generating a 'ModIface' and, depending on the
713 -- 'DynFlags.hscTarget', may also include code generation.
715 -- This function will always cause recompilation and will always overwrite
716 -- previous compilation results (potentially files on disk).
718 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
720 let ms = modSummary tcm
721 let mod = ms_mod_name ms
722 let loc = ms_location ms
723 let (tcg, _details) = tm_internals tcm
725 mb_linkable <- case ms_obj_date ms of
726 Just t | t > ms_hs_date ms -> do
727 l <- liftIO $ findObjectLinkable (ms_mod ms)
730 _otherwise -> return Nothing
732 -- compile doesn't change the session
733 hsc_env <- getSession
734 mod_info <- liftIO $ compile' (hscNothingBackendOnly tcg,
735 hscInteractiveBackendOnly tcg,
736 hscBatchBackendOnly tcg)
737 hsc_env ms 1 1 Nothing mb_linkable
739 modifySession $ \e -> e{ hsc_HPT = addToUFM (hsc_HPT e) mod mod_info }
743 -- %************************************************************************
747 -- %************************************************************************
749 -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
750 -- the 'GHC.compileToCoreModule' interface.
754 cm_module :: !Module,
755 -- | Type environment for types declared in this module
756 cm_types :: !TypeEnv,
758 cm_binds :: [CoreBind],
760 cm_imports :: ![Module]
763 instance Outputable CoreModule where
764 ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb}) =
765 text "%module" <+> ppr mn <+> ppr te $$ vcat (map ppr cb)
767 -- | This is the way to get access to the Core bindings corresponding
768 -- to a module. 'compileToCore' parses, typechecks, and
769 -- desugars the module, then returns the resulting Core module (consisting of
770 -- the module name, type declarations, and function declarations) if
772 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
773 compileToCoreModule = compileCore False
775 -- | Like compileToCoreModule, but invokes the simplifier, so
776 -- as to return simplified and tidied Core.
777 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
778 compileToCoreSimplified = compileCore True
780 -- | Provided for backwards-compatibility: compileToCore returns just the Core
781 -- bindings, but for most purposes, you probably want to call
782 -- compileToCoreModule.
783 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
784 compileToCore fn = do
785 mod <- compileToCoreModule session fn
786 return $ cm_binds mod
788 -- | Takes a CoreModule and compiles the bindings therein
789 -- to object code. The first argument is a bool flag indicating
790 -- whether to run the simplifier.
791 -- The resulting .o, .hi, and executable files, if any, are stored in the
792 -- current directory, and named according to the module name.
793 -- This has only so far been tested with a single self-contained module.
794 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
795 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
796 dflags <- getSessionDynFlags
797 currentTime <- liftIO $ getClockTime
798 cwd <- liftIO $ getCurrentDirectory
799 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
800 ((moduleNameSlashes . moduleName) mName)
802 let modSummary = ModSummary { ms_mod = mName,
803 ms_hsc_src = ExtCoreFile,
804 ms_location = modLocation,
805 -- By setting the object file timestamp to Nothing,
806 -- we always force recompilation, which is what we
807 -- want. (Thus it doesn't matter what the timestamp
808 -- for the (nonexistent) source file is.)
809 ms_hs_date = currentTime,
810 ms_obj_date = Nothing,
811 -- Only handling the single-module case for now, so no imports.
816 ms_hspp_opts = dflags,
817 ms_hspp_buf = Nothing
820 hsc_env <- getSession
821 liftIO $ hscCompileCore hsc_env simplify modSummary (cm_binds cm)
824 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
825 compileCore simplify fn = do
826 -- First, set the target to the desired filename
827 target <- guessTarget fn Nothing
829 _ <- load LoadAllTargets
830 -- Then find dependencies
831 modGraph <- depanal [] True
832 case find ((== fn) . msHsFilePath) modGraph of
833 Just modSummary -> do
834 -- Now we have the module name;
835 -- parse, typecheck and desugar the module
836 mod_guts <- coreModule `fmap`
837 -- TODO: space leaky: call hsc* directly?
838 (desugarModule =<< typecheckModule =<< parseModule modSummary)
839 liftM gutsToCoreModule $
842 -- If simplify is true: simplify (hscSimplify), then tidy
844 hsc_env <- getSession
845 simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts
846 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
847 return $ Left tidy_guts
849 return $ Right mod_guts
851 Nothing -> panic "compileToCoreModule: target FilePath not found in\
852 module dependency graph"
853 where -- two versions, based on whether we simplify (thus run tidyProgram,
854 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
855 -- we just have a ModGuts.
856 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
857 gutsToCoreModule (Left (cg, md)) = CoreModule {
858 cm_module = cg_module cg, cm_types = md_types md,
859 cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
861 gutsToCoreModule (Right mg) = CoreModule {
862 cm_module = mg_module mg, cm_types = mg_types mg,
863 cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds = mg_binds mg
866 -- %************************************************************************
868 -- Inspecting the session
870 -- %************************************************************************
872 -- | Get the module dependency graph.
873 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
874 getModuleGraph = liftM hsc_mod_graph getSession
876 -- | Determines whether a set of modules requires Template Haskell.
878 -- Note that if the session's 'DynFlags' enabled Template Haskell when
879 -- 'depanal' was called, then each module in the returned module graph will
880 -- have Template Haskell enabled whether it is actually needed or not.
881 needsTemplateHaskell :: ModuleGraph -> Bool
882 needsTemplateHaskell ms =
883 any (xopt Opt_TemplateHaskell . ms_hspp_opts) ms
885 -- | Return @True@ <==> module is loaded.
886 isLoaded :: GhcMonad m => ModuleName -> m Bool
887 isLoaded m = withSession $ \hsc_env ->
888 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
890 -- | Return the bindings for the current interactive session.
891 getBindings :: GhcMonad m => m [TyThing]
892 getBindings = withSession $ \hsc_env ->
893 -- we have to implement the shadowing behaviour of ic_tmp_ids here
894 -- (see InteractiveContext) and the quickest way is to use an OccEnv.
896 occ_env = mkOccEnv [ (nameOccName (idName id), AnId id)
897 | id <- ic_tmp_ids (hsc_IC hsc_env) ]
899 return (occEnvElts occ_env)
901 getPrintUnqual :: GhcMonad m => m PrintUnqualified
902 getPrintUnqual = withSession $ \hsc_env ->
903 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
905 -- | Container for information about a 'Module'.
906 data ModuleInfo = ModuleInfo {
907 minf_type_env :: TypeEnv,
908 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
909 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
910 minf_instances :: [Instance]
912 ,minf_modBreaks :: ModBreaks
914 -- ToDo: this should really contain the ModIface too
916 -- We don't want HomeModInfo here, because a ModuleInfo applies
917 -- to package modules too.
919 -- | Request information about a loaded 'Module'
920 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
921 getModuleInfo mdl = withSession $ \hsc_env -> do
922 let mg = hsc_mod_graph hsc_env
923 if mdl `elem` map ms_mod mg
924 then liftIO $ getHomeModuleInfo hsc_env (moduleName mdl)
926 {- if isHomeModule (hsc_dflags hsc_env) mdl
928 else -} liftIO $ getPackageModuleInfo hsc_env mdl
929 -- getPackageModuleInfo will attempt to find the interface, so
930 -- we don't want to call it for a home module, just in case there
931 -- was a problem loading the module and the interface doesn't
932 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
934 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
936 getPackageModuleInfo hsc_env mdl = do
937 mb_avails <- hscGetModuleExports hsc_env mdl
939 Nothing -> return Nothing
941 eps <- readIORef (hsc_EPS hsc_env)
943 names = availsToNameSet avails
945 tys = [ ty | name <- concatMap availNames avails,
946 Just ty <- [lookupTypeEnv pte name] ]
948 return (Just (ModuleInfo {
949 minf_type_env = mkTypeEnv tys,
950 minf_exports = names,
951 minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
952 minf_instances = error "getModuleInfo: instances for package module unimplemented",
953 minf_modBreaks = emptyModBreaks
956 getPackageModuleInfo _hsc_env _mdl = do
957 -- bogusly different for non-GHCI (ToDo)
961 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
962 getHomeModuleInfo hsc_env mdl =
963 case lookupUFM (hsc_HPT hsc_env) mdl of
964 Nothing -> return Nothing
966 let details = hm_details hmi
967 return (Just (ModuleInfo {
968 minf_type_env = md_types details,
969 minf_exports = availsToNameSet (md_exports details),
970 minf_rdr_env = mi_globals $! hm_iface hmi,
971 minf_instances = md_insts details
973 ,minf_modBreaks = getModBreaks hmi
977 -- | The list of top-level entities defined in a module
978 modInfoTyThings :: ModuleInfo -> [TyThing]
979 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
981 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
982 modInfoTopLevelScope minf
983 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
985 modInfoExports :: ModuleInfo -> [Name]
986 modInfoExports minf = nameSetToList $! minf_exports minf
988 -- | Returns the instances defined by the specified module.
989 -- Warning: currently unimplemented for package modules.
990 modInfoInstances :: ModuleInfo -> [Instance]
991 modInfoInstances = minf_instances
993 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
994 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
996 mkPrintUnqualifiedForModule :: GhcMonad m =>
998 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
999 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
1000 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
1002 modInfoLookupName :: GhcMonad m =>
1004 -> m (Maybe TyThing) -- XXX: returns a Maybe X
1005 modInfoLookupName minf name = withSession $ \hsc_env -> do
1006 case lookupTypeEnv (minf_type_env minf) name of
1007 Just tyThing -> return (Just tyThing)
1009 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
1010 return $! lookupType (hsc_dflags hsc_env)
1011 (hsc_HPT hsc_env) (eps_PTE eps) name
1014 modInfoModBreaks :: ModuleInfo -> ModBreaks
1015 modInfoModBreaks = minf_modBreaks
1018 isDictonaryId :: Id -> Bool
1020 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
1022 -- | Looks up a global name: that is, any top-level name in any
1023 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1024 -- the interactive context, and therefore does not require a preceding
1026 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
1027 lookupGlobalName name = withSession $ \hsc_env -> do
1028 liftIO $ lookupTypeHscEnv hsc_env name
1030 findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
1031 findGlobalAnns deserialize target = withSession $ \hsc_env -> do
1032 ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
1033 return (findAnns deserialize ann_env target)
1036 -- | get the GlobalRdrEnv for a session
1037 getGRE :: GhcMonad m => m GlobalRdrEnv
1038 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
1041 -- -----------------------------------------------------------------------------
1043 -- | Return all /external/ modules available in the package database.
1044 -- Modules from the current session (i.e., from the 'HomePackageTable') are
1046 packageDbModules :: GhcMonad m =>
1047 Bool -- ^ Only consider exposed packages.
1049 packageDbModules only_exposed = do
1050 dflags <- getSessionDynFlags
1051 let pkgs = eltsUFM (pkgIdMap (pkgState dflags))
1053 [ mkModule pid modname | p <- pkgs
1054 , not only_exposed || exposed p
1055 , let pid = packageConfigId p
1056 , modname <- exposedModules p ]
1058 -- -----------------------------------------------------------------------------
1059 -- Misc exported utils
1061 dataConType :: DataCon -> Type
1062 dataConType dc = idType (dataConWrapId dc)
1064 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1065 pprParenSymName :: NamedThing a => a -> SDoc
1066 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1068 -- ----------------------------------------------------------------------------
1073 -- - Data and Typeable instances for HsSyn.
1075 -- ToDo: check for small transformations that happen to the syntax in
1076 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1078 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1079 -- to get from TyCons, Ids etc. to TH syntax (reify).
1081 -- :browse will use either lm_toplev or inspect lm_interface, depending
1082 -- on whether the module is interpreted or not.
1086 -- Extract the filename, stringbuffer content and dynflags associed to a module
1088 -- XXX: Explain pre-conditions
1089 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
1090 getModuleSourceAndFlags mod = do
1091 m <- getModSummary (moduleName mod)
1092 case ml_hs_file $ ms_location m of
1093 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
1094 Just sourceFile -> do
1095 source <- liftIO $ hGetStringBuffer sourceFile
1096 return (sourceFile, source, ms_hspp_opts m)
1099 -- | Return module source as token stream, including comments.
1101 -- The module must be in the module graph and its source must be available.
1102 -- Throws a 'HscTypes.SourceError' on parse error.
1103 getTokenStream :: GhcMonad m => Module -> m [Located Token]
1104 getTokenStream mod = do
1105 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1106 let startLoc = mkSrcLoc (mkFastString sourceFile) 1 1
1107 case lexTokenStream source startLoc flags of
1108 POk _ ts -> return ts
1109 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
1111 -- | Give even more information on the source than 'getTokenStream'
1112 -- This function allows reconstructing the source completely with
1113 -- 'showRichTokenStream'.
1114 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
1115 getRichTokenStream mod = do
1116 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1117 let startLoc = mkSrcLoc (mkFastString sourceFile) 1 1
1118 case lexTokenStream source startLoc flags of
1119 POk _ ts -> return $ addSourceToTokens startLoc source ts
1120 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
1122 -- | Given a source location and a StringBuffer corresponding to this
1123 -- location, return a rich token stream with the source associated to the
1125 addSourceToTokens :: SrcLoc -> StringBuffer -> [Located Token]
1126 -> [(Located Token, String)]
1127 addSourceToTokens _ _ [] = []
1128 addSourceToTokens loc buf (t@(L span _) : ts)
1129 | not (isGoodSrcSpan span) = (t,"") : addSourceToTokens loc buf ts
1130 | otherwise = (t,str) : addSourceToTokens newLoc newBuf ts
1132 (newLoc, newBuf, str) = go "" loc buf
1133 start = srcSpanStart span
1134 end = srcSpanEnd span
1135 go acc loc buf | loc < start = go acc nLoc nBuf
1136 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
1137 | otherwise = (loc, buf, reverse acc)
1138 where (ch, nBuf) = nextChar buf
1139 nLoc = advanceSrcLoc loc ch
1142 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
1143 -- return source code almost identical to the original code (except for
1144 -- insignificant whitespace.)
1145 showRichTokenStream :: [(Located Token, String)] -> String
1146 showRichTokenStream ts = go startLoc ts ""
1147 where sourceFile = srcSpanFile (getLoc . fst . head $ ts)
1148 startLoc = mkSrcLoc sourceFile 1 1
1150 go loc ((L span _, str):ts)
1151 | not (isGoodSrcSpan span) = go loc ts
1152 | locLine == tokLine = ((replicate (tokCol - locCol) ' ') ++)
1155 | otherwise = ((replicate (tokLine - locLine) '\n') ++)
1156 . ((replicate tokCol ' ') ++)
1159 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
1160 (tokLine, tokCol) = (srcSpanStartLine span, srcSpanStartCol span)
1161 tokEnd = srcSpanEnd span
1163 -- -----------------------------------------------------------------------------
1164 -- Interactive evaluation
1166 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1167 -- filesystem and package database to find the corresponding 'Module',
1168 -- using the algorithm that is used for an @import@ declaration.
1169 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1170 findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
1172 dflags = hsc_dflags hsc_env
1173 this_pkg = thisPackage dflags
1176 Just pkg | fsToPackageId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
1177 res <- findImportedModule hsc_env mod_name maybe_pkg
1179 Found _ m -> return m
1180 err -> noModError dflags noSrcSpan mod_name err
1182 home <- lookupLoadedHomeModule mod_name
1185 Nothing -> liftIO $ do
1186 res <- findImportedModule hsc_env mod_name maybe_pkg
1188 Found loc m | modulePackageId m /= this_pkg -> return m
1189 | otherwise -> modNotLoadedError m loc
1190 err -> noModError dflags noSrcSpan mod_name err
1192 modNotLoadedError :: Module -> ModLocation -> IO a
1193 modNotLoadedError m loc = ghcError $ CmdLineError $ showSDoc $
1194 text "module is not loaded:" <+>
1195 quotes (ppr (moduleName m)) <+>
1196 parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
1198 -- | Like 'findModule', but differs slightly when the module refers to
1199 -- a source file, and the file has not been loaded via 'load'. In
1200 -- this case, 'findModule' will throw an error (module not loaded),
1201 -- but 'lookupModule' will check to see whether the module can also be
1202 -- found in a package, and if so, that package 'Module' will be
1203 -- returned. If not, the usual module-not-found error will be thrown.
1205 lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1206 lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
1207 lookupModule mod_name Nothing = withSession $ \hsc_env -> do
1208 home <- lookupLoadedHomeModule mod_name
1211 Nothing -> liftIO $ do
1212 res <- findExposedPackageModule hsc_env mod_name Nothing
1214 Found _ m -> return m
1215 err -> noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
1217 lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
1218 lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
1219 case lookupUFM (hsc_HPT hsc_env) mod_name of
1220 Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
1221 _not_a_home_module -> return Nothing
1224 getHistorySpan :: GhcMonad m => History -> m SrcSpan
1225 getHistorySpan h = withSession $ \hsc_env ->
1226 return$ InteractiveEval.getHistorySpan hsc_env h
1228 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
1229 obtainTermFromVal bound force ty a =
1230 withSession $ \hsc_env ->
1231 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
1233 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
1234 obtainTermFromId bound force id =
1235 withSession $ \hsc_env ->
1236 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id
1240 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1241 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1242 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
1244 withSession $ \hsc_env ->
1245 liftIO $ hscTcRcLookupName hsc_env name
1247 -- -----------------------------------------------------------------------------
1250 -- | A pure interface to the module parser.
1252 parser :: String -- ^ Haskell module source text (full Unicode is supported)
1253 -> DynFlags -- ^ the flags
1254 -> FilePath -- ^ the filename (for source locations)
1255 -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
1257 parser str dflags filename =
1259 loc = mkSrcLoc (mkFastString filename) 1 1
1260 buf = stringToStringBuffer str
1262 case unP Parser.parseModule (mkPState dflags buf loc) of
1265 Left (unitBag (mkPlainErrMsg span err))
1267 POk pst rdr_module ->
1268 let (warns,_) = getMessages pst in
1269 Right (warns, rdr_module)