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 {-# OPTIONS -fno-warn-tabs #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and
12 -- detab the module (please do the detabbing in a separate patch). See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
14 -- for details
15
16 module GHC (
17 -- * Initialisation
18 defaultErrorHandler,
19 defaultCleanupHandler,
20
21 -- * GHC Monad
22 Ghc, GhcT, GhcMonad(..), HscEnv,
23 runGhc, runGhcT, initGhcMonad,
24 gcatch, gbracket, gfinally,
25 printException,
26 printExceptionAndWarnings,
27 handleSourceError,
28 needsTemplateHaskell,
29
30 -- * Flags and settings
31 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
32 GhcMode(..), GhcLink(..), defaultObjectTarget,
33 parseDynamicFlags,
34 getSessionDynFlags,
35 setSessionDynFlags,
36 parseStaticFlags,
37
38 -- * Targets
39 Target(..), TargetId(..), Phase,
40 setTargets,
41 getTargets,
42 addTarget,
43 removeTarget,
44 guessTarget,
45
46 -- * Loading\/compiling the program
47 depanal,
48 load, LoadHowMuch(..), InteractiveImport(..),
49 SuccessFlag(..), succeeded, failed,
50 defaultWarnErrLogger, WarnErrLogger,
51 workingDirectoryChanged,
52 parseModule, typecheckModule, desugarModule, loadModule,
53 ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
54 TypecheckedSource, ParsedSource, RenamedSource, -- ditto
55 TypecheckedMod, ParsedMod,
56 moduleInfo, renamedSource, typecheckedSource,
57 parsedSource, coreModule,
58 compileToCoreModule, compileToCoreSimplified,
59 compileCoreToObj,
60 getModSummary,
61
62 -- * Inspecting the module structure of the program
63 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
64 getModuleGraph,
65 isLoaded,
66 topSortModuleGraph,
67
68 -- * Inspecting modules
69 ModuleInfo,
70 getModuleInfo,
71 modInfoTyThings,
72 modInfoTopLevelScope,
73 modInfoExports,
74 modInfoInstances,
75 modInfoIsExportedName,
76 modInfoLookupName,
77 modInfoIface,
78 lookupGlobalName,
79 findGlobalAnns,
80 mkPrintUnqualifiedForModule,
81 ModIface(..),
82
83 -- * Querying the environment
84 packageDbModules,
85
86 -- * Printing
87 PrintUnqualified, alwaysQualify,
88
89 -- * Interactive evaluation
90 getBindings, getInsts, getPrintUnqual,
91 findModule,
92 lookupModule,
93 #ifdef GHCI
94 setContext, getContext,
95 getNamesInScope,
96 getRdrNamesInScope,
97 getGRE,
98 moduleIsInterpreted,
99 getInfo,
100 exprType,
101 typeKind,
102 parseName,
103 RunResult(..),
104 runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
105 parseImportDecl, SingleStep(..),
106 resume,
107 Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
108 resumeHistory, resumeHistoryIx),
109 History(historyBreakInfo, historyEnclosingDecls),
110 GHC.getHistorySpan, getHistoryModule,
111 getResumeContext,
112 abandon, abandonAll,
113 InteractiveEval.back,
114 InteractiveEval.forward,
115 showModule,
116 isModuleInterpreted,
117 InteractiveEval.compileExpr, HValue, dynCompileExpr,
118 GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
119 modInfoModBreaks,
120 ModBreaks(..), BreakIndex,
121 BreakInfo(breakInfo_number, breakInfo_module),
122 BreakArray, setBreakOn, setBreakOff, getBreak,
123 #endif
124 lookupName,
125
126 -- * Abstract syntax elements
127
128 -- ** Packages
129 PackageId,
130
131 -- ** Modules
132 Module, mkModule, pprModule, moduleName, modulePackageId,
133 ModuleName, mkModuleName, moduleNameString,
134
135 -- ** Names
136 Name,
137 isExternalName, nameModule, pprParenSymName, nameSrcSpan,
138 NamedThing(..),
139 RdrName(Qual,Unqual),
140
141 -- ** Identifiers
142 Id, idType,
143 isImplicitId, isDeadBinder,
144 isExportedId, isLocalId, isGlobalId,
145 isRecordSelector,
146 isPrimOpId, isFCallId, isClassOpId_maybe,
147 isDataConWorkId, idDataCon,
148 isBottomingId, isDictonaryId,
149 recordSelectorFieldLabel,
150
151 -- ** Type constructors
152 TyCon,
153 tyConTyVars, tyConDataCons, tyConArity,
154 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
155 isFamilyTyCon, tyConClass_maybe,
156 synTyConDefn, synTyConType, synTyConResKind,
157
158 -- ** Type variables
159 TyVar,
160 alphaTyVars,
161
162 -- ** Data constructors
163 DataCon,
164 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
165 dataConIsInfix, isVanillaDataCon, dataConUserType,
166 dataConStrictMarks,
167 StrictnessMark(..), isMarkedStrict,
168
169 -- ** Classes
170 Class,
171 classMethods, classSCTheta, classTvsFds, classATs,
172 pprFundeps,
173
174 -- ** Instances
175 Instance,
176 instanceDFunId,
177 pprInstance, pprInstanceHdr,
178 pprFamInst, pprFamInstHdr,
179
180 -- ** Types and Kinds
181 Type, splitForAllTys, funResultTy,
182 pprParendType, pprTypeApp,
183 Kind,
184 PredType,
185 ThetaType, pprForAll, pprThetaArrowTy,
186
187 -- ** Entities
188 TyThing(..),
189
190 -- ** Syntax
191 module HsSyn, -- ToDo: remove extraneous bits
192
193 -- ** Fixities
194 FixityDirection(..),
195 defaultFixity, maxPrecedence,
196 negateFixity,
197 compareFixity,
198
199 -- ** Source locations
200 SrcLoc(..), RealSrcLoc,
201 mkSrcLoc, noSrcLoc,
202 srcLocFile, srcLocLine, srcLocCol,
203 SrcSpan(..), RealSrcSpan,
204 mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
205 srcSpanStart, srcSpanEnd,
206 srcSpanFile,
207 srcSpanStartLine, srcSpanEndLine,
208 srcSpanStartCol, srcSpanEndCol,
209
210 -- ** Located
211 GenLocated(..), Located,
212
213 -- *** Constructing Located
214 noLoc, mkGeneralLocated,
215
216 -- *** Deconstructing Located
217 getLoc, unLoc,
218
219 -- *** Combining and comparing Located values
220 eqLocated, cmpLocated, combineLocs, addCLoc,
221 leftmost_smallest, leftmost_largest, rightmost,
222 spans, isSubspanOf,
223
224 -- * Exceptions
225 GhcException(..), showGhcException,
226
227 -- * Token stream manipulations
228 Token,
229 getTokenStream, getRichTokenStream,
230 showRichTokenStream, addSourceToTokens,
231
232 -- * Pure interface to the parser
233 parser,
234
235 -- * Miscellaneous
236 --sessionHscEnv,
237 cyclicModuleErr,
238 ) where
239
240 {-
241 ToDo:
242
243 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
244 * what StaticFlags should we expose, if any?
245 -}
246
247 #include "HsVersions.h"
248
249 #ifdef GHCI
250 import Linker ( HValue )
251 import ByteCodeInstr
252 import BreakArray
253 import InteractiveEval
254 #endif
255
256 import HscMain
257 import GhcMake
258 import DriverPipeline ( compile' )
259 import GhcMonad
260 import TcRnTypes
261 import Packages
262 import NameSet
263 import RdrName
264 import qualified HsSyn -- hack as we want to reexport the whole module
265 import HsSyn hiding ((<.>))
266 import Type hiding( typeKind )
267 import Kind ( synTyConResKind )
268 import TcType hiding( typeKind )
269 import Id
270 import TysPrim ( alphaTyVars )
271 import TyCon
272 import Class
273 import DataCon
274 import Name hiding ( varName )
275 import Avail
276 import InstEnv
277 import FamInstEnv
278 import SrcLoc
279 import CoreSyn
280 import TidyPgm
281 import DriverPhases ( Phase(..), isHaskellSrcFilename )
282 import Finder
283 import HscTypes
284 import DynFlags
285 import StaticFlagParser
286 import qualified StaticFlags
287 import SysTools
288 import Annotations
289 import Module
290 import UniqFM
291 import Panic
292 import Bag ( unitBag )
293 import ErrUtils
294 import MonadUtils
295 import Util
296 import StringBuffer
297 import Outputable
298 import BasicTypes
299 import Maybes ( expectJust )
300 import FastString
301 import qualified Parser
302 import Lexer
303
304 import System.Directory ( doesFileExist, getCurrentDirectory )
305 import Data.Maybe
306 import Data.List ( find )
307 import Data.Typeable ( Typeable )
308 import Data.Word ( Word8 )
309 import Control.Monad
310 import System.Exit ( exitWith, ExitCode(..) )
311 import System.Time ( getClockTime )
312 import Exception
313 import Data.IORef
314 import System.FilePath
315 import System.IO
316 import Prelude hiding (init)
317
318
319 -- %************************************************************************
320 -- %* *
321 -- Initialisation: exception handlers
322 -- %* *
323 -- %************************************************************************
324
325
326 -- | Install some default exception handlers and run the inner computation.
327 -- Unless you want to handle exceptions yourself, you should wrap this around
328 -- the top level of your program. The default handlers output the error
329 -- message(s) to stderr and exit cleanly.
330 defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => LogAction -> m a -> m a
331 defaultErrorHandler la inner =
332 -- top-level exception handler: any unrecognised exception is a compiler bug.
333 ghandle (\exception -> liftIO $ do
334 hFlush stdout
335 case fromException exception of
336 -- an IO exception probably isn't our fault, so don't panic
337 Just (ioe :: IOException) ->
338 fatalErrorMsg' la (text (show ioe))
339 _ -> case fromException exception of
340 Just UserInterrupt -> exitWith (ExitFailure 1)
341 Just StackOverflow ->
342 fatalErrorMsg' la (text "stack overflow: use +RTS -K<size> to increase it")
343 _ -> case fromException exception of
344 Just (ex :: ExitCode) -> throw ex
345 _ ->
346 fatalErrorMsg' la
347 (text (show (Panic (show exception))))
348 exitWith (ExitFailure 1)
349 ) $
350
351 -- error messages propagated as exceptions
352 handleGhcException
353 (\ge -> liftIO $ do
354 hFlush stdout
355 case ge of
356 PhaseFailed _ code -> exitWith code
357 Signal _ -> exitWith (ExitFailure 1)
358 _ -> do fatalErrorMsg' la (text (show ge))
359 exitWith (ExitFailure 1)
360 ) $
361 inner
362
363 -- | Install a default cleanup handler to remove temporary files deposited by
364 -- a GHC run. This is seperate from 'defaultErrorHandler', because you might
365 -- want to override the error handling, but still get the ordinary cleanup
366 -- behaviour.
367 defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) =>
368 DynFlags -> m a -> m a
369 defaultCleanupHandler dflags inner =
370 -- make sure we clean up after ourselves
371 inner `gfinally`
372 (liftIO $ do
373 cleanTempFiles dflags
374 cleanTempDirs dflags
375 )
376 -- exceptions will be blocked while we clean the temporary files,
377 -- so there shouldn't be any difficulty if we receive further
378 -- signals.
379
380
381 -- %************************************************************************
382 -- %* *
383 -- The Ghc Monad
384 -- %* *
385 -- %************************************************************************
386
387 -- | Run function for the 'Ghc' monad.
388 --
389 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
390 -- to this function will create a new session which should not be shared among
391 -- several threads.
392 --
393 -- Any errors not handled inside the 'Ghc' action are propagated as IO
394 -- exceptions.
395
396 runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
397 -> Ghc a -- ^ The action to perform.
398 -> IO a
399 runGhc mb_top_dir ghc = do
400 ref <- newIORef (panic "empty session")
401 let session = Session ref
402 flip unGhc session $ do
403 initGhcMonad mb_top_dir
404 ghc
405 -- XXX: unregister interrupt handlers here?
406
407 -- | Run function for 'GhcT' monad transformer.
408 --
409 -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
410 -- to this function will create a new session which should not be shared among
411 -- several threads.
412
413 runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) =>
414 Maybe FilePath -- ^ See argument to 'initGhcMonad'.
415 -> GhcT m a -- ^ The action to perform.
416 -> m a
417 runGhcT mb_top_dir ghct = do
418 ref <- liftIO $ newIORef (panic "empty session")
419 let session = Session ref
420 flip unGhcT session $ do
421 initGhcMonad mb_top_dir
422 ghct
423
424 -- | Initialise a GHC session.
425 --
426 -- If you implement a custom 'GhcMonad' you must call this function in the
427 -- monad run function. It will initialise the session variable and clear all
428 -- warnings.
429 --
430 -- The first argument should point to the directory where GHC's library files
431 -- reside. More precisely, this should be the output of @ghc --print-libdir@
432 -- of the version of GHC the module using this API is compiled with. For
433 -- portability, you should use the @ghc-paths@ package, available at
434 -- <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ghc-paths>.
435
436 initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
437 initGhcMonad mb_top_dir = do
438 -- catch ^C
439 liftIO $ installSignalHandlers
440
441 liftIO $ StaticFlags.initStaticOpts
442
443 mySettings <- liftIO $ initSysTools mb_top_dir
444 dflags <- liftIO $ initDynFlags (defaultDynFlags mySettings)
445 env <- liftIO $ newHscEnv dflags
446 setSession env
447
448
449 -- %************************************************************************
450 -- %* *
451 -- Flags & settings
452 -- %* *
453 -- %************************************************************************
454
455 -- | Updates the DynFlags in a Session. This also reads
456 -- the package database (unless it has already been read),
457 -- and prepares the compilers knowledge about packages. It
458 -- can be called again to load new packages: just add new
459 -- package flags to (packageFlags dflags).
460 --
461 -- Returns a list of new packages that may need to be linked in using
462 -- the dynamic linker (see 'linkPackages') as a result of new package
463 -- flags. If you are not doing linking or doing static linking, you
464 -- can ignore the list of packages returned.
465 --
466 setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId]
467 setSessionDynFlags dflags = do
468 (dflags', preload) <- liftIO $ initPackages dflags
469 modifySession (\h -> h{ hsc_dflags = dflags' })
470 return preload
471
472
473 parseDynamicFlags :: Monad m =>
474 DynFlags -> [Located String]
475 -> m (DynFlags, [Located String], [Located String])
476 parseDynamicFlags = parseDynamicFlagsCmdLine
477
478
479 -- %************************************************************************
480 -- %* *
481 -- Setting, getting, and modifying the targets
482 -- %* *
483 -- %************************************************************************
484
485 -- ToDo: think about relative vs. absolute file paths. And what
486 -- happens when the current directory changes.
487
488 -- | Sets the targets for this session. Each target may be a module name
489 -- or a filename. The targets correspond to the set of root modules for
490 -- the program\/library. Unloading the current program is achieved by
491 -- setting the current set of targets to be empty, followed by 'load'.
492 setTargets :: GhcMonad m => [Target] -> m ()
493 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
494
495 -- | Returns the current set of targets
496 getTargets :: GhcMonad m => m [Target]
497 getTargets = withSession (return . hsc_targets)
498
499 -- | Add another target.
500 addTarget :: GhcMonad m => Target -> m ()
501 addTarget target
502 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
503
504 -- | Remove a target
505 removeTarget :: GhcMonad m => TargetId -> m ()
506 removeTarget target_id
507 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
508 where
509 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
510
511 -- | Attempts to guess what Target a string refers to. This function
512 -- implements the @--make@/GHCi command-line syntax for filenames:
513 --
514 -- - if the string looks like a Haskell source filename, then interpret it
515 -- as such
516 --
517 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
518 -- then use that
519 --
520 -- - otherwise interpret the string as a module name
521 --
522 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
523 guessTarget str (Just phase)
524 = return (Target (TargetFile str (Just phase)) True Nothing)
525 guessTarget str Nothing
526 | isHaskellSrcFilename file
527 = return (target (TargetFile file Nothing))
528 | otherwise
529 = do exists <- liftIO $ doesFileExist hs_file
530 if exists
531 then return (target (TargetFile hs_file Nothing))
532 else do
533 exists <- liftIO $ doesFileExist lhs_file
534 if exists
535 then return (target (TargetFile lhs_file Nothing))
536 else do
537 if looksLikeModuleName file
538 then return (target (TargetModule (mkModuleName file)))
539 else do
540 throwGhcException
541 (ProgramError (showSDoc $
542 text "target" <+> quotes (text file) <+>
543 text "is not a module name or a source file"))
544 where
545 (file,obj_allowed)
546 | '*':rest <- str = (rest, False)
547 | otherwise = (str, True)
548
549 hs_file = file <.> "hs"
550 lhs_file = file <.> "lhs"
551
552 target tid = Target tid obj_allowed Nothing
553
554
555 -- | Inform GHC that the working directory has changed. GHC will flush
556 -- its cache of module locations, since it may no longer be valid.
557 --
558 -- Note: Before changing the working directory make sure all threads running
559 -- in the same session have stopped. If you change the working directory,
560 -- you should also unload the current program (set targets to empty,
561 -- followed by load).
562 workingDirectoryChanged :: GhcMonad m => m ()
563 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
564
565
566 -- %************************************************************************
567 -- %* *
568 -- Running phases one at a time
569 -- %* *
570 -- %************************************************************************
571
572 class ParsedMod m where
573 modSummary :: m -> ModSummary
574 parsedSource :: m -> ParsedSource
575
576 class ParsedMod m => TypecheckedMod m where
577 renamedSource :: m -> Maybe RenamedSource
578 typecheckedSource :: m -> TypecheckedSource
579 moduleInfo :: m -> ModuleInfo
580 tm_internals :: m -> (TcGblEnv, ModDetails)
581 -- ToDo: improvements that could be made here:
582 -- if the module succeeded renaming but not typechecking,
583 -- we can still get back the GlobalRdrEnv and exports, so
584 -- perhaps the ModuleInfo should be split up into separate
585 -- fields.
586
587 class TypecheckedMod m => DesugaredMod m where
588 coreModule :: m -> ModGuts
589
590 -- | The result of successful parsing.
591 data ParsedModule =
592 ParsedModule { pm_mod_summary :: ModSummary
593 , pm_parsed_source :: ParsedSource }
594
595 instance ParsedMod ParsedModule where
596 modSummary m = pm_mod_summary m
597 parsedSource m = pm_parsed_source m
598
599 -- | The result of successful typechecking. It also contains the parser
600 -- result.
601 data TypecheckedModule =
602 TypecheckedModule { tm_parsed_module :: ParsedModule
603 , tm_renamed_source :: Maybe RenamedSource
604 , tm_typechecked_source :: TypecheckedSource
605 , tm_checked_module_info :: ModuleInfo
606 , tm_internals_ :: (TcGblEnv, ModDetails)
607 }
608
609 instance ParsedMod TypecheckedModule where
610 modSummary m = modSummary (tm_parsed_module m)
611 parsedSource m = parsedSource (tm_parsed_module m)
612
613 instance TypecheckedMod TypecheckedModule where
614 renamedSource m = tm_renamed_source m
615 typecheckedSource m = tm_typechecked_source m
616 moduleInfo m = tm_checked_module_info m
617 tm_internals m = tm_internals_ m
618
619 -- | The result of successful desugaring (i.e., translation to core). Also
620 -- contains all the information of a typechecked module.
621 data DesugaredModule =
622 DesugaredModule { dm_typechecked_module :: TypecheckedModule
623 , dm_core_module :: ModGuts
624 }
625
626 instance ParsedMod DesugaredModule where
627 modSummary m = modSummary (dm_typechecked_module m)
628 parsedSource m = parsedSource (dm_typechecked_module m)
629
630 instance TypecheckedMod DesugaredModule where
631 renamedSource m = renamedSource (dm_typechecked_module m)
632 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
633 moduleInfo m = moduleInfo (dm_typechecked_module m)
634 tm_internals m = tm_internals_ (dm_typechecked_module m)
635
636 instance DesugaredMod DesugaredModule where
637 coreModule m = dm_core_module m
638
639 type ParsedSource = Located (HsModule RdrName)
640 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
641 Maybe LHsDocString)
642 type TypecheckedSource = LHsBinds Id
643
644 -- NOTE:
645 -- - things that aren't in the output of the typechecker right now:
646 -- - the export list
647 -- - the imports
648 -- - type signatures
649 -- - type/data/newtype declarations
650 -- - class declarations
651 -- - instances
652 -- - extra things in the typechecker's output:
653 -- - default methods are turned into top-level decls.
654 -- - dictionary bindings
655
656 -- | Return the 'ModSummary' of a module with the given name.
657 --
658 -- The module must be part of the module graph (see 'hsc_mod_graph' and
659 -- 'ModuleGraph'). If this is not the case, this function will throw a
660 -- 'GhcApiError'.
661 --
662 -- This function ignores boot modules and requires that there is only one
663 -- non-boot module with the given name.
664 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
665 getModSummary mod = do
666 mg <- liftM hsc_mod_graph getSession
667 case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
668 [] -> throw $ mkApiErr (text "Module not part of module graph")
669 [ms] -> return ms
670 multiple -> throw $ mkApiErr (text "getModSummary is ambiguous: " <+> ppr multiple)
671
672 -- | Parse a module.
673 --
674 -- Throws a 'SourceError' on parse error.
675 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
676 parseModule ms = do
677 hsc_env <- getSession
678 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
679 rdr_module <- liftIO $ hscParse hsc_env_tmp ms
680 return (ParsedModule ms rdr_module)
681
682 -- | Typecheck and rename a parsed module.
683 --
684 -- Throws a 'SourceError' if either fails.
685 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
686 typecheckModule pmod = do
687 let ms = modSummary pmod
688 hsc_env <- getSession
689 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
690 (tc_gbl_env, rn_info)
691 <- liftIO $ hscTypecheckRename hsc_env_tmp ms (parsedSource pmod)
692 details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env
693 return $
694 TypecheckedModule {
695 tm_internals_ = (tc_gbl_env, details),
696 tm_parsed_module = pmod,
697 tm_renamed_source = rn_info,
698 tm_typechecked_source = tcg_binds tc_gbl_env,
699 tm_checked_module_info =
700 ModuleInfo {
701 minf_type_env = md_types details,
702 minf_exports = availsToNameSet $ md_exports details,
703 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
704 minf_instances = md_insts details,
705 minf_iface = Nothing
706 #ifdef GHCI
707 ,minf_modBreaks = emptyModBreaks
708 #endif
709 }}
710
711 -- | Desugar a typechecked module.
712 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
713 desugarModule tcm = do
714 let ms = modSummary tcm
715 let (tcg, _) = tm_internals tcm
716 hsc_env <- getSession
717 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
718 guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg
719 return $
720 DesugaredModule {
721 dm_typechecked_module = tcm,
722 dm_core_module = guts
723 }
724
725 -- | Load a module. Input doesn't need to be desugared.
726 --
727 -- A module must be loaded before dependent modules can be typechecked. This
728 -- always includes generating a 'ModIface' and, depending on the
729 -- 'DynFlags.hscTarget', may also include code generation.
730 --
731 -- This function will always cause recompilation and will always overwrite
732 -- previous compilation results (potentially files on disk).
733 --
734 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
735 loadModule tcm = do
736 let ms = modSummary tcm
737 let mod = ms_mod_name ms
738 let loc = ms_location ms
739 let (tcg, _details) = tm_internals tcm
740
741 mb_linkable <- case ms_obj_date ms of
742 Just t | t > ms_hs_date ms -> do
743 l <- liftIO $ findObjectLinkable (ms_mod ms)
744 (ml_obj_file loc) t
745 return (Just l)
746 _otherwise -> return Nothing
747
748 let source_modified | isNothing mb_linkable = SourceModified
749 | otherwise = SourceUnmodified
750 -- we can't determine stability here
751
752 -- compile doesn't change the session
753 hsc_env <- getSession
754 mod_info <- liftIO $ compile' (hscNothingBackendOnly tcg,
755 hscInteractiveBackendOnly tcg,
756 hscBatchBackendOnly tcg)
757 hsc_env ms 1 1 Nothing mb_linkable
758 source_modified
759
760 modifySession $ \e -> e{ hsc_HPT = addToUFM (hsc_HPT e) mod mod_info }
761 return tcm
762
763
764 -- %************************************************************************
765 -- %* *
766 -- Dealing with Core
767 -- %* *
768 -- %************************************************************************
769
770 -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
771 -- the 'GHC.compileToCoreModule' interface.
772 data CoreModule
773 = CoreModule {
774 -- | Module name
775 cm_module :: !Module,
776 -- | Type environment for types declared in this module
777 cm_types :: !TypeEnv,
778 -- | Declarations
779 cm_binds :: CoreProgram
780 }
781
782 instance Outputable CoreModule where
783 ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb}) =
784 text "%module" <+> ppr mn <+> ppr te $$ vcat (map ppr cb)
785
786 -- | This is the way to get access to the Core bindings corresponding
787 -- to a module. 'compileToCore' parses, typechecks, and
788 -- desugars the module, then returns the resulting Core module (consisting of
789 -- the module name, type declarations, and function declarations) if
790 -- successful.
791 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
792 compileToCoreModule = compileCore False
793
794 -- | Like compileToCoreModule, but invokes the simplifier, so
795 -- as to return simplified and tidied Core.
796 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
797 compileToCoreSimplified = compileCore True
798 {-
799 -- | Provided for backwards-compatibility: compileToCore returns just the Core
800 -- bindings, but for most purposes, you probably want to call
801 -- compileToCoreModule.
802 compileToCore :: GhcMonad m => FilePath -> m [CoreBind]
803 compileToCore fn = do
804 mod <- compileToCoreModule session fn
805 return $ cm_binds mod
806 -}
807 -- | Takes a CoreModule and compiles the bindings therein
808 -- to object code. The first argument is a bool flag indicating
809 -- whether to run the simplifier.
810 -- The resulting .o, .hi, and executable files, if any, are stored in the
811 -- current directory, and named according to the module name.
812 -- This has only so far been tested with a single self-contained module.
813 compileCoreToObj :: GhcMonad m => Bool -> CoreModule -> m ()
814 compileCoreToObj simplify cm@(CoreModule{ cm_module = mName }) = do
815 dflags <- getSessionDynFlags
816 currentTime <- liftIO $ getClockTime
817 cwd <- liftIO $ getCurrentDirectory
818 modLocation <- liftIO $ mkHiOnlyModLocation dflags (hiSuf dflags) cwd
819 ((moduleNameSlashes . moduleName) mName)
820
821 let modSummary = ModSummary { ms_mod = mName,
822 ms_hsc_src = ExtCoreFile,
823 ms_location = modLocation,
824 -- By setting the object file timestamp to Nothing,
825 -- we always force recompilation, which is what we
826 -- want. (Thus it doesn't matter what the timestamp
827 -- for the (nonexistent) source file is.)
828 ms_hs_date = currentTime,
829 ms_obj_date = Nothing,
830 -- Only handling the single-module case for now, so no imports.
831 ms_srcimps = [],
832 ms_textual_imps = [],
833 -- No source file
834 ms_hspp_file = "",
835 ms_hspp_opts = dflags,
836 ms_hspp_buf = Nothing
837 }
838
839 hsc_env <- getSession
840 liftIO $ hscCompileCore hsc_env simplify modSummary (cm_binds cm)
841
842
843 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
844 compileCore simplify fn = do
845 -- First, set the target to the desired filename
846 target <- guessTarget fn Nothing
847 addTarget target
848 _ <- load LoadAllTargets
849 -- Then find dependencies
850 modGraph <- depanal [] True
851 case find ((== fn) . msHsFilePath) modGraph of
852 Just modSummary -> do
853 -- Now we have the module name;
854 -- parse, typecheck and desugar the module
855 mod_guts <- coreModule `fmap`
856 -- TODO: space leaky: call hsc* directly?
857 (desugarModule =<< typecheckModule =<< parseModule modSummary)
858 liftM gutsToCoreModule $
859 if simplify
860 then do
861 -- If simplify is true: simplify (hscSimplify), then tidy
862 -- (tidyProgram).
863 hsc_env <- getSession
864 simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts
865 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
866 return $ Left tidy_guts
867 else
868 return $ Right mod_guts
869
870 Nothing -> panic "compileToCoreModule: target FilePath not found in\
871 module dependency graph"
872 where -- two versions, based on whether we simplify (thus run tidyProgram,
873 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
874 -- we just have a ModGuts.
875 gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
876 gutsToCoreModule (Left (cg, md)) = CoreModule {
877 cm_module = cg_module cg,
878 cm_types = md_types md,
879 cm_binds = cg_binds cg
880 }
881 gutsToCoreModule (Right mg) = CoreModule {
882 cm_module = mg_module mg,
883 cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg))
884 (mg_tcs mg)
885 (mg_fam_insts mg),
886 cm_binds = mg_binds mg
887 }
888
889 -- %************************************************************************
890 -- %* *
891 -- Inspecting the session
892 -- %* *
893 -- %************************************************************************
894
895 -- | Get the module dependency graph.
896 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
897 getModuleGraph = liftM hsc_mod_graph getSession
898
899 -- | Determines whether a set of modules requires Template Haskell.
900 --
901 -- Note that if the session's 'DynFlags' enabled Template Haskell when
902 -- 'depanal' was called, then each module in the returned module graph will
903 -- have Template Haskell enabled whether it is actually needed or not.
904 needsTemplateHaskell :: ModuleGraph -> Bool
905 needsTemplateHaskell ms =
906 any (xopt Opt_TemplateHaskell . ms_hspp_opts) ms
907
908 -- | Return @True@ <==> module is loaded.
909 isLoaded :: GhcMonad m => ModuleName -> m Bool
910 isLoaded m = withSession $ \hsc_env ->
911 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
912
913 -- | Return the bindings for the current interactive session.
914 getBindings :: GhcMonad m => m [TyThing]
915 getBindings = withSession $ \hsc_env ->
916 return $ icInScopeTTs $ hsc_IC hsc_env
917
918 -- | Return the instances for the current interactive session.
919 getInsts :: GhcMonad m => m ([Instance], [FamInst])
920 getInsts = withSession $ \hsc_env ->
921 return $ ic_instances (hsc_IC hsc_env)
922
923 getPrintUnqual :: GhcMonad m => m PrintUnqualified
924 getPrintUnqual = withSession $ \hsc_env ->
925 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
926
927 -- | Container for information about a 'Module'.
928 data ModuleInfo = ModuleInfo {
929 minf_type_env :: TypeEnv,
930 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
931 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
932 minf_instances :: [Instance],
933 minf_iface :: Maybe ModIface
934 #ifdef GHCI
935 ,minf_modBreaks :: ModBreaks
936 #endif
937 }
938 -- We don't want HomeModInfo here, because a ModuleInfo applies
939 -- to package modules too.
940
941 -- | Request information about a loaded 'Module'
942 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
943 getModuleInfo mdl = withSession $ \hsc_env -> do
944 let mg = hsc_mod_graph hsc_env
945 if mdl `elem` map ms_mod mg
946 then liftIO $ getHomeModuleInfo hsc_env mdl
947 else do
948 {- if isHomeModule (hsc_dflags hsc_env) mdl
949 then return Nothing
950 else -} liftIO $ getPackageModuleInfo hsc_env mdl
951 -- ToDo: we don't understand what the following comment means.
952 -- (SDM, 19/7/2011)
953 -- getPackageModuleInfo will attempt to find the interface, so
954 -- we don't want to call it for a home module, just in case there
955 -- was a problem loading the module and the interface doesn't
956 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
957
958 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
959 #ifdef GHCI
960 getPackageModuleInfo hsc_env mdl
961 = do eps <- hscEPS hsc_env
962 iface <- hscGetModuleInterface hsc_env mdl
963 let
964 avails = mi_exports iface
965 names = availsToNameSet avails
966 pte = eps_PTE eps
967 tys = [ ty | name <- concatMap availNames avails,
968 Just ty <- [lookupTypeEnv pte name] ]
969 --
970 return (Just (ModuleInfo {
971 minf_type_env = mkTypeEnv tys,
972 minf_exports = names,
973 minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
974 minf_instances = error "getModuleInfo: instances for package module unimplemented",
975 minf_iface = Just iface,
976 minf_modBreaks = emptyModBreaks
977 }))
978 #else
979 -- bogusly different for non-GHCI (ToDo)
980 getPackageModuleInfo _hsc_env _mdl = do
981 return Nothing
982 #endif
983
984 getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
985 getHomeModuleInfo hsc_env mdl =
986 case lookupUFM (hsc_HPT hsc_env) (moduleName mdl) of
987 Nothing -> return Nothing
988 Just hmi -> do
989 let details = hm_details hmi
990 iface = hm_iface hmi
991 return (Just (ModuleInfo {
992 minf_type_env = md_types details,
993 minf_exports = availsToNameSet (md_exports details),
994 minf_rdr_env = mi_globals $! hm_iface hmi,
995 minf_instances = md_insts details,
996 minf_iface = Just iface
997 #ifdef GHCI
998 ,minf_modBreaks = getModBreaks hmi
999 #endif
1000 }))
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)