Add support for all top-level declarations to GHCi
[ghc.git] / compiler / main / GHC.hs
1 -- -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow, 2005
4 --
5 -- The GHC API
6 --
7 -- -----------------------------------------------------------------------------
8
9 module GHC (
10 -- * Initialisation
11 defaultErrorHandler,
12 defaultCleanupHandler,
13
14 -- * GHC Monad
15 Ghc, GhcT, GhcMonad(..), HscEnv,
16 runGhc, runGhcT, initGhcMonad,
17 gcatch, gbracket, gfinally,
18 printException,
19 printExceptionAndWarnings,
20 handleSourceError,
21 needsTemplateHaskell,
22
23 -- * Flags and settings
24 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
25 GhcMode(..), GhcLink(..), defaultObjectTarget,
26 parseDynamicFlags,
27 getSessionDynFlags,
28 setSessionDynFlags,
29 parseStaticFlags,
30
31 -- * Targets
32 Target(..), TargetId(..), Phase,
33 setTargets,
34 getTargets,
35 addTarget,
36 removeTarget,
37 guessTarget,
38
39 -- * Loading\/compiling the program
40 depanal,
41 load, LoadHowMuch(..), InteractiveImport(..),
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,
52 compileCoreToObj,
53 getModSummary,
54
55 -- * Inspecting the module structure of the program
56 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
57 getModuleGraph,
58 isLoaded,
59 topSortModuleGraph,
60
61 -- * Inspecting modules
62 ModuleInfo,
63 getModuleInfo,
64 modInfoTyThings,
65 modInfoTopLevelScope,
66 modInfoExports,
67 modInfoInstances,
68 modInfoIsExportedName,
69 modInfoLookupName,
70 modInfoIface,
71 lookupGlobalName,
72 findGlobalAnns,
73 mkPrintUnqualifiedForModule,
74 ModIface(..),
75
76 -- * Querying the environment
77 packageDbModules,
78
79 -- * Printing
80 PrintUnqualified, alwaysQualify,
81
82 -- * Interactive evaluation
83 getBindings, getInsts, getPrintUnqual,
84 findModule,
85 lookupModule,
86 #ifdef GHCI
87 setContext, getContext,
88 getNamesInScope,
89 getRdrNamesInScope,
90 getGRE,
91 moduleIsInterpreted,
92 getInfo,
93 exprType,
94 typeKind,
95 parseName,
96 RunResult(..),
97 runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
98 parseImportDecl, SingleStep(..),
99 resume,
100 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
101 resumeHistory, resumeHistoryIx),
102 History(historyBreakInfo, historyEnclosingDecls),
103 GHC.getHistorySpan, getHistoryModule,
104 getResumeContext,
105 abandon, abandonAll,
106 InteractiveEval.back,
107 InteractiveEval.forward,
108 showModule,
109 isModuleInterpreted,
110 InteractiveEval.compileExpr, HValue, dynCompileExpr,
111 GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
112 modInfoModBreaks,
113 ModBreaks(..), BreakIndex,
114 BreakInfo(breakInfo_number, breakInfo_module),
115 BreakArray, setBreakOn, setBreakOff, getBreak,
116 #endif
117 lookupName,
118
119 -- * Abstract syntax elements
120
121 -- ** Packages
122 PackageId,
123
124 -- ** Modules
125 Module, mkModule, pprModule, moduleName, modulePackageId,
126 ModuleName, mkModuleName, moduleNameString,
127
128 -- ** Names
129 Name,
130 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
131 NamedThing(..),
132 RdrName(Qual,Unqual),
133
134 -- ** Identifiers
135 Id, idType,
136 isImplicitId, isDeadBinder,
137 isExportedId, isLocalId, isGlobalId,
138 isRecordSelector,
139 isPrimOpId, isFCallId, isClassOpId_maybe,
140 isDataConWorkId, idDataCon,
141 isBottomingId, isDictonaryId,
142 recordSelectorFieldLabel,
143
144 -- ** Type constructors
145 TyCon,
146 tyConTyVars, tyConDataCons, tyConArity,
147 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
148 isFamilyTyCon, tyConClass_maybe,
149 synTyConDefn, synTyConType, synTyConResKind,
150
151 -- ** Type variables
152 TyVar,
153 alphaTyVars,
154
155 -- ** Data constructors
156 DataCon,
157 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
158 dataConIsInfix, isVanillaDataCon, dataConUserType,
159 dataConStrictMarks,
160 StrictnessMark(..), isMarkedStrict,
161
162 -- ** Classes
163 Class,
164 classMethods, classSCTheta, classTvsFds, classATs,
165 pprFundeps,
166
167 -- ** Instances
168 Instance,
169 instanceDFunId,
170 pprInstance, pprInstanceHdr,
171 pprFamInst, pprFamInstHdr,
172
173 -- ** Types and Kinds
174 Type, splitForAllTys, funResultTy,
175 pprParendType, pprTypeApp,
176 Kind,
177 PredType,
178 ThetaType, pprForAll, pprThetaArrowTy,
179
180 -- ** Entities
181 TyThing(..),
182
183 -- ** Syntax
184 module HsSyn, -- ToDo: remove extraneous bits
185
186 -- ** Fixities
187 FixityDirection(..),
188 defaultFixity, maxPrecedence,
189 negateFixity,
190 compareFixity,
191
192 -- ** Source locations
193 SrcLoc(..), RealSrcLoc,
194 mkSrcLoc, noSrcLoc,
195 srcLocFile, srcLocLine, srcLocCol,
196 SrcSpan(..), RealSrcSpan,
197 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
198 srcSpanStart, srcSpanEnd,
199 srcSpanFile,
200 srcSpanStartLine, srcSpanEndLine,
201 srcSpanStartCol, srcSpanEndCol,
202
203 -- ** Located
204 GenLocated(..), Located,
205
206 -- *** Constructing Located
207 noLoc, mkGeneralLocated,
208
209 -- *** Deconstructing Located
210 getLoc, unLoc,
211
212 -- *** Combining and comparing Located values
213 eqLocated, cmpLocated, combineLocs, addCLoc,
214 leftmost_smallest, leftmost_largest, rightmost,
215 spans, isSubspanOf,
216
217 -- * Exceptions
218 GhcException(..), showGhcException,
219
220 -- * Token stream manipulations
221 Token,
222 getTokenStream, getRichTokenStream,
223 showRichTokenStream, addSourceToTokens,
224
225 -- * Pure interface to the parser
226 parser,
227
228 -- * Miscellaneous
229 --sessionHscEnv,
230 cyclicModuleErr,
231 ) where
232
233 {-
234 ToDo:
235
236 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
237 * what StaticFlags should we expose, if any?
238 -}
239
240 #include "HsVersions.h"
241
242 #ifdef GHCI
243 import Linker ( HValue )
244 import ByteCodeInstr
245 import BreakArray
246 import InteractiveEval
247 #endif
248
249 import HscMain
250 import GhcMake
251 import DriverPipeline ( compile' )
252 import GhcMonad
253 import TcRnTypes
254 import Packages
255 import NameSet
256 import RdrName
257 import qualified HsSyn -- hack as we want to reexport the whole module
258 import HsSyn hiding ((<.>))
259 import Type hiding( typeKind )
260 import Coercion ( synTyConResKind )
261 import TcType hiding( typeKind )
262 import Id
263 import TysPrim ( alphaTyVars )
264 import TyCon
265 import Class
266 import DataCon
267 import Name hiding ( varName )
268 import InstEnv
269 import FamInstEnv
270 import SrcLoc
271 import CoreSyn
272 import TidyPgm
273 import DriverPhases ( Phase(..), isHaskellSrcFilename )
274 import Finder
275 import HscTypes
276 import DynFlags
277 import StaticFlagParser
278 import qualified StaticFlags
279 import SysTools ( initSysTools, cleanTempFiles,
280 cleanTempDirs )
281 import Annotations
282 import Module
283 import UniqFM
284 import Panic
285 import Bag ( unitBag )
286 import ErrUtils
287 import MonadUtils
288 import Util
289 import StringBuffer
290 import Outputable
291 import BasicTypes
292 import Maybes ( expectJust )
293 import FastString
294 import qualified Parser
295 import Lexer
296
297 import System.Directory ( doesFileExist, getCurrentDirectory )
298 import Data.Maybe
299 import Data.List ( find )
300 import Data.Typeable ( Typeable )
301 import Data.Word ( Word8 )
302 import Control.Monad
303 import System.Exit ( exitWith, ExitCode(..) )
304 import System.Time ( getClockTime )
305 import Exception
306 import Data.IORef
307 import System.FilePath
308 import System.IO
309 import Prelude hiding (init)
310
311
312 -- %************************************************************************
313 -- %* *
314 -- Initialisation: exception handlers
315 -- %* *
316 -- %************************************************************************
317
318
319 -- | Install some default exception handlers and run the inner computation.
320 -- Unless you want to handle exceptions yourself, you should wrap this around
321 -- the top level of your program. The default handlers output the error
322 -- message(s) to stderr and exit cleanly.
323 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => LogAction -> m a -> m a
324 defaultErrorHandler la inner =
325 -- top-level exception handler: any unrecognised exception is a compiler bug.
326 ghandle (\exception -> liftIO $ do
327 hFlush stdout
328 case fromException exception of
329 -- an IO exception probably isn't our fault, so don't panic
330 Just (ioe :: IOException) ->
331 fatalErrorMsg' la (text (show ioe))
332 _ -> case fromException exception of
333 Just UserInterrupt -> exitWith (ExitFailure 1)
334 Just StackOverflow ->
335 fatalErrorMsg' la (text "stack overflow: use +RTS -K<size> to increase it")
336 _ -> case fromException exception of
337 Just (ex :: ExitCode) -> throw ex
338 _ ->
339 fatalErrorMsg' la
340 (text (show (Panic (show exception))))
341 exitWith (ExitFailure 1)
342 ) $
343
344 -- error messages propagated as exceptions
345 handleGhcException
346 (\ge -> liftIO $ do
347 hFlush stdout
348 case ge of
349 PhaseFailed _ code -> exitWith code
350 Signal _ -> exitWith (ExitFailure 1)
351 _ -> do fatalErrorMsg' la (text (show ge))
352 exitWith (ExitFailure 1)
353 ) $
354 inner
355
356 -- | Install a default cleanup handler to remove temporary files deposited by
357 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
358 -- want to override the error handling, but still get the ordinary cleanup
359 -- behaviour.
360 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
361 DynFlags -> m a -> m a
362 defaultCleanupHandler dflags inner =
363 -- make sure we clean up after ourselves
364 inner `gfinally`
365 (liftIO $ do
366 cleanTempFiles dflags
367 cleanTempDirs dflags
368 )
369 -- exceptions will be blocked while we clean the temporary files,
370 -- so there shouldn't be any difficulty if we receive further
371 -- signals.
372
373
374 -- %************************************************************************
375 -- %* *
376 -- The Ghc Monad
377 -- %* *
378 -- %************************************************************************
379
380 -- | Run function for the 'Ghc' monad.
381 --
382 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
383 -- to this function will create a new session which should not be shared among
384 -- several threads.
385 --
386 -- Any errors not handled inside the 'Ghc' action are propagated as IO
387 -- exceptions.
388
389 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
390 -> Ghc a -- ^ The action to perform.
391 -> IO a
392 runGhc mb_top_dir ghc = do
393 ref <- newIORef (panic "empty session")
394 let session = Session ref
395 flip unGhc session $ do
396 initGhcMonad mb_top_dir
397 ghc
398 -- XXX: unregister interrupt handlers here?
399
400 -- | Run function for 'GhcT' monad transformer.
401 --
402 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
403 -- to this function will create a new session which should not be shared among
404 -- several threads.
405
406 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
407 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
408 -> GhcT m a -- ^ The action to perform.
409 -> m a
410 runGhcT mb_top_dir ghct = do
411 ref <- liftIO $ newIORef (panic "empty session")
412 let session = Session ref
413 flip unGhcT session $ do
414 initGhcMonad mb_top_dir
415 ghct
416
417 -- | Initialise a GHC session.
418 --
419 -- If you implement a custom 'GhcMonad' you must call this function in the
420 -- monad run function. It will initialise the session variable and clear all
421 -- warnings.
422 --
423 -- The first argument should point to the directory where GHC's library files
424 -- reside. More precisely, this should be the output of @ghc --print-libdir@
425 -- of the version of GHC the module using this API is compiled with. For
426 -- portability, you should use the @ghc-paths@ package, available at
427 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
428
429 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
430 initGhcMonad mb_top_dir = do
431 -- catch ^C
432 liftIO $ installSignalHandlers
433
434 liftIO $ StaticFlags.initStaticOpts
435
436 mySettings <- liftIO $ initSysTools mb_top_dir
437 dflags <- liftIO $ initDynFlags (defaultDynFlags mySettings)
438 env <- liftIO $ newHscEnv dflags
439 setSession env
440
441
442 -- %************************************************************************
443 -- %* *
444 -- Flags & settings
445 -- %* *
446 -- %************************************************************************
447
448 -- | Updates the DynFlags in a Session. This also reads
449 -- the package database (unless it has already been read),
450 -- and prepares the compilers knowledge about packages. It
451 -- can be called again to load new packages: just add new
452 -- package flags to (packageFlags dflags).
453 --
454 -- Returns a list of new packages that may need to be linked in using
455 -- the dynamic linker (see 'linkPackages') as a result of new package
456 -- flags. If you are not doing linking or doing static linking, you
457 -- can ignore the list of packages returned.
458 --
459 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
460 setSessionDynFlags dflags = do
461 (dflags', preload) <- liftIO $ initPackages dflags
462 modifySession (\h -> h{ hsc_dflags = dflags' })
463 return preload
464
465
466 parseDynamicFlags :: Monad m =>
467 DynFlags -> [Located String]
468 -> m (DynFlags, [Located String], [Located String])
469 parseDynamicFlags = parseDynamicFlagsCmdLine
470
471
472 -- %************************************************************************
473 -- %* *
474 -- Setting, getting, and modifying the targets
475 -- %* *
476 -- %************************************************************************
477
478 -- ToDo: think about relative vs. absolute file paths. And what
479 -- happens when the current directory changes.
480
481 -- | Sets the targets for this session. Each target may be a module name
482 -- or a filename. The targets correspond to the set of root modules for
483 -- the program\/library. Unloading the current program is achieved by
484 -- setting the current set of targets to be empty, followed by 'load'.
485 setTargets :: GhcMonad m => [Target] -> m ()
486 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
487
488 -- | Returns the current set of targets
489 getTargets :: GhcMonad m => m [Target]
490 getTargets = withSession (return . hsc_targets)
491
492 -- | Add another target.
493 addTarget :: GhcMonad m => Target -> m ()
494 addTarget target
495 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
496
497 -- | Remove a target
498 removeTarget :: GhcMonad m => TargetId -> m ()
499 removeTarget target_id
500 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
501 where
502 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
503
504 -- | Attempts to guess what Target a string refers to. This function
505 -- implements the @--make@/GHCi command-line syntax for filenames:
506 --
507 -- - if the string looks like a Haskell source filename, then interpret it
508 -- as such
509 --
510 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
511 -- then use that
512 --
513 -- - otherwise interpret the string as a module name
514 --
515 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
516 guessTarget str (Just phase)
517 = return (Target (TargetFile str (Just phase)) True Nothing)
518 guessTarget str Nothing
519 | isHaskellSrcFilename file
520 = return (target (TargetFile file Nothing))
521 | otherwise
522 = do exists <- liftIO $ doesFileExist hs_file
523 if exists
524 then return (target (TargetFile hs_file Nothing))
525 else do
526 exists <- liftIO $ doesFileExist lhs_file
527 if exists
528 then return (target (TargetFile lhs_file Nothing))
529 else do
530 if looksLikeModuleName file
531 then return (target (TargetModule (mkModuleName file)))
532 else do
533 throwGhcException
534 (ProgramError (showSDoc $
535 text "target" <+> quotes (text file) <+>
536 text "is not a module name or a source file"))
537 where
538 (file,obj_allowed)
539 | '*':rest <- str = (rest, False)
540 | otherwise = (str, True)
541
542 hs_file = file <.> "hs"
543 lhs_file = file <.> "lhs"
544
545 target tid = Target tid obj_allowed Nothing
546
547
548 -- | Inform GHC that the working directory has changed. GHC will flush
549 -- its cache of module locations, since it may no longer be valid.
550 --
551 -- Note: Before changing the working directory make sure all threads running
552 -- in the same session have stopped. If you change the working directory,
553 -- you should also unload the current program (set targets to empty,
554 -- followed by load).
555 workingDirectoryChanged :: GhcMonad m => m ()
556 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
557
558
559 -- %************************************************************************
560 -- %* *
561 -- Running phases one at a time
562 -- %* *
563 -- %************************************************************************
564
565 class ParsedMod m where
566 modSummary :: m -> ModSummary
567 parsedSource :: m -> ParsedSource
568
569 class ParsedMod m => TypecheckedMod m where
570 renamedSource :: m -> Maybe RenamedSource
571 typecheckedSource :: m -> TypecheckedSource
572 moduleInfo :: m -> ModuleInfo
573 tm_internals :: m -> (TcGblEnv, ModDetails)
574 -- ToDo: improvements that could be made here:
575 -- if the module succeeded renaming but not typechecking,
576 -- we can still get back the GlobalRdrEnv and exports, so
577 -- perhaps the ModuleInfo should be split up into separate
578 -- fields.
579
580 class TypecheckedMod m => DesugaredMod m where
581 coreModule :: m -> ModGuts
582
583 -- | The result of successful parsing.
584 data ParsedModule =
585 ParsedModule { pm_mod_summary :: ModSummary
586 , pm_parsed_source :: ParsedSource }
587
588 instance ParsedMod ParsedModule where
589 modSummary m = pm_mod_summary m
590 parsedSource m = pm_parsed_source m
591
592 -- | The result of successful typechecking. It also contains the parser
593 -- result.
594 data TypecheckedModule =
595 TypecheckedModule { tm_parsed_module :: ParsedModule
596 , tm_renamed_source :: Maybe RenamedSource
597 , tm_typechecked_source :: TypecheckedSource
598 , tm_checked_module_info :: ModuleInfo
599 , tm_internals_ :: (TcGblEnv, ModDetails)
600 }
601
602 instance ParsedMod TypecheckedModule where
603 modSummary m = modSummary (tm_parsed_module m)
604 parsedSource m = parsedSource (tm_parsed_module m)
605
606 instance TypecheckedMod TypecheckedModule where
607 renamedSource m = tm_renamed_source m
608 typecheckedSource m = tm_typechecked_source m
609 moduleInfo m = tm_checked_module_info m
610 tm_internals m = tm_internals_ m
611
612 -- | The result of successful desugaring (i.e., translation to core). Also
613 -- contains all the information of a typechecked module.
614 data DesugaredModule =
615 DesugaredModule { dm_typechecked_module :: TypecheckedModule
616 , dm_core_module :: ModGuts
617 }
618
619 instance ParsedMod DesugaredModule where
620 modSummary m = modSummary (dm_typechecked_module m)
621 parsedSource m = parsedSource (dm_typechecked_module m)
622
623 instance TypecheckedMod DesugaredModule where
624 renamedSource m = renamedSource (dm_typechecked_module m)
625 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
626 moduleInfo m = moduleInfo (dm_typechecked_module m)
627 tm_internals m = tm_internals_ (dm_typechecked_module m)
628
629 instance DesugaredMod DesugaredModule where
630 coreModule m = dm_core_module m
631
632 type ParsedSource = Located (HsModule RdrName)
633 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
634 Maybe LHsDocString)
635 type TypecheckedSource = LHsBinds Id
636
637 -- NOTE:
638 -- - things that aren't in the output of the typechecker right now:
639 -- - the export list
640 -- - the imports
641 -- - type signatures
642 -- - type/data/newtype declarations
643 -- - class declarations
644 -- - instances
645 -- - extra things in the typechecker's output:
646 -- - default methods are turned into top-level decls.
647 -- - dictionary bindings
648
649 -- | Return the 'ModSummary' of a module with the given name.
650 --
651 -- The module must be part of the module graph (see 'hsc_mod_graph' and
652 -- 'ModuleGraph'). If this is not the case, this function will throw a
653 -- 'GhcApiError'.
654 --
655 -- This function ignores boot modules and requires that there is only one
656 -- non-boot module with the given name.
657 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
658 getModSummary mod = do
659 mg <- liftM hsc_mod_graph getSession
660 case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
661 [] -> throw $ mkApiErr (text "Module not part of module graph")
662 [ms] -> return ms
663 multiple -> throw $ mkApiErr (text "getModSummary is ambiguous: " <+> ppr multiple)
664
665 -- | Parse a module.
666 --
667 -- Throws a 'SourceError' on parse error.
668 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
669 parseModule ms = do
670 hsc_env <- getSession
671 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
672 rdr_module <- liftIO $ hscParse hsc_env_tmp ms
673 return (ParsedModule ms rdr_module)
674
675 -- | Typecheck and rename a parsed module.
676 --
677 -- Throws a 'SourceError' if either fails.
678 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
679 typecheckModule pmod = do
680 let ms = modSummary pmod
681 hsc_env <- getSession
682 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
683 (tc_gbl_env, rn_info)
684 <- liftIO $ hscTypecheckRename hsc_env_tmp ms (parsedSource pmod)
685 details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env
686 return $
687 TypecheckedModule {
688 tm_internals_ = (tc_gbl_env, details),
689 tm_parsed_module = pmod,
690 tm_renamed_source = rn_info,
691 tm_typechecked_source = tcg_binds tc_gbl_env,
692 tm_checked_module_info =
693 ModuleInfo {
694 minf_type_env = md_types details,
695 minf_exports = availsToNameSet $ md_exports details,
696 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
697 minf_instances = md_insts details,
698 minf_iface = Nothing
699 #ifdef GHCI
700 ,minf_modBreaks = emptyModBreaks
701 #endif
702 }}
703
704 -- | Desugar a typechecked module.
705 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
706 desugarModule tcm = do
707 let ms = modSummary tcm
708 let (tcg, _) = tm_internals tcm
709 hsc_env <- getSession
710 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
711 guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg
712 return $
713 DesugaredModule {
714 dm_typechecked_module = tcm,
715 dm_core_module = guts
716 }
717
718 -- | Load a module. Input doesn't need to be desugared.
719 --
720 -- A module must be loaded before dependent modules can be typechecked. This
721 -- always includes generating a 'ModIface' and, depending on the
722 -- 'DynFlags.hscTarget', may also include code generation.
723 --
724 -- This function will always cause recompilation and will always overwrite
725 -- previous compilation results (potentially files on disk).
726 --
727 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
728 loadModule tcm = do
729 let ms = modSummary tcm
730 let mod = ms_mod_name ms
731 let loc = ms_location ms
732 let (tcg, _details) = tm_internals tcm
733
734 mb_linkable <- case ms_obj_date ms of
735 Just t | t > ms_hs_date ms -> do
736 l <- liftIO $ findObjectLinkable (ms_mod ms)
737 (ml_obj_file loc) t
738 return (Just l)
739 _otherwise -> return Nothing
740
741 let source_modified | isNothing mb_linkable = SourceModified
742 | otherwise = SourceUnmodified
743 -- we can't determine stability here
744
745 -- compile doesn't change the session
746 hsc_env <- getSession
747 mod_info <- liftIO $ compile' (hscNothingBackendOnly tcg,
748 hscInteractiveBackendOnly tcg,
749 hscBatchBackendOnly tcg)
750 hsc_env ms 1 1 Nothing mb_linkable
751 source_modified
752
753 modifySession $ \e -> e{ hsc_HPT = addToUFM (hsc_HPT e) mod mod_info }
754 return tcm
755
756
757 -- %************************************************************************
758 -- %* *
759 -- Dealing with Core
760 -- %* *
761 -- %************************************************************************
762
763 -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
764 -- the 'GHC.compileToCoreModule' interface.
765 data CoreModule
766 = CoreModule {
767 -- | Module name
768 cm_module :: !Module,
769 -- | Type environment for types declared in this module
770 cm_types :: !TypeEnv,
771 -- | Declarations
772 cm_binds :: [CoreBind]
773 }
774
775 instance Outputable CoreModule where
776 ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb}) =
777 text "%module" <+> ppr mn <+> ppr te $$ vcat (map ppr cb)
778
779 -- | This is the way to get access to the Core bindings corresponding
780 -- to a module. 'compileToCore' parses, typechecks, and
781 -- desugars the module, then returns the resulting Core module (consisting of
782 -- the module name, type declarations, and function declarations) if
783 -- successful.
784 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
785 compileToCoreModule = compileCore False
786
787 -- | Like compileToCoreModule, but invokes the simplifier, so
788 -- as to return simplified and tidied Core.
789 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
790 compileToCoreSimplified = compileCore True
791 {-
792 -- | Provided for backwards-compatibility: compileToCore returns just the Core
793 -- bindings, but for most purposes, you probably want to call
794 -- compileToCoreModule.
795 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
796 compileToCore fn = do
797 mod <- compileToCoreModule session fn
798 return $ cm_binds mod
799 -}
800 -- | Takes a CoreModule and compiles the bindings therein
801 -- to object code. The first argument is a bool flag indicating
802 -- whether to run the simplifier.
803 -- The resulting .o, .hi, and executable files, if any, are stored in the
804 -- current directory, and named according to the module name.
805 -- This has only so far been tested with a single self-contained module.
806 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
807 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
808 dflags <- getSessionDynFlags
809 currentTime <- liftIO $ getClockTime
810 cwd <- liftIO $ getCurrentDirectory
811 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
812 ((moduleNameSlashes . moduleName) mName)
813
814 let modSummary = ModSummary { ms_mod = mName,
815 ms_hsc_src = ExtCoreFile,
816 ms_location = modLocation,
817 -- By setting the object file timestamp to Nothing,
818 -- we always force recompilation, which is what we
819 -- want. (Thus it doesn't matter what the timestamp
820 -- for the (nonexistent) source file is.)
821 ms_hs_date = currentTime,
822 ms_obj_date = Nothing,
823 -- Only handling the single-module case for now, so no imports.
824 ms_srcimps = [],
825 ms_textual_imps = [],
826 -- No source file
827 ms_hspp_file = "",
828 ms_hspp_opts = dflags,
829 ms_hspp_buf = Nothing
830 }
831
832 hsc_env <- getSession
833 liftIO $ hscCompileCore hsc_env simplify modSummary (cm_binds cm)
834
835
836 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
837 compileCore simplify fn = do
838 -- First, set the target to the desired filename
839 target <- guessTarget fn Nothing
840 addTarget target
841 _ <- load LoadAllTargets
842 -- Then find dependencies
843 modGraph <- depanal [] True
844 case find ((== fn) . msHsFilePath) modGraph of
845 Just modSummary -> do
846 -- Now we have the module name;
847 -- parse, typecheck and desugar the module
848 mod_guts <- coreModule `fmap`
849 -- TODO: space leaky: call hsc* directly?
850 (desugarModule =<< typecheckModule =<< parseModule modSummary)
851 liftM gutsToCoreModule $
852 if simplify
853 then do
854 -- If simplify is true: simplify (hscSimplify), then tidy
855 -- (tidyProgram).
856 hsc_env <- getSession
857 simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts
858 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
859 return $ Left tidy_guts
860 else
861 return $ Right mod_guts
862
863 Nothing -> panic "compileToCoreModule: target FilePath not found in\
864 module dependency graph"
865 where -- two versions, based on whether we simplify (thus run tidyProgram,
866 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
867 -- we just have a ModGuts.
868 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
869 gutsToCoreModule (Left (cg, md)) = CoreModule {
870 cm_module = cg_module cg,
871 cm_types = md_types md,
872 cm_binds = cg_binds cg
873 }
874 gutsToCoreModule (Right mg) = CoreModule {
875 cm_module = mg_module mg,
876 cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg))
877 (mg_tcs mg) (mg_clss mg)
878 (mg_fam_insts mg),
879 cm_binds = mg_binds mg
880 }
881
882 -- %************************************************************************
883 -- %* *
884 -- Inspecting the session
885 -- %* *
886 -- %************************************************************************
887
888 -- | Get the module dependency graph.
889 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
890 getModuleGraph = liftM hsc_mod_graph getSession
891
892 -- | Determines whether a set of modules requires Template Haskell.
893 --
894 -- Note that if the session's 'DynFlags' enabled Template Haskell when
895 -- 'depanal' was called, then each module in the returned module graph will
896 -- have Template Haskell enabled whether it is actually needed or not.
897 needsTemplateHaskell :: ModuleGraph -> Bool
898 needsTemplateHaskell ms =
899 any (xopt Opt_TemplateHaskell . ms_hspp_opts) ms
900
901 -- | Return @True@ <==> module is loaded.
902 isLoaded :: GhcMonad m => ModuleName -> m Bool
903 isLoaded m = withSession $ \hsc_env ->
904 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
905
906 -- | Return the bindings for the current interactive session.
907 getBindings :: GhcMonad m => m [TyThing]
908 getBindings = withSession $ \hsc_env ->
909 return $ icInScopeTTs $ hsc_IC hsc_env
910
911 -- | Return the instances for the current interactive session.
912 getInsts :: GhcMonad m => m ([Instance], [FamInst])
913 getInsts = withSession $ \hsc_env ->
914 return $ ic_instances (hsc_IC hsc_env)
915
916 getPrintUnqual :: GhcMonad m => m PrintUnqualified
917 getPrintUnqual = withSession $ \hsc_env ->
918 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
919
920 -- | Container for information about a 'Module'.
921 data ModuleInfo = ModuleInfo {
922 minf_type_env :: TypeEnv,
923 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
924 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
925 minf_instances :: [Instance],
926 minf_iface :: Maybe ModIface
927 #ifdef GHCI
928 ,minf_modBreaks :: ModBreaks
929 #endif
930 }
931 -- We don't want HomeModInfo here, because a ModuleInfo applies
932 -- to package modules too.
933
934 -- | Request information about a loaded 'Module'
935 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
936 getModuleInfo mdl = withSession $ \hsc_env -> do
937 let mg = hsc_mod_graph hsc_env
938 if mdl `elem` map ms_mod mg
939 then liftIO $ getHomeModuleInfo hsc_env mdl
940 else do
941 {- if isHomeModule (hsc_dflags hsc_env) mdl
942 then return Nothing
943 else -} liftIO $ getPackageModuleInfo hsc_env mdl
944 -- ToDo: we don't understand what the following comment means.
945 -- (SDM, 19/7/2011)
946 -- getPackageModuleInfo will attempt to find the interface, so
947 -- we don't want to call it for a home module, just in case there
948 -- was a problem loading the module and the interface doesn't
949 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
950
951 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
952 #ifdef GHCI
953 getPackageModuleInfo hsc_env mdl
954 = do eps <- hscEPS hsc_env
955 iface <- hscGetModuleInterface hsc_env mdl
956 let
957 avails = mi_exports iface
958 names = availsToNameSet avails
959 pte = eps_PTE eps
960 tys = [ ty | name <- concatMap availNames avails,
961 Just ty <- [lookupTypeEnv pte name] ]
962 --
963 return (Just (ModuleInfo {
964 minf_type_env = mkTypeEnv tys,
965 minf_exports = names,
966 minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
967 minf_instances = error "getModuleInfo: instances for package module unimplemented",
968 minf_iface = Just iface,
969 minf_modBreaks = emptyModBreaks
970 }))
971 #else
972 -- bogusly different for non-GHCI (ToDo)
973 getPackageModuleInfo _hsc_env _mdl = do
974 return Nothing
975 #endif
976
977 getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
978 getHomeModuleInfo hsc_env mdl =
979 case lookupUFM (hsc_HPT hsc_env) (moduleName mdl) of
980 Nothing -> return Nothing
981 Just hmi -> do
982 let details = hm_details hmi
983 iface = hm_iface hmi
984 return (Just (ModuleInfo {
985 minf_type_env = md_types details,
986 minf_exports = availsToNameSet (md_exports details),
987 minf_rdr_env = mi_globals $! hm_iface hmi,
988 minf_instances = md_insts details,
989 minf_iface = Just iface
990 #ifdef GHCI
991 ,minf_modBreaks = getModBreaks hmi
992 #endif
993 }))
994
995 -- | The list of top-level entities defined in a module
996 modInfoTyThings :: ModuleInfo -> [TyThing]
997 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
998
999 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1000 modInfoTopLevelScope minf
1001 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1002
1003 modInfoExports :: ModuleInfo -> [Name]
1004 modInfoExports minf = nameSetToList $! minf_exports minf
1005
1006 -- | Returns the instances defined by the specified module.
1007 -- Warning: currently unimplemented for package modules.
1008 modInfoInstances :: ModuleInfo -> [Instance]
1009 modInfoInstances = minf_instances
1010
1011 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1012 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1013
1014 mkPrintUnqualifiedForModule :: GhcMonad m =>
1015 ModuleInfo
1016 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
1017 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
1018 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
1019
1020 modInfoLookupName :: GhcMonad m =>
1021 ModuleInfo -> Name
1022 -> m (Maybe TyThing) -- XXX: returns a Maybe X
1023 modInfoLookupName minf name = withSession $ \hsc_env -> do
1024 case lookupTypeEnv (minf_type_env minf) name of
1025 Just tyThing -> return (Just tyThing)
1026 Nothing -> do
1027 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
1028 return $! lookupType (hsc_dflags hsc_env)
1029 (hsc_HPT hsc_env) (eps_PTE eps) name
1030
1031 modInfoIface :: ModuleInfo -> Maybe ModIface
1032 modInfoIface = minf_iface
1033
1034 #ifdef GHCI
1035 modInfoModBreaks :: ModuleInfo -> ModBreaks
1036 modInfoModBreaks = minf_modBreaks
1037 #endif
1038
1039 isDictonaryId :: Id -> Bool
1040 isDictonaryId id
1041 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
1042
1043 -- | Looks up a global name: that is, any top-level name in any
1044 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1045 -- the interactive context, and therefore does not require a preceding
1046 -- 'setContext'.
1047 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
1048 lookupGlobalName name = withSession $ \hsc_env -> do
1049 liftIO $ lookupTypeHscEnv hsc_env name
1050
1051 findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
1052 findGlobalAnns deserialize target = withSession $ \hsc_env -> do
1053 ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
1054 return (findAnns deserialize ann_env target)
1055
1056 #ifdef GHCI
1057 -- | get the GlobalRdrEnv for a session
1058 getGRE :: GhcMonad m => m GlobalRdrEnv
1059 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
1060 #endif
1061
1062 -- -----------------------------------------------------------------------------
1063
1064 -- | Return all /external/ modules available in the package database.
1065 -- Modules from the current session (i.e., from the 'HomePackageTable') are
1066 -- not included.
1067 packageDbModules :: GhcMonad m =>
1068 Bool -- ^ Only consider exposed packages.
1069 -> m [Module]
1070 packageDbModules only_exposed = do
1071 dflags <- getSessionDynFlags
1072 let pkgs = eltsUFM (pkgIdMap (pkgState dflags))
1073 return $
1074 [ mkModule pid modname | p <- pkgs
1075 , not only_exposed || exposed p
1076 , let pid = packageConfigId p
1077 , modname <- exposedModules p ]
1078
1079 -- -----------------------------------------------------------------------------
1080 -- Misc exported utils
1081
1082 dataConType :: DataCon -> Type
1083 dataConType dc = idType (dataConWrapId dc)
1084
1085 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1086 pprParenSymName :: NamedThing a => a -> SDoc
1087 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1088
1089 -- ----------------------------------------------------------------------------
1090
1091 #if 0
1092
1093 -- ToDo:
1094 -- - Data and Typeable instances for HsSyn.
1095
1096 -- ToDo: check for small transformations that happen to the syntax in
1097 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1098
1099 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1100 -- to get from TyCons, Ids etc. to TH syntax (reify).
1101
1102 -- :browse will use either lm_toplev or inspect lm_interface, depending
1103 -- on whether the module is interpreted or not.
1104
1105 #endif
1106
1107 -- Extract the filename, stringbuffer content and dynflags associed to a module
1108 --
1109 -- XXX: Explain pre-conditions
1110 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
1111 getModuleSourceAndFlags mod = do
1112 m <- getModSummary (moduleName mod)
1113 case ml_hs_file $ ms_location m of
1114 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
1115 Just sourceFile -> do
1116 source <- liftIO $ hGetStringBuffer sourceFile
1117 return (sourceFile, source, ms_hspp_opts m)
1118
1119
1120 -- | Return module source as token stream, including comments.
1121 --
1122 -- The module must be in the module graph and its source must be available.
1123 -- Throws a 'HscTypes.SourceError' on parse error.
1124 getTokenStream :: GhcMonad m => Module -> m [Located Token]
1125 getTokenStream mod = do
1126 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1127 let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
1128 case lexTokenStream source startLoc flags of
1129 POk _ ts -> return ts
1130 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
1131
1132 -- | Give even more information on the source than 'getTokenStream'
1133 -- This function allows reconstructing the source completely with
1134 -- 'showRichTokenStream'.
1135 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
1136 getRichTokenStream mod = do
1137 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1138 let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
1139 case lexTokenStream source startLoc flags of
1140 POk _ ts -> return $ addSourceToTokens startLoc source ts
1141 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
1142
1143 -- | Given a source location and a StringBuffer corresponding to this
1144 -- location, return a rich token stream with the source associated to the
1145 -- tokens.
1146 addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token]
1147 -> [(Located Token, String)]
1148 addSourceToTokens _ _ [] = []
1149 addSourceToTokens loc buf (t@(L span _) : ts)
1150 = case span of
1151 UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts
1152 RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts
1153 where
1154 (newLoc, newBuf, str) = go "" loc buf
1155 start = realSrcSpanStart s
1156 end = realSrcSpanEnd s
1157 go acc loc buf | loc < start = go acc nLoc nBuf
1158 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
1159 | otherwise = (loc, buf, reverse acc)
1160 where (ch, nBuf) = nextChar buf
1161 nLoc = advanceSrcLoc loc ch
1162
1163
1164 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
1165 -- return source code almost identical to the original code (except for
1166 -- insignificant whitespace.)
1167 showRichTokenStream :: [(Located Token, String)] -> String
1168 showRichTokenStream ts = go startLoc ts ""
1169 where sourceFile = getFile $ map (getLoc . fst) ts
1170 getFile [] = panic "showRichTokenStream: No source file found"
1171 getFile (UnhelpfulSpan _ : xs) = getFile xs
1172 getFile (RealSrcSpan s : _) = srcSpanFile s
1173 startLoc = mkRealSrcLoc sourceFile 1 1
1174 go _ [] = id
1175 go loc ((L span _, str):ts)
1176 = case span of
1177 UnhelpfulSpan _ -> go loc ts
1178 RealSrcSpan s
1179 | locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
1180 . (str ++)
1181 . go tokEnd ts
1182 | otherwise -> ((replicate (tokLine - locLine) '\n') ++)
1183 . ((replicate tokCol ' ') ++)
1184 . (str ++)
1185 . go tokEnd ts
1186 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
1187 (tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
1188 tokEnd = realSrcSpanEnd s
1189
1190 -- -----------------------------------------------------------------------------
1191 -- Interactive evaluation
1192
1193 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1194 -- filesystem and package database to find the corresponding 'Module',
1195 -- using the algorithm that is used for an @import@ declaration.
1196 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1197 findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
1198 let
1199 dflags = hsc_dflags hsc_env
1200 this_pkg = thisPackage dflags
1201 --
1202 case maybe_pkg of
1203 Just pkg | fsToPackageId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
1204 res <- findImportedModule hsc_env mod_name maybe_pkg
1205 case res of
1206 Found _ m -> return m
1207 err -> noModError dflags noSrcSpan mod_name err
1208 _otherwise -> do
1209 home <- lookupLoadedHomeModule mod_name
1210 case home of
1211 Just m -> return m
1212 Nothing -> liftIO $ do
1213 res <- findImportedModule hsc_env mod_name maybe_pkg
1214 case res of
1215 Found loc m | modulePackageId m /= this_pkg -> return m
1216 | otherwise -> modNotLoadedError m loc
1217 err -> noModError dflags noSrcSpan mod_name err
1218
1219 modNotLoadedError :: Module -> ModLocation -> IO a
1220 modNotLoadedError m loc = ghcError $ CmdLineError $ showSDoc $
1221 text "module is not loaded:" <+>
1222 quotes (ppr (moduleName m)) <+>
1223 parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
1224
1225 -- | Like 'findModule', but differs slightly when the module refers to
1226 -- a source file, and the file has not been loaded via 'load'. In
1227 -- this case, 'findModule' will throw an error (module not loaded),
1228 -- but 'lookupModule' will check to see whether the module can also be
1229 -- found in a package, and if so, that package 'Module' will be
1230 -- returned. If not, the usual module-not-found error will be thrown.
1231 --
1232 lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1233 lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
1234 lookupModule mod_name Nothing = withSession $ \hsc_env -> do
1235 home <- lookupLoadedHomeModule mod_name
1236 case home of
1237 Just m -> return m
1238 Nothing -> liftIO $ do
1239 res <- findExposedPackageModule hsc_env mod_name Nothing
1240 case res of
1241 Found _ m -> return m
1242 err -> noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
1243
1244 lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
1245 lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
1246 case lookupUFM (hsc_HPT hsc_env) mod_name of
1247 Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
1248 _not_a_home_module -> return Nothing
1249
1250 #ifdef GHCI
1251 getHistorySpan :: GhcMonad m => History -> m SrcSpan
1252 getHistorySpan h = withSession $ \hsc_env ->
1253 return$ InteractiveEval.getHistorySpan hsc_env h
1254
1255 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
1256 obtainTermFromVal bound force ty a =
1257 withSession $ \hsc_env ->
1258 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
1259
1260 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
1261 obtainTermFromId bound force id =
1262 withSession $ \hsc_env ->
1263 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id
1264
1265 #endif
1266
1267 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1268 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1269 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
1270 lookupName name =
1271 withSession $ \hsc_env ->
1272 liftIO $ hscTcRcLookupName hsc_env name
1273
1274 -- -----------------------------------------------------------------------------
1275 -- Pure API
1276
1277 -- | A pure interface to the module parser.
1278 --
1279 parser :: String -- ^ Haskell module source text (full Unicode is supported)
1280 -> DynFlags -- ^ the flags
1281 -> FilePath -- ^ the filename (for source locations)
1282 -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
1283
1284 parser str dflags filename =
1285 let
1286 loc = mkRealSrcLoc (mkFastString filename) 1 1
1287 buf = stringToStringBuffer str
1288 in
1289 case unP Parser.parseModule (mkPState dflags buf loc) of
1290
1291 PFailed span err ->
1292 Left (unitBag (mkPlainErrMsg span err))
1293
1294 POk pst rdr_module ->
1295 let (warns,_) = getMessages pst in
1296 Right (warns, rdr_module)