Merge branch 'master' of http://darcs.haskell.org/ghc
[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 do
932 {- if isHomeModule (hsc_dflags hsc_env) mdl
933 then return Nothing
934 else -} liftIO $ getPackageModuleInfo hsc_env mdl
935 -- getPackageModuleInfo will attempt to find the interface, so
936 -- we don't want to call it for a home module, just in case there
937 -- was a problem loading the module and the interface doesn't
938 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
939
940 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
941 #ifdef GHCI
942 getPackageModuleInfo hsc_env mdl = do
943 mb_avails <- hscGetModuleExports hsc_env mdl
944 -- This is the only use of hscGetModuleExports. Perhaps we could use
945 -- hscRnImportDecls instead, but that does a lot more than we need
946 -- (building instance environment, checking family instance consistency
947 -- etc.).
948 case mb_avails of
949 Nothing -> return Nothing
950 Just avails -> do
951 eps <- hscEPS hsc_env
952 iface <- lookupModuleIface hsc_env mdl
953 let
954 names = availsToNameSet avails
955 pte = eps_PTE eps
956 tys = [ ty | name <- concatMap availNames avails,
957 Just ty <- [lookupTypeEnv pte name] ]
958 --
959 return (Just (ModuleInfo {
960 minf_type_env = mkTypeEnv tys,
961 minf_exports = names,
962 minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
963 minf_instances = error "getModuleInfo: instances for package module unimplemented",
964 minf_iface = iface,
965 minf_modBreaks = emptyModBreaks
966 }))
967 #else
968 -- bogusly different for non-GHCI (ToDo)
969 getPackageModuleInfo _hsc_env _mdl = do
970 return Nothing
971 #endif
972
973 getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
974 getHomeModuleInfo hsc_env mdl =
975 case lookupUFM (hsc_HPT hsc_env) (moduleName mdl) of
976 Nothing -> return Nothing
977 Just hmi -> do
978 let details = hm_details hmi
979 iface <- lookupModuleIface hsc_env mdl
980 return (Just (ModuleInfo {
981 minf_type_env = md_types details,
982 minf_exports = availsToNameSet (md_exports details),
983 minf_rdr_env = mi_globals $! hm_iface hmi,
984 minf_instances = md_insts details,
985 minf_iface = iface
986 #ifdef GHCI
987 ,minf_modBreaks = getModBreaks hmi
988 #endif
989 }))
990
991 lookupModuleIface :: HscEnv -> Module -> IO (Maybe ModIface)
992 lookupModuleIface env m = do
993 eps <- hscEPS env
994 let dflags = hsc_dflags env
995 pkgIfaceT = eps_PIT eps
996 homePkgT = hsc_HPT env
997 iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
998 return iface
999
1000 -- | The list of top-level entities defined in a module
1001 modInfoTyThings :: ModuleInfo -> [TyThing]
1002 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1003
1004 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1005 modInfoTopLevelScope minf
1006 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1007
1008 modInfoExports :: ModuleInfo -> [Name]
1009 modInfoExports minf = nameSetToList $! minf_exports minf
1010
1011 -- | Returns the instances defined by the specified module.
1012 -- Warning: currently unimplemented for package modules.
1013 modInfoInstances :: ModuleInfo -> [Instance]
1014 modInfoInstances = minf_instances
1015
1016 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1017 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1018
1019 mkPrintUnqualifiedForModule :: GhcMonad m =>
1020 ModuleInfo
1021 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
1022 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
1023 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
1024
1025 modInfoLookupName :: GhcMonad m =>
1026 ModuleInfo -> Name
1027 -> m (Maybe TyThing) -- XXX: returns a Maybe X
1028 modInfoLookupName minf name = withSession $ \hsc_env -> do
1029 case lookupTypeEnv (minf_type_env minf) name of
1030 Just tyThing -> return (Just tyThing)
1031 Nothing -> do
1032 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
1033 return $! lookupType (hsc_dflags hsc_env)
1034 (hsc_HPT hsc_env) (eps_PTE eps) name
1035
1036 modInfoIface :: ModuleInfo -> Maybe ModIface
1037 modInfoIface = minf_iface
1038
1039 #ifdef GHCI
1040 modInfoModBreaks :: ModuleInfo -> ModBreaks
1041 modInfoModBreaks = minf_modBreaks
1042 #endif
1043
1044 isDictonaryId :: Id -> Bool
1045 isDictonaryId id
1046 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
1047
1048 -- | Looks up a global name: that is, any top-level name in any
1049 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1050 -- the interactive context, and therefore does not require a preceding
1051 -- 'setContext'.
1052 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
1053 lookupGlobalName name = withSession $ \hsc_env -> do
1054 liftIO $ lookupTypeHscEnv hsc_env name
1055
1056 findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
1057 findGlobalAnns deserialize target = withSession $ \hsc_env -> do
1058 ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
1059 return (findAnns deserialize ann_env target)
1060
1061 #ifdef GHCI
1062 -- | get the GlobalRdrEnv for a session
1063 getGRE :: GhcMonad m => m GlobalRdrEnv
1064 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
1065 #endif
1066
1067 -- -----------------------------------------------------------------------------
1068
1069 -- | Return all /external/ modules available in the package database.
1070 -- Modules from the current session (i.e., from the 'HomePackageTable') are
1071 -- not included.
1072 packageDbModules :: GhcMonad m =>
1073 Bool -- ^ Only consider exposed packages.
1074 -> m [Module]
1075 packageDbModules only_exposed = do
1076 dflags <- getSessionDynFlags
1077 let pkgs = eltsUFM (pkgIdMap (pkgState dflags))
1078 return $
1079 [ mkModule pid modname | p <- pkgs
1080 , not only_exposed || exposed p
1081 , let pid = packageConfigId p
1082 , modname <- exposedModules p ]
1083
1084 -- -----------------------------------------------------------------------------
1085 -- Misc exported utils
1086
1087 dataConType :: DataCon -> Type
1088 dataConType dc = idType (dataConWrapId dc)
1089
1090 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1091 pprParenSymName :: NamedThing a => a -> SDoc
1092 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1093
1094 -- ----------------------------------------------------------------------------
1095
1096 #if 0
1097
1098 -- ToDo:
1099 -- - Data and Typeable instances for HsSyn.
1100
1101 -- ToDo: check for small transformations that happen to the syntax in
1102 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1103
1104 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1105 -- to get from TyCons, Ids etc. to TH syntax (reify).
1106
1107 -- :browse will use either lm_toplev or inspect lm_interface, depending
1108 -- on whether the module is interpreted or not.
1109
1110 #endif
1111
1112 -- Extract the filename, stringbuffer content and dynflags associed to a module
1113 --
1114 -- XXX: Explain pre-conditions
1115 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
1116 getModuleSourceAndFlags mod = do
1117 m <- getModSummary (moduleName mod)
1118 case ml_hs_file $ ms_location m of
1119 Nothing -> throw $ mkApiErr (text "No source available for module " <+> ppr mod)
1120 Just sourceFile -> do
1121 source <- liftIO $ hGetStringBuffer sourceFile
1122 return (sourceFile, source, ms_hspp_opts m)
1123
1124
1125 -- | Return module source as token stream, including comments.
1126 --
1127 -- The module must be in the module graph and its source must be available.
1128 -- Throws a 'HscTypes.SourceError' on parse error.
1129 getTokenStream :: GhcMonad m => Module -> m [Located Token]
1130 getTokenStream mod = do
1131 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1132 let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
1133 case lexTokenStream source startLoc flags of
1134 POk _ ts -> return ts
1135 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
1136
1137 -- | Give even more information on the source than 'getTokenStream'
1138 -- This function allows reconstructing the source completely with
1139 -- 'showRichTokenStream'.
1140 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
1141 getRichTokenStream mod = do
1142 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1143 let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
1144 case lexTokenStream source startLoc flags of
1145 POk _ ts -> return $ addSourceToTokens startLoc source ts
1146 PFailed span err -> throw $ mkSrcErr (unitBag $ mkPlainErrMsg span err)
1147
1148 -- | Given a source location and a StringBuffer corresponding to this
1149 -- location, return a rich token stream with the source associated to the
1150 -- tokens.
1151 addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token]
1152 -> [(Located Token, String)]
1153 addSourceToTokens _ _ [] = []
1154 addSourceToTokens loc buf (t@(L span _) : ts)
1155 = case span of
1156 UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts
1157 RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts
1158 where
1159 (newLoc, newBuf, str) = go "" loc buf
1160 start = realSrcSpanStart s
1161 end = realSrcSpanEnd s
1162 go acc loc buf | loc < start = go acc nLoc nBuf
1163 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
1164 | otherwise = (loc, buf, reverse acc)
1165 where (ch, nBuf) = nextChar buf
1166 nLoc = advanceSrcLoc loc ch
1167
1168
1169 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
1170 -- return source code almost identical to the original code (except for
1171 -- insignificant whitespace.)
1172 showRichTokenStream :: [(Located Token, String)] -> String
1173 showRichTokenStream ts = go startLoc ts ""
1174 where sourceFile = getFile $ map (getLoc . fst) ts
1175 getFile [] = panic "showRichTokenStream: No source file found"
1176 getFile (UnhelpfulSpan _ : xs) = getFile xs
1177 getFile (RealSrcSpan s : _) = srcSpanFile s
1178 startLoc = mkRealSrcLoc sourceFile 1 1
1179 go _ [] = id
1180 go loc ((L span _, str):ts)
1181 = case span of
1182 UnhelpfulSpan _ -> go loc ts
1183 RealSrcSpan s
1184 | locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
1185 . (str ++)
1186 . go tokEnd ts
1187 | otherwise -> ((replicate (tokLine - locLine) '\n') ++)
1188 . ((replicate tokCol ' ') ++)
1189 . (str ++)
1190 . go tokEnd ts
1191 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
1192 (tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
1193 tokEnd = realSrcSpanEnd s
1194
1195 -- -----------------------------------------------------------------------------
1196 -- Interactive evaluation
1197
1198 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1199 -- filesystem and package database to find the corresponding 'Module',
1200 -- using the algorithm that is used for an @import@ declaration.
1201 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1202 findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
1203 let
1204 dflags = hsc_dflags hsc_env
1205 this_pkg = thisPackage dflags
1206 --
1207 case maybe_pkg of
1208 Just pkg | fsToPackageId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
1209 res <- findImportedModule hsc_env mod_name maybe_pkg
1210 case res of
1211 Found _ m -> return m
1212 err -> noModError dflags noSrcSpan mod_name err
1213 _otherwise -> do
1214 home <- lookupLoadedHomeModule mod_name
1215 case home of
1216 Just m -> return m
1217 Nothing -> liftIO $ do
1218 res <- findImportedModule hsc_env mod_name maybe_pkg
1219 case res of
1220 Found loc m | modulePackageId m /= this_pkg -> return m
1221 | otherwise -> modNotLoadedError m loc
1222 err -> noModError dflags noSrcSpan mod_name err
1223
1224 modNotLoadedError :: Module -> ModLocation -> IO a
1225 modNotLoadedError m loc = ghcError $ CmdLineError $ showSDoc $
1226 text "module is not loaded:" <+>
1227 quotes (ppr (moduleName m)) <+>
1228 parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
1229
1230 -- | Like 'findModule', but differs slightly when the module refers to
1231 -- a source file, and the file has not been loaded via 'load'. In
1232 -- this case, 'findModule' will throw an error (module not loaded),
1233 -- but 'lookupModule' will check to see whether the module can also be
1234 -- found in a package, and if so, that package 'Module' will be
1235 -- returned. If not, the usual module-not-found error will be thrown.
1236 --
1237 lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1238 lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
1239 lookupModule mod_name Nothing = withSession $ \hsc_env -> do
1240 home <- lookupLoadedHomeModule mod_name
1241 case home of
1242 Just m -> return m
1243 Nothing -> liftIO $ do
1244 res <- findExposedPackageModule hsc_env mod_name Nothing
1245 case res of
1246 Found _ m -> return m
1247 err -> noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
1248
1249 lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
1250 lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
1251 case lookupUFM (hsc_HPT hsc_env) mod_name of
1252 Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
1253 _not_a_home_module -> return Nothing
1254
1255 #ifdef GHCI
1256 getHistorySpan :: GhcMonad m => History -> m SrcSpan
1257 getHistorySpan h = withSession $ \hsc_env ->
1258 return$ InteractiveEval.getHistorySpan hsc_env h
1259
1260 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
1261 obtainTermFromVal bound force ty a =
1262 withSession $ \hsc_env ->
1263 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
1264
1265 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
1266 obtainTermFromId bound force id =
1267 withSession $ \hsc_env ->
1268 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id
1269
1270 #endif
1271
1272 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1273 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1274 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
1275 lookupName name =
1276 withSession $ \hsc_env ->
1277 liftIO $ hscTcRcLookupName hsc_env name
1278
1279 -- -----------------------------------------------------------------------------
1280 -- Pure API
1281
1282 -- | A pure interface to the module parser.
1283 --
1284 parser :: String -- ^ Haskell module source text (full Unicode is supported)
1285 -> DynFlags -- ^ the flags
1286 -> FilePath -- ^ the filename (for source locations)
1287 -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
1288
1289 parser str dflags filename =
1290 let
1291 loc = mkRealSrcLoc (mkFastString filename) 1 1
1292 buf = stringToStringBuffer str
1293 in
1294 case unP Parser.parseModule (mkPState dflags buf loc) of
1295
1296 PFailed span err ->
1297 Left (unitBag (mkPlainErrMsg span err))
1298
1299 POk pst rdr_module ->
1300 let (warns,_) = getMessages pst in
1301 Right (warns, rdr_module)