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