Revert D727
[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', preload) <- liftIO $ initPackages dflags
574 modifySession $ \h -> h{ hsc_dflags = dflags'
575 , hsc_IC = (hsc_IC h){ ic_dflags = dflags' } }
576 invalidateModSummaryCache
577 return preload
578
579 -- | Sets the program 'DynFlags'.
580 setProgramDynFlags :: GhcMonad m => DynFlags -> m [PackageKey]
581 setProgramDynFlags dflags = do
582 (dflags', preload) <- liftIO $ initPackages dflags
583 modifySession $ \h -> h{ hsc_dflags = dflags' }
584 invalidateModSummaryCache
585 return preload
586
587 -- When changing the DynFlags, we want the changes to apply to future
588 -- loads, but without completely discarding the program. But the
589 -- DynFlags are cached in each ModSummary in the hsc_mod_graph, so
590 -- after a change to DynFlags, the changes would apply to new modules
591 -- but not existing modules; this seems undesirable.
592 --
593 -- Furthermore, the GHC API client might expect that changing
594 -- log_action would affect future compilation messages, but for those
595 -- modules we have cached ModSummaries for, we'll continue to use the
596 -- old log_action. This is definitely wrong (#7478).
597 --
598 -- Hence, we invalidate the ModSummary cache after changing the
599 -- DynFlags. We do this by tweaking the date on each ModSummary, so
600 -- that the next downsweep will think that all the files have changed
601 -- and preprocess them again. This won't necessarily cause everything
602 -- to be recompiled, because by the time we check whether we need to
603 -- recopmile a module, we'll have re-summarised the module and have a
604 -- correct ModSummary.
605 --
606 invalidateModSummaryCache :: GhcMonad m => m ()
607 invalidateModSummaryCache =
608 modifySession $ \h -> h { hsc_mod_graph = map inval (hsc_mod_graph h) }
609 where
610 inval ms = ms { ms_hs_date = addUTCTime (-1) (ms_hs_date ms) }
611
612 -- | Returns the program 'DynFlags'.
613 getProgramDynFlags :: GhcMonad m => m DynFlags
614 getProgramDynFlags = getSessionDynFlags
615
616 -- | Set the 'DynFlags' used to evaluate interactive expressions.
617 -- Note: this cannot be used for changes to packages. Use
618 -- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the
619 -- 'pkgState' into the interactive @DynFlags@.
620 setInteractiveDynFlags :: GhcMonad m => DynFlags -> m ()
621 setInteractiveDynFlags dflags = do
622 modifySession $ \h -> h{ hsc_IC = (hsc_IC h) { ic_dflags = dflags }}
623
624 -- | Get the 'DynFlags' used to evaluate interactive expressions.
625 getInteractiveDynFlags :: GhcMonad m => m DynFlags
626 getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h))
627
628
629 parseDynamicFlags :: MonadIO m =>
630 DynFlags -> [Located String]
631 -> m (DynFlags, [Located String], [Located String])
632 parseDynamicFlags = parseDynamicFlagsCmdLine
633
634
635 -- %************************************************************************
636 -- %* *
637 -- Setting, getting, and modifying the targets
638 -- %* *
639 -- %************************************************************************
640
641 -- ToDo: think about relative vs. absolute file paths. And what
642 -- happens when the current directory changes.
643
644 -- | Sets the targets for this session. Each target may be a module name
645 -- or a filename. The targets correspond to the set of root modules for
646 -- the program\/library. Unloading the current program is achieved by
647 -- setting the current set of targets to be empty, followed by 'load'.
648 setTargets :: GhcMonad m => [Target] -> m ()
649 setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
650
651 -- | Returns the current set of targets
652 getTargets :: GhcMonad m => m [Target]
653 getTargets = withSession (return . hsc_targets)
654
655 -- | Add another target.
656 addTarget :: GhcMonad m => Target -> m ()
657 addTarget target
658 = modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
659
660 -- | Remove a target
661 removeTarget :: GhcMonad m => TargetId -> m ()
662 removeTarget target_id
663 = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
664 where
665 filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
666
667 -- | Attempts to guess what Target a string refers to. This function
668 -- implements the @--make@/GHCi command-line syntax for filenames:
669 --
670 -- - if the string looks like a Haskell source filename, then interpret it
671 -- as such
672 --
673 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
674 -- then use that
675 --
676 -- - otherwise interpret the string as a module name
677 --
678 guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
679 guessTarget str (Just phase)
680 = return (Target (TargetFile str (Just phase)) True Nothing)
681 guessTarget str Nothing
682 | isHaskellSrcFilename file
683 = return (target (TargetFile file Nothing))
684 | otherwise
685 = do exists <- liftIO $ doesFileExist hs_file
686 if exists
687 then return (target (TargetFile hs_file Nothing))
688 else do
689 exists <- liftIO $ doesFileExist lhs_file
690 if exists
691 then return (target (TargetFile lhs_file Nothing))
692 else do
693 if looksLikeModuleName file
694 then return (target (TargetModule (mkModuleName file)))
695 else do
696 dflags <- getDynFlags
697 liftIO $ throwGhcExceptionIO
698 (ProgramError (showSDoc dflags $
699 text "target" <+> quotes (text file) <+>
700 text "is not a module name or a source file"))
701 where
702 (file,obj_allowed)
703 | '*':rest <- str = (rest, False)
704 | otherwise = (str, True)
705
706 hs_file = file <.> "hs"
707 lhs_file = file <.> "lhs"
708
709 target tid = Target tid obj_allowed Nothing
710
711
712 -- | Inform GHC that the working directory has changed. GHC will flush
713 -- its cache of module locations, since it may no longer be valid.
714 --
715 -- Note: Before changing the working directory make sure all threads running
716 -- in the same session have stopped. If you change the working directory,
717 -- you should also unload the current program (set targets to empty,
718 -- followed by load).
719 workingDirectoryChanged :: GhcMonad m => m ()
720 workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
721
722
723 -- %************************************************************************
724 -- %* *
725 -- Running phases one at a time
726 -- %* *
727 -- %************************************************************************
728
729 class ParsedMod m where
730 modSummary :: m -> ModSummary
731 parsedSource :: m -> ParsedSource
732
733 class ParsedMod m => TypecheckedMod m where
734 renamedSource :: m -> Maybe RenamedSource
735 typecheckedSource :: m -> TypecheckedSource
736 moduleInfo :: m -> ModuleInfo
737 tm_internals :: m -> (TcGblEnv, ModDetails)
738 -- ToDo: improvements that could be made here:
739 -- if the module succeeded renaming but not typechecking,
740 -- we can still get back the GlobalRdrEnv and exports, so
741 -- perhaps the ModuleInfo should be split up into separate
742 -- fields.
743
744 class TypecheckedMod m => DesugaredMod m where
745 coreModule :: m -> ModGuts
746
747 -- | The result of successful parsing.
748 data ParsedModule =
749 ParsedModule { pm_mod_summary :: ModSummary
750 , pm_parsed_source :: ParsedSource
751 , pm_extra_src_files :: [FilePath]
752 , pm_annotations :: ApiAnns }
753 -- See Note [Api annotations] in ApiAnnotation.hs
754
755 instance ParsedMod ParsedModule where
756 modSummary m = pm_mod_summary m
757 parsedSource m = pm_parsed_source m
758
759 -- | The result of successful typechecking. It also contains the parser
760 -- result.
761 data TypecheckedModule =
762 TypecheckedModule { tm_parsed_module :: ParsedModule
763 , tm_renamed_source :: Maybe RenamedSource
764 , tm_typechecked_source :: TypecheckedSource
765 , tm_checked_module_info :: ModuleInfo
766 , tm_internals_ :: (TcGblEnv, ModDetails)
767 }
768
769 instance ParsedMod TypecheckedModule where
770 modSummary m = modSummary (tm_parsed_module m)
771 parsedSource m = parsedSource (tm_parsed_module m)
772
773 instance TypecheckedMod TypecheckedModule where
774 renamedSource m = tm_renamed_source m
775 typecheckedSource m = tm_typechecked_source m
776 moduleInfo m = tm_checked_module_info m
777 tm_internals m = tm_internals_ m
778
779 -- | The result of successful desugaring (i.e., translation to core). Also
780 -- contains all the information of a typechecked module.
781 data DesugaredModule =
782 DesugaredModule { dm_typechecked_module :: TypecheckedModule
783 , dm_core_module :: ModGuts
784 }
785
786 instance ParsedMod DesugaredModule where
787 modSummary m = modSummary (dm_typechecked_module m)
788 parsedSource m = parsedSource (dm_typechecked_module m)
789
790 instance TypecheckedMod DesugaredModule where
791 renamedSource m = renamedSource (dm_typechecked_module m)
792 typecheckedSource m = typecheckedSource (dm_typechecked_module m)
793 moduleInfo m = moduleInfo (dm_typechecked_module m)
794 tm_internals m = tm_internals_ (dm_typechecked_module m)
795
796 instance DesugaredMod DesugaredModule where
797 coreModule m = dm_core_module m
798
799 type ParsedSource = Located (HsModule RdrName)
800 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
801 Maybe LHsDocString)
802 type TypecheckedSource = LHsBinds Id
803
804 -- NOTE:
805 -- - things that aren't in the output of the typechecker right now:
806 -- - the export list
807 -- - the imports
808 -- - type signatures
809 -- - type/data/newtype declarations
810 -- - class declarations
811 -- - instances
812 -- - extra things in the typechecker's output:
813 -- - default methods are turned into top-level decls.
814 -- - dictionary bindings
815
816 -- | Return the 'ModSummary' of a module with the given name.
817 --
818 -- The module must be part of the module graph (see 'hsc_mod_graph' and
819 -- 'ModuleGraph'). If this is not the case, this function will throw a
820 -- 'GhcApiError'.
821 --
822 -- This function ignores boot modules and requires that there is only one
823 -- non-boot module with the given name.
824 getModSummary :: GhcMonad m => ModuleName -> m ModSummary
825 getModSummary mod = do
826 mg <- liftM hsc_mod_graph getSession
827 case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
828 [] -> do dflags <- getDynFlags
829 liftIO $ throwIO $ mkApiErr dflags (text "Module not part of module graph")
830 [ms] -> return ms
831 multiple -> do dflags <- getDynFlags
832 liftIO $ throwIO $ mkApiErr dflags (text "getModSummary is ambiguous: " <+> ppr multiple)
833
834 -- | Parse a module.
835 --
836 -- Throws a 'SourceError' on parse error.
837 parseModule :: GhcMonad m => ModSummary -> m ParsedModule
838 parseModule ms = do
839 hsc_env <- getSession
840 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
841 hpm <- liftIO $ hscParse hsc_env_tmp ms
842 return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm)
843 (hpm_annotations hpm))
844 -- See Note [Api annotations] in ApiAnnotation.hs
845
846 -- | Typecheck and rename a parsed module.
847 --
848 -- Throws a 'SourceError' if either fails.
849 typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
850 typecheckModule pmod = do
851 let ms = modSummary pmod
852 hsc_env <- getSession
853 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
854 (tc_gbl_env, rn_info)
855 <- liftIO $ hscTypecheckRename hsc_env_tmp ms $
856 HsParsedModule { hpm_module = parsedSource pmod,
857 hpm_src_files = pm_extra_src_files pmod,
858 hpm_annotations = pm_annotations pmod }
859 details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env
860 safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env
861
862 return $
863 TypecheckedModule {
864 tm_internals_ = (tc_gbl_env, details),
865 tm_parsed_module = pmod,
866 tm_renamed_source = rn_info,
867 tm_typechecked_source = tcg_binds tc_gbl_env,
868 tm_checked_module_info =
869 ModuleInfo {
870 minf_type_env = md_types details,
871 minf_exports = availsToNameSet $ md_exports details,
872 minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
873 minf_instances = fixSafeInstances safe $ md_insts details,
874 minf_iface = Nothing,
875 minf_safe = safe
876 #ifdef GHCI
877 ,minf_modBreaks = emptyModBreaks
878 #endif
879 }}
880
881 -- | Desugar a typechecked module.
882 desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
883 desugarModule tcm = do
884 let ms = modSummary tcm
885 let (tcg, _) = tm_internals tcm
886 hsc_env <- getSession
887 let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
888 guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg
889 return $
890 DesugaredModule {
891 dm_typechecked_module = tcm,
892 dm_core_module = guts
893 }
894
895 -- | Load a module. Input doesn't need to be desugared.
896 --
897 -- A module must be loaded before dependent modules can be typechecked. This
898 -- always includes generating a 'ModIface' and, depending on the
899 -- 'DynFlags.hscTarget', may also include code generation.
900 --
901 -- This function will always cause recompilation and will always overwrite
902 -- previous compilation results (potentially files on disk).
903 --
904 loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
905 loadModule tcm = do
906 let ms = modSummary tcm
907 let mod = ms_mod_name ms
908 let loc = ms_location ms
909 let (tcg, _details) = tm_internals tcm
910
911 mb_linkable <- case ms_obj_date ms of
912 Just t | t > ms_hs_date ms -> do
913 l <- liftIO $ findObjectLinkable (ms_mod ms)
914 (ml_obj_file loc) t
915 return (Just l)
916 _otherwise -> return Nothing
917
918 let source_modified | isNothing mb_linkable = SourceModified
919 | otherwise = SourceUnmodified
920 -- we can't determine stability here
921
922 -- compile doesn't change the session
923 hsc_env <- getSession
924 mod_info <- liftIO $ compileOne' (Just tcg) Nothing
925 hsc_env ms 1 1 Nothing mb_linkable
926 source_modified
927
928 modifySession $ \e -> e{ hsc_HPT = addToUFM (hsc_HPT e) mod mod_info }
929 return tcm
930
931
932 -- %************************************************************************
933 -- %* *
934 -- Dealing with Core
935 -- %* *
936 -- %************************************************************************
937
938 -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
939 -- the 'GHC.compileToCoreModule' interface.
940 data CoreModule
941 = CoreModule {
942 -- | Module name
943 cm_module :: !Module,
944 -- | Type environment for types declared in this module
945 cm_types :: !TypeEnv,
946 -- | Declarations
947 cm_binds :: CoreProgram,
948 -- | Safe Haskell mode
949 cm_safe :: SafeHaskellMode
950 }
951
952 instance Outputable CoreModule where
953 ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb,
954 cm_safe = sf})
955 = text "%module" <+> ppr mn <+> parens (ppr sf) <+> ppr te
956 $$ vcat (map ppr cb)
957
958 -- | This is the way to get access to the Core bindings corresponding
959 -- to a module. 'compileToCore' parses, typechecks, and
960 -- desugars the module, then returns the resulting Core module (consisting of
961 -- the module name, type declarations, and function declarations) if
962 -- successful.
963 compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
964 compileToCoreModule = compileCore False
965
966 -- | Like compileToCoreModule, but invokes the simplifier, so
967 -- as to return simplified and tidied Core.
968 compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
969 compileToCoreSimplified = compileCore True
970
971 compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
972 compileCore simplify fn = do
973 -- First, set the target to the desired filename
974 target <- guessTarget fn Nothing
975 addTarget target
976 _ <- load LoadAllTargets
977 -- Then find dependencies
978 modGraph <- depanal [] True
979 case find ((== fn) . msHsFilePath) modGraph of
980 Just modSummary -> do
981 -- Now we have the module name;
982 -- parse, typecheck and desugar the module
983 mod_guts <- coreModule `fmap`
984 -- TODO: space leaky: call hsc* directly?
985 (desugarModule =<< typecheckModule =<< parseModule modSummary)
986 liftM (gutsToCoreModule (mg_safe_haskell mod_guts)) $
987 if simplify
988 then do
989 -- If simplify is true: simplify (hscSimplify), then tidy
990 -- (tidyProgram).
991 hsc_env <- getSession
992 simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts
993 tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
994 return $ Left tidy_guts
995 else
996 return $ Right mod_guts
997
998 Nothing -> panic "compileToCoreModule: target FilePath not found in\
999 module dependency graph"
1000 where -- two versions, based on whether we simplify (thus run tidyProgram,
1001 -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1002 -- we just have a ModGuts.
1003 gutsToCoreModule :: SafeHaskellMode
1004 -> Either (CgGuts, ModDetails) ModGuts
1005 -> CoreModule
1006 gutsToCoreModule safe_mode (Left (cg, md)) = CoreModule {
1007 cm_module = cg_module cg,
1008 cm_types = md_types md,
1009 cm_binds = cg_binds cg,
1010 cm_safe = safe_mode
1011 }
1012 gutsToCoreModule safe_mode (Right mg) = CoreModule {
1013 cm_module = mg_module mg,
1014 cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg))
1015 (mg_tcs mg)
1016 (mg_fam_insts mg),
1017 cm_binds = mg_binds mg,
1018 cm_safe = safe_mode
1019 }
1020
1021 -- %************************************************************************
1022 -- %* *
1023 -- Inspecting the session
1024 -- %* *
1025 -- %************************************************************************
1026
1027 -- | Get the module dependency graph.
1028 getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
1029 getModuleGraph = liftM hsc_mod_graph getSession
1030
1031 -- | Determines whether a set of modules requires Template Haskell.
1032 --
1033 -- Note that if the session's 'DynFlags' enabled Template Haskell when
1034 -- 'depanal' was called, then each module in the returned module graph will
1035 -- have Template Haskell enabled whether it is actually needed or not.
1036 needsTemplateHaskell :: ModuleGraph -> Bool
1037 needsTemplateHaskell ms =
1038 any (xopt Opt_TemplateHaskell . ms_hspp_opts) ms
1039
1040 -- | Return @True@ <==> module is loaded.
1041 isLoaded :: GhcMonad m => ModuleName -> m Bool
1042 isLoaded m = withSession $ \hsc_env ->
1043 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1044
1045 -- | Return the bindings for the current interactive session.
1046 getBindings :: GhcMonad m => m [TyThing]
1047 getBindings = withSession $ \hsc_env ->
1048 return $ icInScopeTTs $ hsc_IC hsc_env
1049
1050 -- | Return the instances for the current interactive session.
1051 getInsts :: GhcMonad m => m ([ClsInst], [FamInst])
1052 getInsts = withSession $ \hsc_env ->
1053 return $ ic_instances (hsc_IC hsc_env)
1054
1055 getPrintUnqual :: GhcMonad m => m PrintUnqualified
1056 getPrintUnqual = withSession $ \hsc_env ->
1057 return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
1058
1059 -- | Container for information about a 'Module'.
1060 data ModuleInfo = ModuleInfo {
1061 minf_type_env :: TypeEnv,
1062 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1063 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1064 minf_instances :: [ClsInst],
1065 minf_iface :: Maybe ModIface,
1066 minf_safe :: SafeHaskellMode
1067 #ifdef GHCI
1068 ,minf_modBreaks :: ModBreaks
1069 #endif
1070 }
1071 -- We don't want HomeModInfo here, because a ModuleInfo applies
1072 -- to package modules too.
1073
1074 -- | Request information about a loaded 'Module'
1075 getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
1076 getModuleInfo mdl = withSession $ \hsc_env -> do
1077 let mg = hsc_mod_graph hsc_env
1078 if mdl `elem` map ms_mod mg
1079 then liftIO $ getHomeModuleInfo hsc_env mdl
1080 else do
1081 {- if isHomeModule (hsc_dflags hsc_env) mdl
1082 then return Nothing
1083 else -} liftIO $ getPackageModuleInfo hsc_env mdl
1084 -- ToDo: we don't understand what the following comment means.
1085 -- (SDM, 19/7/2011)
1086 -- getPackageModuleInfo will attempt to find the interface, so
1087 -- we don't want to call it for a home module, just in case there
1088 -- was a problem loading the module and the interface doesn't
1089 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1090
1091 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1092 #ifdef GHCI
1093 getPackageModuleInfo hsc_env mdl
1094 = do eps <- hscEPS hsc_env
1095 iface <- hscGetModuleInterface hsc_env mdl
1096 let
1097 avails = mi_exports iface
1098 names = availsToNameSet avails
1099 pte = eps_PTE eps
1100 tys = [ ty | name <- concatMap availNames avails,
1101 Just ty <- [lookupTypeEnv pte name] ]
1102 --
1103 return (Just (ModuleInfo {
1104 minf_type_env = mkTypeEnv tys,
1105 minf_exports = names,
1106 minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
1107 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1108 minf_iface = Just iface,
1109 minf_safe = getSafeMode $ mi_trust iface,
1110 minf_modBreaks = emptyModBreaks
1111 }))
1112 #else
1113 -- bogusly different for non-GHCI (ToDo)
1114 getPackageModuleInfo _hsc_env _mdl = do
1115 return Nothing
1116 #endif
1117
1118 getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1119 getHomeModuleInfo hsc_env mdl =
1120 case lookupUFM (hsc_HPT hsc_env) (moduleName mdl) of
1121 Nothing -> return Nothing
1122 Just hmi -> do
1123 let details = hm_details hmi
1124 iface = hm_iface hmi
1125 return (Just (ModuleInfo {
1126 minf_type_env = md_types details,
1127 minf_exports = availsToNameSet (md_exports details),
1128 minf_rdr_env = mi_globals $! hm_iface hmi,
1129 minf_instances = md_insts details,
1130 minf_iface = Just iface,
1131 minf_safe = getSafeMode $ mi_trust iface
1132 #ifdef GHCI
1133 ,minf_modBreaks = getModBreaks hmi
1134 #endif
1135 }))
1136
1137 -- | The list of top-level entities defined in a module
1138 modInfoTyThings :: ModuleInfo -> [TyThing]
1139 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1140
1141 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1142 modInfoTopLevelScope minf
1143 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1144
1145 modInfoExports :: ModuleInfo -> [Name]
1146 modInfoExports minf = nameSetElems $! minf_exports minf
1147
1148 -- | Returns the instances defined by the specified module.
1149 -- Warning: currently unimplemented for package modules.
1150 modInfoInstances :: ModuleInfo -> [ClsInst]
1151 modInfoInstances = minf_instances
1152
1153 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1154 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1155
1156 mkPrintUnqualifiedForModule :: GhcMonad m =>
1157 ModuleInfo
1158 -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
1159 mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
1160 return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
1161
1162 modInfoLookupName :: GhcMonad m =>
1163 ModuleInfo -> Name
1164 -> m (Maybe TyThing) -- XXX: returns a Maybe X
1165 modInfoLookupName minf name = withSession $ \hsc_env -> do
1166 case lookupTypeEnv (minf_type_env minf) name of
1167 Just tyThing -> return (Just tyThing)
1168 Nothing -> do
1169 eps <- liftIO $ readIORef (hsc_EPS hsc_env)
1170 return $! lookupType (hsc_dflags hsc_env)
1171 (hsc_HPT hsc_env) (eps_PTE eps) name
1172
1173 modInfoIface :: ModuleInfo -> Maybe ModIface
1174 modInfoIface = minf_iface
1175
1176 -- | Retrieve module safe haskell mode
1177 modInfoSafe :: ModuleInfo -> SafeHaskellMode
1178 modInfoSafe = minf_safe
1179
1180 #ifdef GHCI
1181 modInfoModBreaks :: ModuleInfo -> ModBreaks
1182 modInfoModBreaks = minf_modBreaks
1183 #endif
1184
1185 isDictonaryId :: Id -> Bool
1186 isDictonaryId id
1187 = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
1188
1189 -- | Looks up a global name: that is, any top-level name in any
1190 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1191 -- the interactive context, and therefore does not require a preceding
1192 -- 'setContext'.
1193 lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
1194 lookupGlobalName name = withSession $ \hsc_env -> do
1195 liftIO $ lookupTypeHscEnv hsc_env name
1196
1197 findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
1198 findGlobalAnns deserialize target = withSession $ \hsc_env -> do
1199 ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
1200 return (findAnns deserialize ann_env target)
1201
1202 #ifdef GHCI
1203 -- | get the GlobalRdrEnv for a session
1204 getGRE :: GhcMonad m => m GlobalRdrEnv
1205 getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
1206 #endif
1207
1208 -- -----------------------------------------------------------------------------
1209
1210 {- ToDo: Move the primary logic here to compiler/main/Packages.hs
1211 -- | Return all /external/ modules available in the package database.
1212 -- Modules from the current session (i.e., from the 'HomePackageTable') are
1213 -- not included. This includes module names which are reexported by packages.
1214 packageDbModules :: GhcMonad m =>
1215 Bool -- ^ Only consider exposed packages.
1216 -> m [Module]
1217 packageDbModules only_exposed = do
1218 dflags <- getSessionDynFlags
1219 let pkgs = eltsUFM (pkgIdMap (pkgState dflags))
1220 return $
1221 [ mkModule pid modname
1222 | p <- pkgs
1223 , not only_exposed || exposed p
1224 , let pid = packageConfigId p
1225 , modname <- exposedModules p
1226 ++ map exportName (reexportedModules p) ]
1227 -}
1228
1229 -- -----------------------------------------------------------------------------
1230 -- Misc exported utils
1231
1232 dataConType :: DataCon -> Type
1233 dataConType dc = idType (dataConWrapId dc)
1234
1235 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1236 pprParenSymName :: NamedThing a => a -> SDoc
1237 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1238
1239 -- ----------------------------------------------------------------------------
1240
1241 #if 0
1242
1243 -- ToDo:
1244 -- - Data and Typeable instances for HsSyn.
1245
1246 -- ToDo: check for small transformations that happen to the syntax in
1247 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1248
1249 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1250 -- to get from TyCons, Ids etc. to TH syntax (reify).
1251
1252 -- :browse will use either lm_toplev or inspect lm_interface, depending
1253 -- on whether the module is interpreted or not.
1254
1255 #endif
1256
1257 -- Extract the filename, stringbuffer content and dynflags associed to a module
1258 --
1259 -- XXX: Explain pre-conditions
1260 getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
1261 getModuleSourceAndFlags mod = do
1262 m <- getModSummary (moduleName mod)
1263 case ml_hs_file $ ms_location m of
1264 Nothing -> do dflags <- getDynFlags
1265 liftIO $ throwIO $ mkApiErr dflags (text "No source available for module " <+> ppr mod)
1266 Just sourceFile -> do
1267 source <- liftIO $ hGetStringBuffer sourceFile
1268 return (sourceFile, source, ms_hspp_opts m)
1269
1270
1271 -- | Return module source as token stream, including comments.
1272 --
1273 -- The module must be in the module graph and its source must be available.
1274 -- Throws a 'HscTypes.SourceError' on parse error.
1275 getTokenStream :: GhcMonad m => Module -> m [Located Token]
1276 getTokenStream mod = do
1277 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1278 let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
1279 case lexTokenStream source startLoc flags of
1280 POk _ ts -> return ts
1281 PFailed span err ->
1282 do dflags <- getDynFlags
1283 liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
1284
1285 -- | Give even more information on the source than 'getTokenStream'
1286 -- This function allows reconstructing the source completely with
1287 -- 'showRichTokenStream'.
1288 getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
1289 getRichTokenStream mod = do
1290 (sourceFile, source, flags) <- getModuleSourceAndFlags mod
1291 let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
1292 case lexTokenStream source startLoc flags of
1293 POk _ ts -> return $ addSourceToTokens startLoc source ts
1294 PFailed span err ->
1295 do dflags <- getDynFlags
1296 liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
1297
1298 -- | Given a source location and a StringBuffer corresponding to this
1299 -- location, return a rich token stream with the source associated to the
1300 -- tokens.
1301 addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token]
1302 -> [(Located Token, String)]
1303 addSourceToTokens _ _ [] = []
1304 addSourceToTokens loc buf (t@(L span _) : ts)
1305 = case span of
1306 UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts
1307 RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts
1308 where
1309 (newLoc, newBuf, str) = go "" loc buf
1310 start = realSrcSpanStart s
1311 end = realSrcSpanEnd s
1312 go acc loc buf | loc < start = go acc nLoc nBuf
1313 | start <= loc && loc < end = go (ch:acc) nLoc nBuf
1314 | otherwise = (loc, buf, reverse acc)
1315 where (ch, nBuf) = nextChar buf
1316 nLoc = advanceSrcLoc loc ch
1317
1318
1319 -- | Take a rich token stream such as produced from 'getRichTokenStream' and
1320 -- return source code almost identical to the original code (except for
1321 -- insignificant whitespace.)
1322 showRichTokenStream :: [(Located Token, String)] -> String
1323 showRichTokenStream ts = go startLoc ts ""
1324 where sourceFile = getFile $ map (getLoc . fst) ts
1325 getFile [] = panic "showRichTokenStream: No source file found"
1326 getFile (UnhelpfulSpan _ : xs) = getFile xs
1327 getFile (RealSrcSpan s : _) = srcSpanFile s
1328 startLoc = mkRealSrcLoc sourceFile 1 1
1329 go _ [] = id
1330 go loc ((L span _, str):ts)
1331 = case span of
1332 UnhelpfulSpan _ -> go loc ts
1333 RealSrcSpan s
1334 | locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
1335 . (str ++)
1336 . go tokEnd ts
1337 | otherwise -> ((replicate (tokLine - locLine) '\n') ++)
1338 . ((replicate (tokCol - 1) ' ') ++)
1339 . (str ++)
1340 . go tokEnd ts
1341 where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
1342 (tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
1343 tokEnd = realSrcSpanEnd s
1344
1345 -- -----------------------------------------------------------------------------
1346 -- Interactive evaluation
1347
1348 -- | Takes a 'ModuleName' and possibly a 'PackageKey', and consults the
1349 -- filesystem and package database to find the corresponding 'Module',
1350 -- using the algorithm that is used for an @import@ declaration.
1351 --
1352 -- However, there is a twist for local modules, see #2682.
1353 --
1354 -- The full algorithm:
1355 -- IF it's a package qualified import for a REMOTE package (not @this_pkg@ or
1356 -- this), do a normal lookup.
1357 -- OTHERWISE see if it is ALREADY loaded, and use it if it is.
1358 -- OTHERWISE do a normal lookup, but reject the result if the found result
1359 -- is from the LOCAL package (@this_pkg@).
1360 --
1361 -- For signatures, we return the BACKING implementation to keep the API
1362 -- consistent with what we had before. (ToDo: create a new GHC API which
1363 -- can deal with signatures.)
1364 --
1365 findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1366 findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
1367 let
1368 dflags = hsc_dflags hsc_env
1369 this_pkg = thisPackage dflags
1370 --
1371 case maybe_pkg of
1372 Just pkg | fsToPackageKey pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
1373 res <- findImportedModule hsc_env mod_name maybe_pkg
1374 case res of
1375 FoundModule h -> return (fr_mod h)
1376 FoundSigs _ backing -> return backing
1377 err -> throwOneError $ noModError dflags noSrcSpan mod_name err
1378 _otherwise -> do
1379 home <- lookupLoadedHomeModule mod_name
1380 case home of
1381 -- TODO: This COULD be a signature
1382 Just m -> return m
1383 Nothing -> liftIO $ do
1384 res <- findImportedModule hsc_env mod_name maybe_pkg
1385 case res of
1386 FoundModule (FoundHs { fr_mod = m, fr_loc = loc })
1387 | modulePackageKey m /= this_pkg -> return m
1388 | otherwise -> modNotLoadedError dflags m loc
1389 FoundSigs (FoundHs { fr_loc = loc, fr_mod = m }:_) backing
1390 | modulePackageKey m /= this_pkg -> return backing
1391 | otherwise -> modNotLoadedError dflags m loc
1392 err -> throwOneError $ noModError dflags noSrcSpan mod_name err
1393
1394 modNotLoadedError :: DynFlags -> Module -> ModLocation -> IO a
1395 modNotLoadedError dflags m loc = throwGhcExceptionIO $ CmdLineError $ showSDoc dflags $
1396 text "module is not loaded:" <+>
1397 quotes (ppr (moduleName m)) <+>
1398 parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
1399
1400 -- | Like 'findModule', but differs slightly when the module refers to
1401 -- a source file, and the file has not been loaded via 'load'. In
1402 -- this case, 'findModule' will throw an error (module not loaded),
1403 -- but 'lookupModule' will check to see whether the module can also be
1404 -- found in a package, and if so, that package 'Module' will be
1405 -- returned. If not, the usual module-not-found error will be thrown.
1406 --
1407 lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
1408 lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
1409 lookupModule mod_name Nothing = withSession $ \hsc_env -> do
1410 home <- lookupLoadedHomeModule mod_name
1411 case home of
1412 -- TODO: This COULD be a signature
1413 Just m -> return m
1414 Nothing -> liftIO $ do
1415 res <- findExposedPackageModule hsc_env mod_name Nothing
1416 case res of
1417 FoundModule (FoundHs { fr_mod = m }) -> return m
1418 FoundSigs _ backing -> return backing
1419 err -> throwOneError $ noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
1420
1421 lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
1422 lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
1423 case lookupUFM (hsc_HPT hsc_env) mod_name of
1424 Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
1425 _not_a_home_module -> return Nothing
1426
1427 #ifdef GHCI
1428 -- | Check that a module is safe to import (according to Safe Haskell).
1429 --
1430 -- We return True to indicate the import is safe and False otherwise
1431 -- although in the False case an error may be thrown first.
1432 isModuleTrusted :: GhcMonad m => Module -> m Bool
1433 isModuleTrusted m = withSession $ \hsc_env ->
1434 liftIO $ hscCheckSafe hsc_env m noSrcSpan
1435
1436 -- | Return if a module is trusted and the pkgs it depends on to be trusted.
1437 moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [PackageKey])
1438 moduleTrustReqs m = withSession $ \hsc_env ->
1439 liftIO $ hscGetSafe hsc_env m noSrcSpan
1440
1441 -- | Set the monad GHCi lifts user statements into.
1442 --
1443 -- Checks that a type (in string form) is an instance of the
1444 -- @GHC.GHCi.GHCiSandboxIO@ type class. Sets it to be the GHCi monad if it is,
1445 -- throws an error otherwise.
1446 setGHCiMonad :: GhcMonad m => String -> m ()
1447 setGHCiMonad name = withSession $ \hsc_env -> do
1448 ty <- liftIO $ hscIsGHCiMonad hsc_env name
1449 modifySession $ \s ->
1450 let ic = (hsc_IC s) { ic_monad = ty }
1451 in s { hsc_IC = ic }
1452
1453 getHistorySpan :: GhcMonad m => History -> m SrcSpan
1454 getHistorySpan h = withSession $ \hsc_env ->
1455 return $ InteractiveEval.getHistorySpan hsc_env h
1456
1457 obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
1458 obtainTermFromVal bound force ty a = withSession $ \hsc_env ->
1459 liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
1460
1461 obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
1462 obtainTermFromId bound force id = withSession $ \hsc_env ->
1463 liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id
1464
1465 #endif
1466
1467 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1468 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1469 lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
1470 lookupName name =
1471 withSession $ \hsc_env ->
1472 liftIO $ hscTcRcLookupName hsc_env name
1473
1474 -- -----------------------------------------------------------------------------
1475 -- Pure API
1476
1477 -- | A pure interface to the module parser.
1478 --
1479 parser :: String -- ^ Haskell module source text (full Unicode is supported)
1480 -> DynFlags -- ^ the flags
1481 -> FilePath -- ^ the filename (for source locations)
1482 -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
1483
1484 parser str dflags filename =
1485 let
1486 loc = mkRealSrcLoc (mkFastString filename) 1 1
1487 buf = stringToStringBuffer str
1488 in
1489 case unP Parser.parseModule (mkPState dflags buf loc) of
1490
1491 PFailed span err ->
1492 Left (unitBag (mkPlainErrMsg dflags span err))
1493
1494 POk pst rdr_module ->
1495 let (warns,_) = getMessages pst in
1496 Right (warns, rdr_module)
1497