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