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