Added the new :breakpoint continue option
[ghc.git] / compiler / main / GHC.hs
1 -- -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow, 2005
4 --
5 -- The GHC API
6 --
7 -- -----------------------------------------------------------------------------
8
9 module GHC (
10 -- * Initialisation
11 Session,
12 defaultErrorHandler,
13 defaultCleanupHandler,
14 newSession,
15
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), GhcMode(..), HscTarget(..), dopt,
18 parseDynamicFlags,
19 getSessionDynFlags,
20 setSessionDynFlags,
21
22 -- * Targets
23 Target(..), TargetId(..), Phase,
24 setTargets,
25 getTargets,
26 addTarget,
27 removeTarget,
28 guessTarget,
29
30 -- * Extending the program scope
31 extendGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
32 setGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
33 extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
34 setGlobalTypeScope, -- :: Session -> [Id] -> IO ()
35
36 -- * Loading\/compiling the program
37 depanal,
38 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
39 workingDirectoryChanged,
40 checkModule, CheckedModule(..),
41 TypecheckedSource, ParsedSource, RenamedSource,
42
43 -- * Parsing Haddock comments
44 parseHaddockComment,
45
46 -- * Inspecting the module structure of the program
47 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
48 getModuleGraph,
49 isLoaded,
50 topSortModuleGraph,
51
52 -- * Inspecting modules
53 ModuleInfo,
54 getModuleInfo,
55 modInfoTyThings,
56 modInfoTopLevelScope,
57 modInfoPrintUnqualified,
58 modInfoExports,
59 modInfoInstances,
60 modInfoIsExportedName,
61 modInfoLookupName,
62 #if defined(GHCI)
63 modInfoBkptSites,
64 #endif
65 lookupGlobalName,
66
67 -- * Printing
68 PrintUnqualified, alwaysQualify,
69
70 -- * Interactive evaluation
71 getBindings, getPrintUnqual,
72 findModule,
73 #ifdef GHCI
74 setContext, getContext,
75 getNamesInScope,
76 getRdrNamesInScope,
77 moduleIsInterpreted,
78 getInfo,
79 exprType,
80 typeKind,
81 parseName,
82 RunResult(..),
83 runStmt,
84 showModule,
85 isModuleInterpreted,
86 compileExpr, HValue, dynCompileExpr,
87 lookupName,
88
89 getBreakpointHandler, setBreakpointHandler,
90 obtainTerm,
91 #endif
92
93 -- * Abstract syntax elements
94
95 -- ** Packages
96 PackageId,
97
98 -- ** Modules
99 Module, mkModule, pprModule, moduleName, modulePackageId,
100 ModuleName, mkModuleName, moduleNameString,
101
102 -- ** Names
103 Name,
104 nameModule, pprParenSymName, nameSrcLoc,
105 NamedThing(..),
106 RdrName(Qual,Unqual),
107
108 -- ** Identifiers
109 Id, idType,
110 isImplicitId, isDeadBinder,
111 isExportedId, isLocalId, isGlobalId,
112 isRecordSelector,
113 isPrimOpId, isFCallId, isClassOpId_maybe,
114 isDataConWorkId, idDataCon,
115 isBottomingId, isDictonaryId,
116 recordSelectorFieldLabel,
117
118 -- ** Type constructors
119 TyCon,
120 tyConTyVars, tyConDataCons, tyConArity,
121 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
122 isOpenTyCon,
123 synTyConDefn, synTyConType, synTyConResKind,
124
125 -- ** Type variables
126 TyVar,
127 alphaTyVars,
128
129 -- ** Data constructors
130 DataCon,
131 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
132 dataConIsInfix, isVanillaDataCon,
133 dataConStrictMarks,
134 StrictnessMark(..), isMarkedStrict,
135
136 -- ** Classes
137 Class,
138 classMethods, classSCTheta, classTvsFds,
139 pprFundeps,
140
141 -- ** Instances
142 Instance,
143 instanceDFunId, pprInstance, pprInstanceHdr,
144
145 -- ** Types and Kinds
146 Type, dropForAlls, splitForAllTys, funResultTy,
147 pprParendType, pprTypeApp,
148 Kind,
149 PredType,
150 ThetaType, pprThetaArrow,
151
152 -- ** Entities
153 TyThing(..),
154
155 -- ** Syntax
156 module HsSyn, -- ToDo: remove extraneous bits
157
158 -- ** Fixities
159 FixityDirection(..),
160 defaultFixity, maxPrecedence,
161 negateFixity,
162 compareFixity,
163
164 -- ** Source locations
165 SrcLoc, pprDefnLoc,
166
167 -- * Exceptions
168 GhcException(..), showGhcException,
169
170 -- * Miscellaneous
171 sessionHscEnv,
172 cyclicModuleErr,
173 ) where
174
175 {-
176 ToDo:
177
178 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
179 * what StaticFlags should we expose, if any?
180 -}
181
182 #include "HsVersions.h"
183
184 #ifdef GHCI
185 import RtClosureInspect ( cvObtainTerm, Term )
186 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
187 tcRnLookupName, getModuleExports )
188 import RdrName ( plusGlobalRdrEnv, Provenance(..),
189 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
190 mkGlobalRdrEnv )
191 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
192 import Name ( nameOccName )
193 import Type ( tidyType )
194 import Var ( varName )
195 import VarEnv ( emptyTidyEnv )
196 import GHC.Exts ( unsafeCoerce# )
197
198 -- For breakpoints
199 import Breakpoints ( SiteNumber, Coord, nullBkptHandler,
200 BkptHandler(..), BkptLocation, noDbgSites )
201 import Linker ( initDynLinker )
202 import PrelNames ( breakpointJumpName, breakpointCondJumpName,
203 breakpointAutoJumpName )
204
205 import GHC.Exts ( Int(..), Ptr(..), int2Addr#, indexArray# )
206 import GHC.Base ( Opaque(..) )
207 import Foreign.StablePtr( deRefStablePtr, castPtrToStablePtr )
208 import Foreign ( unsafePerformIO )
209 import Data.Maybe ( fromMaybe)
210 import qualified Linker
211
212 import Data.Dynamic ( Dynamic )
213 import Linker ( HValue, getHValue, extendLinkEnv )
214 #endif
215
216 import Packages ( initPackages )
217 import NameSet ( NameSet, nameSetToList, elemNameSet )
218 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..),
219 globalRdrEnvElts, extendGlobalRdrEnv,
220 emptyGlobalRdrEnv )
221 import HsSyn
222 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
223 pprThetaArrow, pprParendType, splitForAllTys,
224 pprTypeApp, funResultTy )
225 import Id ( Id, idType, isImplicitId, isDeadBinder,
226 isExportedId, isLocalId, isGlobalId,
227 isRecordSelector, recordSelectorFieldLabel,
228 isPrimOpId, isFCallId, isClassOpId_maybe,
229 isDataConWorkId, idDataCon,
230 isBottomingId )
231 import Var ( TyVar )
232 import TysPrim ( alphaTyVars )
233 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
234 isPrimTyCon, isFunTyCon, isOpenTyCon, tyConArity,
235 tyConTyVars, tyConDataCons, synTyConDefn,
236 synTyConType, synTyConResKind )
237 import Class ( Class, classSCTheta, classTvsFds, classMethods )
238 import FunDeps ( pprFundeps )
239 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
240 dataConFieldLabels, dataConStrictMarks,
241 dataConIsInfix, isVanillaDataCon )
242 import Name ( Name, nameModule, NamedThing(..), nameSrcLoc )
243 import OccName ( parenSymOcc )
244 import NameEnv ( nameEnvElts )
245 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
246 import SrcLoc
247 import DriverPipeline
248 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
249 import HeaderInfo ( getImports, getOptions )
250 import Finder
251 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
252 import HscTypes
253 import DynFlags
254 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
255 cleanTempDirs )
256 import Module
257 import UniqFM
258 import PackageConfig ( PackageId, stringToPackageId )
259 import FiniteMap
260 import Panic
261 import Digraph
262 import Bag ( unitBag, listToBag )
263 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
264 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
265 WarnMsg )
266 import qualified ErrUtils
267 import Util
268 import StringBuffer ( StringBuffer, hGetStringBuffer )
269 import Outputable
270 import BasicTypes
271 import TcType ( tcSplitSigmaTy, isDictTy )
272 import Maybes ( expectJust, mapCatMaybes )
273 import HaddockParse ( parseHaddockParagraphs, parseHaddockString )
274 import HaddockLex ( tokenise )
275
276 import Control.Concurrent
277 import System.Directory ( getModificationTime, doesFileExist )
278 import Data.Maybe ( isJust, isNothing )
279 import Data.List ( partition, nub )
280 import qualified Data.List as List
281 import Control.Monad ( unless, when )
282 import System.Exit ( exitWith, ExitCode(..) )
283 import System.Time ( ClockTime )
284 import Control.Exception as Exception hiding (handle)
285 import Data.IORef
286 import System.IO
287 import System.IO.Error ( isDoesNotExistError )
288 import Prelude hiding (init)
289
290 #if __GLASGOW_HASKELL__ < 600
291 import System.IO as System.IO.Error ( try )
292 #else
293 import System.IO.Error ( try )
294 #endif
295
296 -- -----------------------------------------------------------------------------
297 -- Exception handlers
298
299 -- | Install some default exception handlers and run the inner computation.
300 -- Unless you want to handle exceptions yourself, you should wrap this around
301 -- the top level of your program. The default handlers output the error
302 -- message(s) to stderr and exit cleanly.
303 defaultErrorHandler :: DynFlags -> IO a -> IO a
304 defaultErrorHandler dflags inner =
305 -- top-level exception handler: any unrecognised exception is a compiler bug.
306 handle (\exception -> do
307 hFlush stdout
308 case exception of
309 -- an IO exception probably isn't our fault, so don't panic
310 IOException _ ->
311 fatalErrorMsg dflags (text (show exception))
312 AsyncException StackOverflow ->
313 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
314 _other ->
315 fatalErrorMsg dflags (text (show (Panic (show exception))))
316 exitWith (ExitFailure 1)
317 ) $
318
319 -- program errors: messages with locations attached. Sometimes it is
320 -- convenient to just throw these as exceptions.
321 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
322 exitWith (ExitFailure 1)) $
323
324 -- error messages propagated as exceptions
325 handleDyn (\dyn -> do
326 hFlush stdout
327 case dyn of
328 PhaseFailed _ code -> exitWith code
329 Interrupted -> exitWith (ExitFailure 1)
330 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
331 exitWith (ExitFailure 1)
332 ) $
333 inner
334
335 -- | Install a default cleanup handler to remove temporary files
336 -- deposited by a GHC run. This is seperate from
337 -- 'defaultErrorHandler', because you might want to override the error
338 -- handling, but still get the ordinary cleanup behaviour.
339 defaultCleanupHandler :: DynFlags -> IO a -> IO a
340 defaultCleanupHandler dflags inner =
341 -- make sure we clean up after ourselves
342 later (unless (dopt Opt_KeepTmpFiles dflags) $
343 do cleanTempFiles dflags
344 cleanTempDirs dflags
345 )
346 -- exceptions will be blocked while we clean the temporary files,
347 -- so there shouldn't be any difficulty if we receive further
348 -- signals.
349 inner
350
351
352 #if defined(GHCI)
353 GLOBAL_VAR(v_bkptLinkEnv, [], [(Name, HValue)])
354 -- stores the current breakpoint handler to help setContext to
355 -- restore it after a context change
356 #endif
357
358 -- | Starts a new session. A session consists of a set of loaded
359 -- modules, a set of options (DynFlags), and an interactive context.
360 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
361 -- code".
362 newSession :: GhcMode -> Maybe FilePath -> IO Session
363 newSession mode mb_top_dir = do
364 -- catch ^C
365 main_thread <- myThreadId
366 modifyMVar_ interruptTargetThread (return . (main_thread :))
367 installSignalHandlers
368
369 dflags0 <- initSysTools mb_top_dir defaultDynFlags
370 dflags <- initDynFlags dflags0
371 env <- newHscEnv dflags{ ghcMode=mode }
372 ref <- newIORef env
373 return (Session ref)
374
375 -- tmp: this breaks the abstraction, but required because DriverMkDepend
376 -- needs to call the Finder. ToDo: untangle this.
377 sessionHscEnv :: Session -> IO HscEnv
378 sessionHscEnv (Session ref) = readIORef ref
379
380 withSession :: Session -> (HscEnv -> IO a) -> IO a
381 withSession (Session ref) f = do h <- readIORef ref; f h
382
383 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
384 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
385
386 -- -----------------------------------------------------------------------------
387 -- Flags & settings
388
389 -- | Grabs the DynFlags from the Session
390 getSessionDynFlags :: Session -> IO DynFlags
391 getSessionDynFlags s = withSession s (return . hsc_dflags)
392
393 -- | Updates the DynFlags in a Session. This also reads
394 -- the package database (unless it has already been read),
395 -- and prepares the compilers knowledge about packages. It
396 -- can be called again to load new packages: just add new
397 -- package flags to (packageFlags dflags).
398 --
399 -- Returns a list of new packages that may need to be linked in using
400 -- the dynamic linker (see 'linkPackages') as a result of new package
401 -- flags. If you are not doing linking or doing static linking, you
402 -- can ignore the list of packages returned.
403 --
404 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
405 setSessionDynFlags (Session ref) dflags = do
406 hsc_env <- readIORef ref
407 (dflags', preload) <- initPackages dflags
408 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
409 return preload
410
411 -- | If there is no -o option, guess the name of target executable
412 -- by using top-level source file name as a base.
413 guessOutputFile :: Session -> IO ()
414 guessOutputFile s = modifySession s $ \env ->
415 let dflags = hsc_dflags env
416 mod_graph = hsc_mod_graph env
417 mainModuleSrcPath, guessedName :: Maybe String
418 mainModuleSrcPath = do
419 let isMain = (== mainModIs dflags) . ms_mod
420 [ms] <- return (filter isMain mod_graph)
421 ml_hs_file (ms_location ms)
422 guessedName = fmap basenameOf mainModuleSrcPath
423 in
424 case outputFile dflags of
425 Just _ -> env
426 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
427
428 -- -----------------------------------------------------------------------------
429 -- Targets
430
431 -- ToDo: think about relative vs. absolute file paths. And what
432 -- happens when the current directory changes.
433
434 -- | Sets the targets for this session. Each target may be a module name
435 -- or a filename. The targets correspond to the set of root modules for
436 -- the program\/library. Unloading the current program is achieved by
437 -- setting the current set of targets to be empty, followed by load.
438 setTargets :: Session -> [Target] -> IO ()
439 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
440
441 -- | returns the current set of targets
442 getTargets :: Session -> IO [Target]
443 getTargets s = withSession s (return . hsc_targets)
444
445 -- | Add another target
446 addTarget :: Session -> Target -> IO ()
447 addTarget s target
448 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
449
450 -- | Remove a target
451 removeTarget :: Session -> TargetId -> IO ()
452 removeTarget s target_id
453 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
454 where
455 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
456
457 -- Attempts to guess what Target a string refers to. This function implements
458 -- the --make/GHCi command-line syntax for filenames:
459 --
460 -- - if the string looks like a Haskell source filename, then interpret
461 -- it as such
462 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
463 -- then use that
464 -- - otherwise interpret the string as a module name
465 --
466 guessTarget :: String -> Maybe Phase -> IO Target
467 guessTarget file (Just phase)
468 = return (Target (TargetFile file (Just phase)) Nothing)
469 guessTarget file Nothing
470 | isHaskellSrcFilename file
471 = return (Target (TargetFile file Nothing) Nothing)
472 | otherwise
473 = do exists <- doesFileExist hs_file
474 if exists
475 then return (Target (TargetFile hs_file Nothing) Nothing)
476 else do
477 exists <- doesFileExist lhs_file
478 if exists
479 then return (Target (TargetFile lhs_file Nothing) Nothing)
480 else do
481 return (Target (TargetModule (mkModuleName file)) Nothing)
482 where
483 hs_file = file `joinFileExt` "hs"
484 lhs_file = file `joinFileExt` "lhs"
485
486 -- -----------------------------------------------------------------------------
487 -- Extending the program scope
488
489 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
490 extendGlobalRdrScope session rdrElts
491 = modifySession session $ \hscEnv ->
492 let global_rdr = hsc_global_rdr_env hscEnv
493 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
494
495 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
496 setGlobalRdrScope session rdrElts
497 = modifySession session $ \hscEnv ->
498 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
499
500 extendGlobalTypeScope :: Session -> [Id] -> IO ()
501 extendGlobalTypeScope session ids
502 = modifySession session $ \hscEnv ->
503 let global_type = hsc_global_type_env hscEnv
504 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
505
506 setGlobalTypeScope :: Session -> [Id] -> IO ()
507 setGlobalTypeScope session ids
508 = modifySession session $ \hscEnv ->
509 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
510
511 -- -----------------------------------------------------------------------------
512 -- Parsing Haddock comments
513
514 parseHaddockComment :: String -> Either String (HsDoc RdrName)
515 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
516
517 -- -----------------------------------------------------------------------------
518 -- Loading the program
519
520 -- Perform a dependency analysis starting from the current targets
521 -- and update the session with the new module graph.
522 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
523 depanal (Session ref) excluded_mods allow_dup_roots = do
524 hsc_env <- readIORef ref
525 let
526 dflags = hsc_dflags hsc_env
527 gmode = ghcMode (hsc_dflags hsc_env)
528 targets = hsc_targets hsc_env
529 old_graph = hsc_mod_graph hsc_env
530
531 showPass dflags "Chasing dependencies"
532 when (gmode == BatchCompile) $
533 debugTraceMsg dflags 2 (hcat [
534 text "Chasing modules from: ",
535 hcat (punctuate comma (map pprTarget targets))])
536
537 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
538 case r of
539 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
540 _ -> return ()
541 return r
542
543 {-
544 -- | The result of load.
545 data LoadResult
546 = LoadOk Errors -- ^ all specified targets were loaded successfully.
547 | LoadFailed Errors -- ^ not all modules were loaded.
548
549 type Errors = [String]
550
551 data ErrMsg = ErrMsg {
552 errMsgSeverity :: Severity, -- warning, error, etc.
553 errMsgSpans :: [SrcSpan],
554 errMsgShortDoc :: Doc,
555 errMsgExtraInfo :: Doc
556 }
557 -}
558
559 data LoadHowMuch
560 = LoadAllTargets
561 | LoadUpTo ModuleName
562 | LoadDependenciesOf ModuleName
563
564 -- | Try to load the program. If a Module is supplied, then just
565 -- attempt to load up to this target. If no Module is supplied,
566 -- then try to load all targets.
567 load :: Session -> LoadHowMuch -> IO SuccessFlag
568 load s@(Session ref) how_much
569 = do
570 -- Dependency analysis first. Note that this fixes the module graph:
571 -- even if we don't get a fully successful upsweep, the full module
572 -- graph is still retained in the Session. We can tell which modules
573 -- were successfully loaded by inspecting the Session's HPT.
574 mb_graph <- depanal s [] False
575 case mb_graph of
576 Just mod_graph -> load2 s how_much mod_graph
577 Nothing -> return Failed
578
579 load2 s@(Session ref) how_much mod_graph = do
580 guessOutputFile s
581 hsc_env <- readIORef ref
582
583 let hpt1 = hsc_HPT hsc_env
584 let dflags = hsc_dflags hsc_env
585 let ghci_mode = ghcMode dflags -- this never changes
586
587 -- The "bad" boot modules are the ones for which we have
588 -- B.hs-boot in the module graph, but no B.hs
589 -- The downsweep should have ensured this does not happen
590 -- (see msDeps)
591 let all_home_mods = [ms_mod_name s
592 | s <- mod_graph, not (isBootSummary s)]
593 #ifdef DEBUG
594 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
595 not (ms_mod_name s `elem` all_home_mods)]
596 #endif
597 ASSERT( null bad_boot_mods ) return ()
598
599 -- mg2_with_srcimps drops the hi-boot nodes, returning a
600 -- graph with cycles. Among other things, it is used for
601 -- backing out partially complete cycles following a failed
602 -- upsweep, and for removing from hpt all the modules
603 -- not in strict downwards closure, during calls to compile.
604 let mg2_with_srcimps :: [SCC ModSummary]
605 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
606
607 -- If we can determine that any of the {-# SOURCE #-} imports
608 -- are definitely unnecessary, then emit a warning.
609 warnUnnecessarySourceImports dflags mg2_with_srcimps
610
611 let
612 -- check the stability property for each module.
613 stable_mods@(stable_obj,stable_bco)
614 | BatchCompile <- ghci_mode = ([],[])
615 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
616
617 -- prune bits of the HPT which are definitely redundant now,
618 -- to save space.
619 pruned_hpt = pruneHomePackageTable hpt1
620 (flattenSCCs mg2_with_srcimps)
621 stable_mods
622
623 evaluate pruned_hpt
624
625 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
626 text "Stable BCO:" <+> ppr stable_bco)
627
628 -- Unload any modules which are going to be re-linked this time around.
629 let stable_linkables = [ linkable
630 | m <- stable_obj++stable_bco,
631 Just hmi <- [lookupUFM pruned_hpt m],
632 Just linkable <- [hm_linkable hmi] ]
633 unload hsc_env stable_linkables
634
635 -- We could at this point detect cycles which aren't broken by
636 -- a source-import, and complain immediately, but it seems better
637 -- to let upsweep_mods do this, so at least some useful work gets
638 -- done before the upsweep is abandoned.
639 --hPutStrLn stderr "after tsort:\n"
640 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
641
642 -- Now do the upsweep, calling compile for each module in
643 -- turn. Final result is version 3 of everything.
644
645 -- Topologically sort the module graph, this time including hi-boot
646 -- nodes, and possibly just including the portion of the graph
647 -- reachable from the module specified in the 2nd argument to load.
648 -- This graph should be cycle-free.
649 -- If we're restricting the upsweep to a portion of the graph, we
650 -- also want to retain everything that is still stable.
651 let full_mg :: [SCC ModSummary]
652 full_mg = topSortModuleGraph False mod_graph Nothing
653
654 maybe_top_mod = case how_much of
655 LoadUpTo m -> Just m
656 LoadDependenciesOf m -> Just m
657 _ -> Nothing
658
659 partial_mg0 :: [SCC ModSummary]
660 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
661
662 -- LoadDependenciesOf m: we want the upsweep to stop just
663 -- short of the specified module (unless the specified module
664 -- is stable).
665 partial_mg
666 | LoadDependenciesOf mod <- how_much
667 = ASSERT( case last partial_mg0 of
668 AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
669 List.init partial_mg0
670 | otherwise
671 = partial_mg0
672
673 stable_mg =
674 [ AcyclicSCC ms
675 | AcyclicSCC ms <- full_mg,
676 ms_mod_name ms `elem` stable_obj++stable_bco,
677 ms_mod_name ms `notElem` [ ms_mod_name ms' |
678 AcyclicSCC ms' <- partial_mg ] ]
679
680 mg = stable_mg ++ partial_mg
681
682 -- clean up between compilations
683 let cleanup = cleanTempFilesExcept dflags
684 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
685
686 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
687 2 (ppr mg))
688 (upsweep_ok, hsc_env1, modsUpswept)
689 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
690 pruned_hpt stable_mods cleanup mg
691
692 -- Make modsDone be the summaries for each home module now
693 -- available; this should equal the domain of hpt3.
694 -- Get in in a roughly top .. bottom order (hence reverse).
695
696 let modsDone = reverse modsUpswept
697
698 -- Try and do linking in some form, depending on whether the
699 -- upsweep was completely or only partially successful.
700
701 if succeeded upsweep_ok
702
703 then
704 -- Easy; just relink it all.
705 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
706
707 -- Clean up after ourselves
708 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
709
710 -- Issue a warning for the confusing case where the user
711 -- said '-o foo' but we're not going to do any linking.
712 -- We attempt linking if either (a) one of the modules is
713 -- called Main, or (b) the user said -no-hs-main, indicating
714 -- that main() is going to come from somewhere else.
715 --
716 let ofile = outputFile dflags
717 let no_hs_main = dopt Opt_NoHsMain dflags
718 let
719 main_mod = mainModIs dflags
720 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
721 do_linking = a_root_is_Main || no_hs_main
722
723 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
724 debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
725 "but no output will be generated\n" ++
726 "because there is no " ++ moduleNameString (moduleName main_mod) ++ " module."))
727
728 -- link everything together
729 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
730
731 loadFinish Succeeded linkresult ref hsc_env1
732
733 else
734 -- Tricky. We need to back out the effects of compiling any
735 -- half-done cycles, both so as to clean up the top level envs
736 -- and to avoid telling the interactive linker to link them.
737 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
738
739 let modsDone_names
740 = map ms_mod modsDone
741 let mods_to_zap_names
742 = findPartiallyCompletedCycles modsDone_names
743 mg2_with_srcimps
744 let mods_to_keep
745 = filter ((`notElem` mods_to_zap_names).ms_mod)
746 modsDone
747
748 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
749 (hsc_HPT hsc_env1)
750
751 -- Clean up after ourselves
752 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
753
754 -- there should be no Nothings where linkables should be, now
755 ASSERT(all (isJust.hm_linkable)
756 (eltsUFM (hsc_HPT hsc_env))) do
757
758 -- Link everything together
759 linkresult <- link ghci_mode dflags False hpt4
760
761 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
762 loadFinish Failed linkresult ref hsc_env4
763
764 -- Finish up after a load.
765
766 -- If the link failed, unload everything and return.
767 loadFinish all_ok Failed ref hsc_env
768 = do unload hsc_env []
769 writeIORef ref $! discardProg hsc_env
770 return Failed
771
772 -- Empty the interactive context and set the module context to the topmost
773 -- newly loaded module, or the Prelude if none were loaded.
774 loadFinish all_ok Succeeded ref hsc_env
775 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
776 return all_ok
777
778
779 -- Forget the current program, but retain the persistent info in HscEnv
780 discardProg :: HscEnv -> HscEnv
781 discardProg hsc_env
782 = hsc_env { hsc_mod_graph = emptyMG,
783 hsc_IC = emptyInteractiveContext,
784 hsc_HPT = emptyHomePackageTable }
785
786 -- used to fish out the preprocess output files for the purposes of
787 -- cleaning up. The preprocessed file *might* be the same as the
788 -- source file, but that doesn't do any harm.
789 ppFilesFromSummaries summaries = map ms_hspp_file summaries
790
791 -- -----------------------------------------------------------------------------
792 -- Check module
793
794 data CheckedModule =
795 CheckedModule { parsedSource :: ParsedSource,
796 renamedSource :: Maybe RenamedSource,
797 typecheckedSource :: Maybe TypecheckedSource,
798 checkedModuleInfo :: Maybe ModuleInfo
799 }
800 -- ToDo: improvements that could be made here:
801 -- if the module succeeded renaming but not typechecking,
802 -- we can still get back the GlobalRdrEnv and exports, so
803 -- perhaps the ModuleInfo should be split up into separate
804 -- fields within CheckedModule.
805
806 type ParsedSource = Located (HsModule RdrName)
807 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
808 Maybe (HsDoc Name), HaddockModInfo Name)
809 type TypecheckedSource = LHsBinds Id
810
811 -- NOTE:
812 -- - things that aren't in the output of the typechecker right now:
813 -- - the export list
814 -- - the imports
815 -- - type signatures
816 -- - type/data/newtype declarations
817 -- - class declarations
818 -- - instances
819 -- - extra things in the typechecker's output:
820 -- - default methods are turned into top-level decls.
821 -- - dictionary bindings
822
823
824 -- | This is the way to get access to parsed and typechecked source code
825 -- for a module. 'checkModule' loads all the dependencies of the specified
826 -- module in the Session, and then attempts to typecheck the module. If
827 -- successful, it returns the abstract syntax for the module.
828 checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
829 checkModule session@(Session ref) mod = do
830 -- load up the dependencies first
831 r <- load session (LoadDependenciesOf mod)
832 if (failed r) then return Nothing else do
833
834 -- now parse & typecheck the module
835 hsc_env <- readIORef ref
836 let mg = hsc_mod_graph hsc_env
837 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
838 [] -> return Nothing
839 (ms:_) -> do
840 mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
841 case mbChecked of
842 Nothing -> return Nothing
843 Just (HscChecked parsed renamed Nothing) ->
844 return (Just (CheckedModule {
845 parsedSource = parsed,
846 renamedSource = renamed,
847 typecheckedSource = Nothing,
848 checkedModuleInfo = Nothing }))
849 Just (HscChecked parsed renamed
850 (Just (tc_binds, rdr_env, details))) -> do
851 let minf = ModuleInfo {
852 minf_type_env = md_types details,
853 minf_exports = availsToNameSet $
854 md_exports details,
855 minf_rdr_env = Just rdr_env,
856 minf_instances = md_insts details
857 #ifdef GHCI
858 ,minf_dbg_sites = noDbgSites
859 #endif
860 }
861 return (Just (CheckedModule {
862 parsedSource = parsed,
863 renamedSource = renamed,
864 typecheckedSource = Just tc_binds,
865 checkedModuleInfo = Just minf }))
866
867 -- ---------------------------------------------------------------------------
868 -- Unloading
869
870 unload :: HscEnv -> [Linkable] -> IO ()
871 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
872 = case ghcMode (hsc_dflags hsc_env) of
873 BatchCompile -> return ()
874 JustTypecheck -> return ()
875 #ifdef GHCI
876 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
877 #else
878 Interactive -> panic "unload: no interpreter"
879 #endif
880 other -> panic "unload: strange mode"
881
882 -- -----------------------------------------------------------------------------
883 -- checkStability
884
885 {-
886 Stability tells us which modules definitely do not need to be recompiled.
887 There are two main reasons for having stability:
888
889 - avoid doing a complete upsweep of the module graph in GHCi when
890 modules near the bottom of the tree have not changed.
891
892 - to tell GHCi when it can load object code: we can only load object code
893 for a module when we also load object code fo all of the imports of the
894 module. So we need to know that we will definitely not be recompiling
895 any of these modules, and we can use the object code.
896
897 NB. stability is of no importance to BatchCompile at all, only Interactive.
898 (ToDo: what about JustTypecheck?)
899
900 The stability check is as follows. Both stableObject and
901 stableBCO are used during the upsweep phase later.
902
903 -------------------
904 stable m = stableObject m || stableBCO m
905
906 stableObject m =
907 all stableObject (imports m)
908 && old linkable does not exist, or is == on-disk .o
909 && date(on-disk .o) > date(.hs)
910
911 stableBCO m =
912 all stable (imports m)
913 && date(BCO) > date(.hs)
914 -------------------
915
916 These properties embody the following ideas:
917
918 - if a module is stable:
919 - if it has been compiled in a previous pass (present in HPT)
920 then it does not need to be compiled or re-linked.
921 - if it has not been compiled in a previous pass,
922 then we only need to read its .hi file from disk and
923 link it to produce a ModDetails.
924
925 - if a modules is not stable, we will definitely be at least
926 re-linking, and possibly re-compiling it during the upsweep.
927 All non-stable modules can (and should) therefore be unlinked
928 before the upsweep.
929
930 - Note that objects are only considered stable if they only depend
931 on other objects. We can't link object code against byte code.
932 -}
933
934 checkStability
935 :: HomePackageTable -- HPT from last compilation
936 -> [SCC ModSummary] -- current module graph (cyclic)
937 -> [ModuleName] -- all home modules
938 -> ([ModuleName], -- stableObject
939 [ModuleName]) -- stableBCO
940
941 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
942 where
943 checkSCC (stable_obj, stable_bco) scc0
944 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
945 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
946 | otherwise = (stable_obj, stable_bco)
947 where
948 scc = flattenSCC scc0
949 scc_mods = map ms_mod_name scc
950 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
951
952 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
953 -- all imports outside the current SCC, but in the home pkg
954
955 stable_obj_imps = map (`elem` stable_obj) scc_allimps
956 stable_bco_imps = map (`elem` stable_bco) scc_allimps
957
958 stableObjects =
959 and stable_obj_imps
960 && all object_ok scc
961
962 stableBCOs =
963 and (zipWith (||) stable_obj_imps stable_bco_imps)
964 && all bco_ok scc
965
966 object_ok ms
967 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
968 && same_as_prev t
969 | otherwise = False
970 where
971 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
972 Just hmi | Just l <- hm_linkable hmi
973 -> isObjectLinkable l && t == linkableTime l
974 _other -> True
975 -- why '>=' rather than '>' above? If the filesystem stores
976 -- times to the nearset second, we may occasionally find that
977 -- the object & source have the same modification time,
978 -- especially if the source was automatically generated
979 -- and compiled. Using >= is slightly unsafe, but it matches
980 -- make's behaviour.
981
982 bco_ok ms
983 = case lookupUFM hpt (ms_mod_name ms) of
984 Just hmi | Just l <- hm_linkable hmi ->
985 not (isObjectLinkable l) &&
986 linkableTime l >= ms_hs_date ms
987 _other -> False
988
989 ms_allimps :: ModSummary -> [ModuleName]
990 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
991
992 -- -----------------------------------------------------------------------------
993 -- Prune the HomePackageTable
994
995 -- Before doing an upsweep, we can throw away:
996 --
997 -- - For non-stable modules:
998 -- - all ModDetails, all linked code
999 -- - all unlinked code that is out of date with respect to
1000 -- the source file
1001 --
1002 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1003 -- space at the end of the upsweep, because the topmost ModDetails of the
1004 -- old HPT holds on to the entire type environment from the previous
1005 -- compilation.
1006
1007 pruneHomePackageTable
1008 :: HomePackageTable
1009 -> [ModSummary]
1010 -> ([ModuleName],[ModuleName])
1011 -> HomePackageTable
1012
1013 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1014 = mapUFM prune hpt
1015 where prune hmi
1016 | is_stable modl = hmi'
1017 | otherwise = hmi'{ hm_details = emptyModDetails }
1018 where
1019 modl = moduleName (mi_module (hm_iface hmi))
1020 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1021 = hmi{ hm_linkable = Nothing }
1022 | otherwise
1023 = hmi
1024 where ms = expectJust "prune" (lookupUFM ms_map modl)
1025
1026 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1027
1028 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1029
1030 -- -----------------------------------------------------------------------------
1031
1032 -- Return (names of) all those in modsDone who are part of a cycle
1033 -- as defined by theGraph.
1034 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1035 findPartiallyCompletedCycles modsDone theGraph
1036 = chew theGraph
1037 where
1038 chew [] = []
1039 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
1040 chew ((CyclicSCC vs):rest)
1041 = let names_in_this_cycle = nub (map ms_mod vs)
1042 mods_in_this_cycle
1043 = nub ([done | done <- modsDone,
1044 done `elem` names_in_this_cycle])
1045 chewed_rest = chew rest
1046 in
1047 if notNull mods_in_this_cycle
1048 && length mods_in_this_cycle < length names_in_this_cycle
1049 then mods_in_this_cycle ++ chewed_rest
1050 else chewed_rest
1051
1052 -- -----------------------------------------------------------------------------
1053 -- The upsweep
1054
1055 -- This is where we compile each module in the module graph, in a pass
1056 -- from the bottom to the top of the graph.
1057
1058 -- There better had not be any cyclic groups here -- we check for them.
1059
1060 upsweep
1061 :: HscEnv -- Includes initially-empty HPT
1062 -> HomePackageTable -- HPT from last time round (pruned)
1063 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1064 -> IO () -- How to clean up unwanted tmp files
1065 -> [SCC ModSummary] -- Mods to do (the worklist)
1066 -> IO (SuccessFlag,
1067 HscEnv, -- With an updated HPT
1068 [ModSummary]) -- Mods which succeeded
1069
1070 upsweep hsc_env old_hpt stable_mods cleanup mods
1071 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1072
1073 upsweep' hsc_env old_hpt stable_mods cleanup
1074 [] _ _
1075 = return (Succeeded, hsc_env, [])
1076
1077 upsweep' hsc_env old_hpt stable_mods cleanup
1078 (CyclicSCC ms:_) _ _
1079 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1080 return (Failed, hsc_env, [])
1081
1082 upsweep' hsc_env old_hpt stable_mods cleanup
1083 (AcyclicSCC mod:mods) mod_index nmods
1084 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1085 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1086 -- (moduleEnvElts (hsc_HPT hsc_env)))
1087
1088 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1089 mod_index nmods
1090
1091 cleanup -- Remove unwanted tmp files between compilations
1092
1093 case mb_mod_info of
1094 Nothing -> return (Failed, hsc_env, [])
1095 Just mod_info -> do
1096 { let this_mod = ms_mod_name mod
1097
1098 -- Add new info to hsc_env
1099 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1100 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1101
1102 -- Space-saving: delete the old HPT entry
1103 -- for mod BUT if mod is a hs-boot
1104 -- node, don't delete it. For the
1105 -- interface, the HPT entry is probaby for the
1106 -- main Haskell source file. Deleting it
1107 -- would force .. (what?? --SDM)
1108 old_hpt1 | isBootSummary mod = old_hpt
1109 | otherwise = delFromUFM old_hpt this_mod
1110
1111 ; (restOK, hsc_env2, modOKs)
1112 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1113 mods (mod_index+1) nmods
1114 ; return (restOK, hsc_env2, mod:modOKs)
1115 }
1116
1117
1118 -- Compile a single module. Always produce a Linkable for it if
1119 -- successful. If no compilation happened, return the old Linkable.
1120 upsweep_mod :: HscEnv
1121 -> HomePackageTable
1122 -> ([ModuleName],[ModuleName])
1123 -> ModSummary
1124 -> Int -- index of module
1125 -> Int -- total number of modules
1126 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1127
1128 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1129 = do
1130 let
1131 this_mod_name = ms_mod_name summary
1132 this_mod = ms_mod summary
1133 mb_obj_date = ms_obj_date summary
1134 obj_fn = ml_obj_file (ms_location summary)
1135 hs_date = ms_hs_date summary
1136
1137 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1138 compile_it = upsweep_compile hsc_env old_hpt this_mod_name
1139 summary mod_index nmods
1140
1141 case ghcMode (hsc_dflags hsc_env) of
1142 BatchCompile ->
1143 case () of
1144 -- Batch-compilating is easy: just check whether we have
1145 -- an up-to-date object file. If we do, then the compiler
1146 -- needs to do a recompilation check.
1147 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1148 linkable <-
1149 findObjectLinkable this_mod obj_fn obj_date
1150 compile_it (Just linkable)
1151
1152 | otherwise ->
1153 compile_it Nothing
1154
1155 interactive ->
1156 case () of
1157 _ | is_stable_obj, isJust old_hmi ->
1158 return old_hmi
1159 -- object is stable, and we have an entry in the
1160 -- old HPT: nothing to do
1161
1162 | is_stable_obj, isNothing old_hmi -> do
1163 linkable <-
1164 findObjectLinkable this_mod obj_fn
1165 (expectJust "upseep1" mb_obj_date)
1166 compile_it (Just linkable)
1167 -- object is stable, but we need to load the interface
1168 -- off disk to make a HMI.
1169
1170 | is_stable_bco ->
1171 ASSERT(isJust old_hmi) -- must be in the old_hpt
1172 return old_hmi
1173 -- BCO is stable: nothing to do
1174
1175 | Just hmi <- old_hmi,
1176 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1177 linkableTime l >= ms_hs_date summary ->
1178 compile_it (Just l)
1179 -- we have an old BCO that is up to date with respect
1180 -- to the source: do a recompilation check as normal.
1181
1182 | otherwise ->
1183 compile_it Nothing
1184 -- no existing code at all: we must recompile.
1185 where
1186 is_stable_obj = this_mod_name `elem` stable_obj
1187 is_stable_bco = this_mod_name `elem` stable_bco
1188
1189 old_hmi = lookupUFM old_hpt this_mod_name
1190
1191 -- Run hsc to compile a module
1192 upsweep_compile hsc_env old_hpt this_mod summary
1193 mod_index nmods
1194 mb_old_linkable = do
1195 let
1196 -- The old interface is ok if it's in the old HPT
1197 -- a) we're compiling a source file, and the old HPT
1198 -- entry is for a source file
1199 -- b) we're compiling a hs-boot file
1200 -- Case (b) allows an hs-boot file to get the interface of its
1201 -- real source file on the second iteration of the compilation
1202 -- manager, but that does no harm. Otherwise the hs-boot file
1203 -- will always be recompiled
1204
1205 mb_old_iface
1206 = case lookupUFM old_hpt this_mod of
1207 Nothing -> Nothing
1208 Just hm_info | isBootSummary summary -> Just iface
1209 | not (mi_boot iface) -> Just iface
1210 | otherwise -> Nothing
1211 where
1212 iface = hm_iface hm_info
1213
1214 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1215 mod_index nmods
1216
1217 case compresult of
1218 -- Compilation failed. Compile may still have updated the PCS, tho.
1219 CompErrs -> return Nothing
1220
1221 -- Compilation "succeeded", and may or may not have returned a new
1222 -- linkable (depending on whether compilation was actually performed
1223 -- or not).
1224 CompOK new_details new_iface new_linkable
1225 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1226 hm_details = new_details,
1227 hm_linkable = new_linkable }
1228 return (Just new_info)
1229
1230
1231 -- Filter modules in the HPT
1232 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1233 retainInTopLevelEnvs keep_these hpt
1234 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1235 | mod <- keep_these
1236 , let mb_mod_info = lookupUFM hpt mod
1237 , isJust mb_mod_info ]
1238
1239 -- ---------------------------------------------------------------------------
1240 -- Topological sort of the module graph
1241
1242 topSortModuleGraph
1243 :: Bool -- Drop hi-boot nodes? (see below)
1244 -> [ModSummary]
1245 -> Maybe ModuleName
1246 -> [SCC ModSummary]
1247 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1248 -- The resulting list of strongly-connected-components is in topologically
1249 -- sorted order, starting with the module(s) at the bottom of the
1250 -- dependency graph (ie compile them first) and ending with the ones at
1251 -- the top.
1252 --
1253 -- Drop hi-boot nodes (first boolean arg)?
1254 --
1255 -- False: treat the hi-boot summaries as nodes of the graph,
1256 -- so the graph must be acyclic
1257 --
1258 -- True: eliminate the hi-boot nodes, and instead pretend
1259 -- the a source-import of Foo is an import of Foo
1260 -- The resulting graph has no hi-boot nodes, but can by cyclic
1261
1262 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1263 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1264 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1265 = stronglyConnComp (map vertex_fn (reachable graph root))
1266 where
1267 -- restrict the graph to just those modules reachable from
1268 -- the specified module. We do this by building a graph with
1269 -- the full set of nodes, and determining the reachable set from
1270 -- the specified node.
1271 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1272 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1273 root
1274 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1275 | otherwise = throwDyn (ProgramError "module does not exist")
1276
1277 moduleGraphNodes :: Bool -> [ModSummary]
1278 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1279 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1280 where
1281 -- Drop hs-boot nodes by using HsSrcFile as the key
1282 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1283 | otherwise = HsBootFile
1284
1285 -- We use integers as the keys for the SCC algorithm
1286 nodes :: [(ModSummary, Int, [Int])]
1287 nodes = [(s, expectJust "topSort" $
1288 lookup_key (ms_hsc_src s) (ms_mod_name s),
1289 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1290 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1291 (-- see [boot-edges] below
1292 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1293 then []
1294 else case lookup_key HsBootFile (ms_mod_name s) of
1295 Nothing -> []
1296 Just k -> [k])
1297 )
1298 | s <- summaries
1299 , not (isBootSummary s && drop_hs_boot_nodes) ]
1300 -- Drop the hi-boot ones if told to do so
1301
1302 -- [boot-edges] if this is a .hs and there is an equivalent
1303 -- .hs-boot, add a link from the former to the latter. This
1304 -- has the effect of detecting bogus cases where the .hs-boot
1305 -- depends on the .hs, by introducing a cycle. Additionally,
1306 -- it ensures that we will always process the .hs-boot before
1307 -- the .hs, and so the HomePackageTable will always have the
1308 -- most up to date information.
1309
1310 key_map :: NodeMap Int
1311 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1312 | s <- summaries]
1313 `zip` [1..])
1314
1315 lookup_key :: HscSource -> ModuleName -> Maybe Int
1316 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1317
1318 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1319 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1320 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1321 -- the IsBootInterface parameter True; else False
1322
1323
1324 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1325 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1326
1327 msKey :: ModSummary -> NodeKey
1328 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1329
1330 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1331 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1332
1333 nodeMapElts :: NodeMap a -> [a]
1334 nodeMapElts = eltsFM
1335
1336 ms_mod_name :: ModSummary -> ModuleName
1337 ms_mod_name = moduleName . ms_mod
1338
1339 -- If there are {-# SOURCE #-} imports between strongly connected
1340 -- components in the topological sort, then those imports can
1341 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1342 -- were necessary, then the edge would be part of a cycle.
1343 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1344 warnUnnecessarySourceImports dflags sccs =
1345 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1346 where check ms =
1347 let mods_in_this_cycle = map ms_mod_name ms in
1348 [ warn m i | m <- ms, i <- ms_srcimps m,
1349 unLoc i `notElem` mods_in_this_cycle ]
1350
1351 warn :: ModSummary -> Located ModuleName -> WarnMsg
1352 warn ms (L loc mod) =
1353 mkPlainErrMsg loc
1354 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1355 <+> quotes (ppr mod))
1356
1357 -----------------------------------------------------------------------------
1358 -- Downsweep (dependency analysis)
1359
1360 -- Chase downwards from the specified root set, returning summaries
1361 -- for all home modules encountered. Only follow source-import
1362 -- links.
1363
1364 -- We pass in the previous collection of summaries, which is used as a
1365 -- cache to avoid recalculating a module summary if the source is
1366 -- unchanged.
1367 --
1368 -- The returned list of [ModSummary] nodes has one node for each home-package
1369 -- module, plus one for any hs-boot files. The imports of these nodes
1370 -- are all there, including the imports of non-home-package modules.
1371
1372 downsweep :: HscEnv
1373 -> [ModSummary] -- Old summaries
1374 -> [ModuleName] -- Ignore dependencies on these; treat
1375 -- them as if they were package modules
1376 -> Bool -- True <=> allow multiple targets to have
1377 -- the same module name; this is
1378 -- very useful for ghc -M
1379 -> IO (Maybe [ModSummary])
1380 -- The elts of [ModSummary] all have distinct
1381 -- (Modules, IsBoot) identifiers, unless the Bool is true
1382 -- in which case there can be repeats
1383 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1384 = -- catch error messages and return them
1385 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1386 rootSummaries <- mapM getRootSummary roots
1387 let root_map = mkRootMap rootSummaries
1388 checkDuplicates root_map
1389 summs <- loop (concatMap msDeps rootSummaries) root_map
1390 return (Just summs)
1391 where
1392 roots = hsc_targets hsc_env
1393
1394 old_summary_map :: NodeMap ModSummary
1395 old_summary_map = mkNodeMap old_summaries
1396
1397 getRootSummary :: Target -> IO ModSummary
1398 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1399 = do exists <- doesFileExist file
1400 if exists
1401 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1402 else throwDyn $ mkPlainErrMsg noSrcSpan $
1403 text "can't find file:" <+> text file
1404 getRootSummary (Target (TargetModule modl) maybe_buf)
1405 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1406 (L rootLoc modl) maybe_buf excl_mods
1407 case maybe_summary of
1408 Nothing -> packageModErr modl
1409 Just s -> return s
1410
1411 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1412
1413 -- In a root module, the filename is allowed to diverge from the module
1414 -- name, so we have to check that there aren't multiple root files
1415 -- defining the same module (otherwise the duplicates will be silently
1416 -- ignored, leading to confusing behaviour).
1417 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1418 checkDuplicates root_map
1419 | allow_dup_roots = return ()
1420 | null dup_roots = return ()
1421 | otherwise = multiRootsErr (head dup_roots)
1422 where
1423 dup_roots :: [[ModSummary]] -- Each at least of length 2
1424 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1425
1426 loop :: [(Located ModuleName,IsBootInterface)]
1427 -- Work list: process these modules
1428 -> NodeMap [ModSummary]
1429 -- Visited set; the range is a list because
1430 -- the roots can have the same module names
1431 -- if allow_dup_roots is True
1432 -> IO [ModSummary]
1433 -- The result includes the worklist, except
1434 -- for those mentioned in the visited set
1435 loop [] done = return (concat (nodeMapElts done))
1436 loop ((wanted_mod, is_boot) : ss) done
1437 | Just summs <- lookupFM done key
1438 = if isSingleton summs then
1439 loop ss done
1440 else
1441 do { multiRootsErr summs; return [] }
1442 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1443 is_boot wanted_mod Nothing excl_mods
1444 ; case mb_s of
1445 Nothing -> loop ss done
1446 Just s -> loop (msDeps s ++ ss)
1447 (addToFM done key [s]) }
1448 where
1449 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1450
1451 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1452 mkRootMap summaries = addListToFM_C (++) emptyFM
1453 [ (msKey s, [s]) | s <- summaries ]
1454
1455 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1456 -- (msDeps s) returns the dependencies of the ModSummary s.
1457 -- A wrinkle is that for a {-# SOURCE #-} import we return
1458 -- *both* the hs-boot file
1459 -- *and* the source file
1460 -- as "dependencies". That ensures that the list of all relevant
1461 -- modules always contains B.hs if it contains B.hs-boot.
1462 -- Remember, this pass isn't doing the topological sort. It's
1463 -- just gathering the list of all relevant ModSummaries
1464 msDeps s =
1465 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1466 ++ [ (m,False) | m <- ms_imps s ]
1467
1468 -----------------------------------------------------------------------------
1469 -- Summarising modules
1470
1471 -- We have two types of summarisation:
1472 --
1473 -- * Summarise a file. This is used for the root module(s) passed to
1474 -- cmLoadModules. The file is read, and used to determine the root
1475 -- module name. The module name may differ from the filename.
1476 --
1477 -- * Summarise a module. We are given a module name, and must provide
1478 -- a summary. The finder is used to locate the file in which the module
1479 -- resides.
1480
1481 summariseFile
1482 :: HscEnv
1483 -> [ModSummary] -- old summaries
1484 -> FilePath -- source file name
1485 -> Maybe Phase -- start phase
1486 -> Maybe (StringBuffer,ClockTime)
1487 -> IO ModSummary
1488
1489 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1490 -- we can use a cached summary if one is available and the
1491 -- source file hasn't changed, But we have to look up the summary
1492 -- by source file, rather than module name as we do in summarise.
1493 | Just old_summary <- findSummaryBySourceFile old_summaries file
1494 = do
1495 let location = ms_location old_summary
1496
1497 -- return the cached summary if the source didn't change
1498 src_timestamp <- case maybe_buf of
1499 Just (_,t) -> return t
1500 Nothing -> getModificationTime file
1501 -- The file exists; we checked in getRootSummary above.
1502 -- If it gets removed subsequently, then this
1503 -- getModificationTime may fail, but that's the right
1504 -- behaviour.
1505
1506 if ms_hs_date old_summary == src_timestamp
1507 then do -- update the object-file timestamp
1508 obj_timestamp <- getObjTimestamp location False
1509 return old_summary{ ms_obj_date = obj_timestamp }
1510 else
1511 new_summary
1512
1513 | otherwise
1514 = new_summary
1515 where
1516 new_summary = do
1517 let dflags = hsc_dflags hsc_env
1518
1519 (dflags', hspp_fn, buf)
1520 <- preprocessFile dflags file mb_phase maybe_buf
1521
1522 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1523
1524 -- Make a ModLocation for this file
1525 location <- mkHomeModLocation dflags mod_name file
1526
1527 -- Tell the Finder cache where it is, so that subsequent calls
1528 -- to findModule will find it, even if it's not on any search path
1529 mod <- addHomeModuleToFinder hsc_env mod_name location
1530
1531 src_timestamp <- case maybe_buf of
1532 Just (_,t) -> return t
1533 Nothing -> getModificationTime file
1534 -- getMofificationTime may fail
1535
1536 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1537
1538 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1539 ms_location = location,
1540 ms_hspp_file = hspp_fn,
1541 ms_hspp_opts = dflags',
1542 ms_hspp_buf = Just buf,
1543 ms_srcimps = srcimps, ms_imps = the_imps,
1544 ms_hs_date = src_timestamp,
1545 ms_obj_date = obj_timestamp })
1546
1547 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1548 findSummaryBySourceFile summaries file
1549 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1550 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1551 [] -> Nothing
1552 (x:xs) -> Just x
1553
1554 -- Summarise a module, and pick up source and timestamp.
1555 summariseModule
1556 :: HscEnv
1557 -> NodeMap ModSummary -- Map of old summaries
1558 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1559 -> Located ModuleName -- Imported module to be summarised
1560 -> Maybe (StringBuffer, ClockTime)
1561 -> [ModuleName] -- Modules to exclude
1562 -> IO (Maybe ModSummary) -- Its new summary
1563
1564 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1565 | wanted_mod `elem` excl_mods
1566 = return Nothing
1567
1568 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1569 = do -- Find its new timestamp; all the
1570 -- ModSummaries in the old map have valid ml_hs_files
1571 let location = ms_location old_summary
1572 src_fn = expectJust "summariseModule" (ml_hs_file location)
1573
1574 -- check the modification time on the source file, and
1575 -- return the cached summary if it hasn't changed. If the
1576 -- file has disappeared, we need to call the Finder again.
1577 case maybe_buf of
1578 Just (_,t) -> check_timestamp old_summary location src_fn t
1579 Nothing -> do
1580 m <- System.IO.Error.try (getModificationTime src_fn)
1581 case m of
1582 Right t -> check_timestamp old_summary location src_fn t
1583 Left e | isDoesNotExistError e -> find_it
1584 | otherwise -> ioError e
1585
1586 | otherwise = find_it
1587 where
1588 dflags = hsc_dflags hsc_env
1589
1590 hsc_src = if is_boot then HsBootFile else HsSrcFile
1591
1592 check_timestamp old_summary location src_fn src_timestamp
1593 | ms_hs_date old_summary == src_timestamp = do
1594 -- update the object-file timestamp
1595 obj_timestamp <- getObjTimestamp location is_boot
1596 return (Just old_summary{ ms_obj_date = obj_timestamp })
1597 | otherwise =
1598 -- source changed: re-summarise.
1599 new_summary location (ms_mod old_summary) src_fn src_timestamp
1600
1601 find_it = do
1602 -- Don't use the Finder's cache this time. If the module was
1603 -- previously a package module, it may have now appeared on the
1604 -- search path, so we want to consider it to be a home module. If
1605 -- the module was previously a home module, it may have moved.
1606 uncacheModule hsc_env wanted_mod
1607 found <- findImportedModule hsc_env wanted_mod Nothing
1608 case found of
1609 Found location mod
1610 | isJust (ml_hs_file location) ->
1611 -- Home package
1612 just_found location mod
1613 | otherwise ->
1614 -- Drop external-pkg
1615 ASSERT(modulePackageId mod /= thisPackage dflags)
1616 return Nothing
1617 where
1618
1619 err -> noModError dflags loc wanted_mod err
1620 -- Not found
1621
1622 just_found location mod = do
1623 -- Adjust location to point to the hs-boot source file,
1624 -- hi file, object file, when is_boot says so
1625 let location' | is_boot = addBootSuffixLocn location
1626 | otherwise = location
1627 src_fn = expectJust "summarise2" (ml_hs_file location')
1628
1629 -- Check that it exists
1630 -- It might have been deleted since the Finder last found it
1631 maybe_t <- modificationTimeIfExists src_fn
1632 case maybe_t of
1633 Nothing -> noHsFileErr loc src_fn
1634 Just t -> new_summary location' mod src_fn t
1635
1636
1637 new_summary location mod src_fn src_timestamp
1638 = do
1639 -- Preprocess the source file and get its imports
1640 -- The dflags' contains the OPTIONS pragmas
1641 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1642 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1643
1644 when (mod_name /= wanted_mod) $
1645 throwDyn $ mkPlainErrMsg mod_loc $
1646 text "file name does not match module name"
1647 <+> quotes (ppr mod_name)
1648
1649 -- Find the object timestamp, and return the summary
1650 obj_timestamp <- getObjTimestamp location is_boot
1651
1652 return (Just ( ModSummary { ms_mod = mod,
1653 ms_hsc_src = hsc_src,
1654 ms_location = location,
1655 ms_hspp_file = hspp_fn,
1656 ms_hspp_opts = dflags',
1657 ms_hspp_buf = Just buf,
1658 ms_srcimps = srcimps,
1659 ms_imps = the_imps,
1660 ms_hs_date = src_timestamp,
1661 ms_obj_date = obj_timestamp }))
1662
1663
1664 getObjTimestamp location is_boot
1665 = if is_boot then return Nothing
1666 else modificationTimeIfExists (ml_obj_file location)
1667
1668
1669 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1670 -> IO (DynFlags, FilePath, StringBuffer)
1671 preprocessFile dflags src_fn mb_phase Nothing
1672 = do
1673 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1674 buf <- hGetStringBuffer hspp_fn
1675 return (dflags', hspp_fn, buf)
1676
1677 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1678 = do
1679 -- case we bypass the preprocessing stage?
1680 let
1681 local_opts = getOptions buf src_fn
1682 --
1683 (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1684
1685 let
1686 needs_preprocessing
1687 | Just (Unlit _) <- mb_phase = True
1688 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1689 -- note: local_opts is only required if there's no Unlit phase
1690 | dopt Opt_Cpp dflags' = True
1691 | dopt Opt_Pp dflags' = True
1692 | otherwise = False
1693
1694 when needs_preprocessing $
1695 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1696
1697 return (dflags', src_fn, buf)
1698
1699
1700 -----------------------------------------------------------------------------
1701 -- Error messages
1702 -----------------------------------------------------------------------------
1703
1704 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1705 -- ToDo: we don't have a proper line number for this error
1706 noModError dflags loc wanted_mod err
1707 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1708
1709 noHsFileErr loc path
1710 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1711
1712 packageModErr mod
1713 = throwDyn $ mkPlainErrMsg noSrcSpan $
1714 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1715
1716 multiRootsErr :: [ModSummary] -> IO ()
1717 multiRootsErr summs@(summ1:_)
1718 = throwDyn $ mkPlainErrMsg noSrcSpan $
1719 text "module" <+> quotes (ppr mod) <+>
1720 text "is defined in multiple files:" <+>
1721 sep (map text files)
1722 where
1723 mod = ms_mod summ1
1724 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1725
1726 cyclicModuleErr :: [ModSummary] -> SDoc
1727 cyclicModuleErr ms
1728 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1729 2 (vcat (map show_one ms))
1730 where
1731 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1732 nest 2 $ ptext SLIT("imports:") <+>
1733 (pp_imps HsBootFile (ms_srcimps ms)
1734 $$ pp_imps HsSrcFile (ms_imps ms))]
1735 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1736 pp_imps src mods = fsep (map (show_mod src) mods)
1737
1738
1739 -- | Inform GHC that the working directory has changed. GHC will flush
1740 -- its cache of module locations, since it may no longer be valid.
1741 -- Note: if you change the working directory, you should also unload
1742 -- the current program (set targets to empty, followed by load).
1743 workingDirectoryChanged :: Session -> IO ()
1744 workingDirectoryChanged s = withSession s $ flushFinderCaches
1745
1746 -- -----------------------------------------------------------------------------
1747 -- inspecting the session
1748
1749 -- | Get the module dependency graph.
1750 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1751 getModuleGraph s = withSession s (return . hsc_mod_graph)
1752
1753 isLoaded :: Session -> ModuleName -> IO Bool
1754 isLoaded s m = withSession s $ \hsc_env ->
1755 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1756
1757 getBindings :: Session -> IO [TyThing]
1758 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1759
1760 getPrintUnqual :: Session -> IO PrintUnqualified
1761 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1762
1763 -- | Container for information about a 'Module'.
1764 data ModuleInfo = ModuleInfo {
1765 minf_type_env :: TypeEnv,
1766 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1767 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1768 minf_instances :: [Instance]
1769 #ifdef GHCI
1770 ,minf_dbg_sites :: [(SiteNumber,Coord)]
1771 #endif
1772 -- ToDo: this should really contain the ModIface too
1773 }
1774 -- We don't want HomeModInfo here, because a ModuleInfo applies
1775 -- to package modules too.
1776
1777 -- | Request information about a loaded 'Module'
1778 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1779 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1780 let mg = hsc_mod_graph hsc_env
1781 if mdl `elem` map ms_mod mg
1782 then getHomeModuleInfo hsc_env (moduleName mdl)
1783 else do
1784 {- if isHomeModule (hsc_dflags hsc_env) mdl
1785 then return Nothing
1786 else -} getPackageModuleInfo hsc_env mdl
1787 -- getPackageModuleInfo will attempt to find the interface, so
1788 -- we don't want to call it for a home module, just in case there
1789 -- was a problem loading the module and the interface doesn't
1790 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1791
1792 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1793 getPackageModuleInfo hsc_env mdl = do
1794 #ifdef GHCI
1795 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1796 case mb_avails of
1797 Nothing -> return Nothing
1798 Just avails -> do
1799 eps <- readIORef (hsc_EPS hsc_env)
1800 let
1801 names = availsToNameSet avails
1802 pte = eps_PTE eps
1803 tys = [ ty | name <- concatMap availNames avails,
1804 Just ty <- [lookupTypeEnv pte name] ]
1805 --
1806 return (Just (ModuleInfo {
1807 minf_type_env = mkTypeEnv tys,
1808 minf_exports = names,
1809 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1810 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1811 minf_dbg_sites = noDbgSites
1812 }))
1813 #else
1814 -- bogusly different for non-GHCI (ToDo)
1815 return Nothing
1816 #endif
1817
1818 getHomeModuleInfo hsc_env mdl =
1819 case lookupUFM (hsc_HPT hsc_env) mdl of
1820 Nothing -> return Nothing
1821 Just hmi -> do
1822 let details = hm_details hmi
1823 return (Just (ModuleInfo {
1824 minf_type_env = md_types details,
1825 minf_exports = availsToNameSet (md_exports details),
1826 minf_rdr_env = mi_globals $! hm_iface hmi,
1827 minf_instances = md_insts details
1828 #ifdef GHCI
1829 ,minf_dbg_sites = md_dbg_sites details
1830 #endif
1831 }))
1832
1833 -- | The list of top-level entities defined in a module
1834 modInfoTyThings :: ModuleInfo -> [TyThing]
1835 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1836
1837 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1838 modInfoTopLevelScope minf
1839 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1840
1841 modInfoExports :: ModuleInfo -> [Name]
1842 modInfoExports minf = nameSetToList $! minf_exports minf
1843
1844 -- | Returns the instances defined by the specified module.
1845 -- Warning: currently unimplemented for package modules.
1846 modInfoInstances :: ModuleInfo -> [Instance]
1847 modInfoInstances = minf_instances
1848
1849 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1850 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1851
1852 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1853 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1854
1855 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1856 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1857 case lookupTypeEnv (minf_type_env minf) name of
1858 Just tyThing -> return (Just tyThing)
1859 Nothing -> do
1860 eps <- readIORef (hsc_EPS hsc_env)
1861 return $! lookupType (hsc_dflags hsc_env)
1862 (hsc_HPT hsc_env) (eps_PTE eps) name
1863
1864 #ifdef GHCI
1865 modInfoBkptSites = minf_dbg_sites
1866 #endif
1867
1868 isDictonaryId :: Id -> Bool
1869 isDictonaryId id
1870 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1871
1872 -- | Looks up a global name: that is, any top-level name in any
1873 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1874 -- the interactive context, and therefore does not require a preceding
1875 -- 'setContext'.
1876 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1877 lookupGlobalName s name = withSession s $ \hsc_env -> do
1878 eps <- readIORef (hsc_EPS hsc_env)
1879 return $! lookupType (hsc_dflags hsc_env)
1880 (hsc_HPT hsc_env) (eps_PTE eps) name
1881
1882 -- -----------------------------------------------------------------------------
1883 -- Misc exported utils
1884
1885 dataConType :: DataCon -> Type
1886 dataConType dc = idType (dataConWrapId dc)
1887
1888 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1889 pprParenSymName :: NamedThing a => a -> SDoc
1890 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1891
1892 -- ----------------------------------------------------------------------------
1893
1894 #if 0
1895
1896 -- ToDo:
1897 -- - Data and Typeable instances for HsSyn.
1898
1899 -- ToDo: check for small transformations that happen to the syntax in
1900 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1901
1902 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1903 -- to get from TyCons, Ids etc. to TH syntax (reify).
1904
1905 -- :browse will use either lm_toplev or inspect lm_interface, depending
1906 -- on whether the module is interpreted or not.
1907
1908 -- This is for reconstructing refactored source code
1909 -- Calls the lexer repeatedly.
1910 -- ToDo: add comment tokens to token stream
1911 getTokenStream :: Session -> Module -> IO [Located Token]
1912 #endif
1913
1914 -- -----------------------------------------------------------------------------
1915 -- Interactive evaluation
1916
1917 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1918 -- filesystem and package database to find the corresponding 'Module',
1919 -- using the algorithm that is used for an @import@ declaration.
1920 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1921 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1922 findModule' hsc_env mod_name maybe_pkg
1923
1924 findModule' hsc_env mod_name maybe_pkg =
1925 let
1926 dflags = hsc_dflags hsc_env
1927 hpt = hsc_HPT hsc_env
1928 this_pkg = thisPackage dflags
1929 in
1930 case lookupUFM hpt mod_name of
1931 Just mod_info -> return (mi_module (hm_iface mod_info))
1932 _not_a_home_module -> do
1933 res <- findImportedModule hsc_env mod_name Nothing
1934 case res of
1935 Found _ m | modulePackageId m /= this_pkg -> return m
1936 | otherwise -> throwDyn (CmdLineError (showSDoc $
1937 text "module" <+> pprModule m <+>
1938 text "is not loaded"))
1939 err -> let msg = cannotFindModule dflags mod_name err in
1940 throwDyn (CmdLineError (showSDoc msg))
1941
1942 #ifdef GHCI
1943
1944 -- | Set the interactive evaluation context.
1945 --
1946 -- Setting the context doesn't throw away any bindings; the bindings
1947 -- we've built up in the InteractiveContext simply move to the new
1948 -- module. They always shadow anything in scope in the current context.
1949 setContext :: Session
1950 -> [Module] -- entire top level scope of these modules
1951 -> [Module] -- exports only of these modules
1952 -> IO ()
1953 setContext sess@(Session ref) toplev_mods export_mods = do
1954 hsc_env <- readIORef ref
1955 let old_ic = hsc_IC hsc_env
1956 hpt = hsc_HPT hsc_env
1957 --
1958 export_env <- mkExportEnv hsc_env export_mods
1959 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
1960 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1961 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
1962 ic_exports = export_mods,
1963 ic_rn_gbl_env = all_env }}
1964 reinstallBreakpointHandlers sess
1965
1966 -- Make a GlobalRdrEnv based on the exports of the modules only.
1967 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1968 mkExportEnv hsc_env mods = do
1969 stuff <- mapM (getModuleExports hsc_env) mods
1970 let
1971 (_msgs, mb_name_sets) = unzip stuff
1972 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
1973 | (Just avails, mod) <- zip mb_name_sets mods ]
1974 --
1975 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1976
1977 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
1978 nameSetToGlobalRdrEnv names mod =
1979 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1980 | name <- nameSetToList names ]
1981
1982 vanillaProv :: ModuleName -> Provenance
1983 -- We're building a GlobalRdrEnv as if the user imported
1984 -- all the specified modules into the global interactive module
1985 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1986 where
1987 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
1988 is_qual = False,
1989 is_dloc = srcLocSpan interactiveSrcLoc }
1990
1991 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1992 mkTopLevEnv hpt modl
1993 = case lookupUFM hpt (moduleName modl) of
1994 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
1995 showSDoc (ppr modl)))
1996 Just details ->
1997 case mi_globals (hm_iface details) of
1998 Nothing ->
1999 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
2000 ++ showSDoc (ppr modl)))
2001 Just env -> return env
2002
2003 -- | Get the interactive evaluation context, consisting of a pair of the
2004 -- set of modules from which we take the full top-level scope, and the set
2005 -- of modules from which we take just the exports respectively.
2006 getContext :: Session -> IO ([Module],[Module])
2007 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
2008 return (ic_toplev_scope ic, ic_exports ic))
2009
2010 -- | Returns 'True' if the specified module is interpreted, and hence has
2011 -- its full top-level scope available.
2012 moduleIsInterpreted :: Session -> Module -> IO Bool
2013 moduleIsInterpreted s modl = withSession s $ \h ->
2014 if modulePackageId modl /= thisPackage (hsc_dflags h)
2015 then return False
2016 else case lookupUFM (hsc_HPT h) (moduleName modl) of
2017 Just details -> return (isJust (mi_globals (hm_iface details)))
2018 _not_a_home_module -> return False
2019
2020 -- | Looks up an identifier in the current interactive context (for :info)
2021 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
2022 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
2023
2024 -- | Returns all names in scope in the current interactive context
2025 getNamesInScope :: Session -> IO [Name]
2026 getNamesInScope s = withSession s $ \hsc_env -> do
2027 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
2028
2029 getRdrNamesInScope :: Session -> IO [RdrName]
2030 getRdrNamesInScope s = withSession s $ \hsc_env -> do
2031 let env = ic_rn_gbl_env (hsc_IC hsc_env)
2032 return (concat (map greToRdrNames (globalRdrEnvElts env)))
2033
2034 -- ToDo: move to RdrName
2035 greToRdrNames :: GlobalRdrElt -> [RdrName]
2036 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
2037 = case prov of
2038 LocalDef -> [unqual]
2039 Imported specs -> concat (map do_spec (map is_decl specs))
2040 where
2041 occ = nameOccName name
2042 unqual = Unqual occ
2043 do_spec decl_spec
2044 | is_qual decl_spec = [qual]
2045 | otherwise = [unqual,qual]
2046 where qual = Qual (is_as decl_spec) occ
2047
2048 -- | Parses a string as an identifier, and returns the list of 'Name's that
2049 -- the identifier can refer to in the current interactive context.
2050 parseName :: Session -> String -> IO [Name]
2051 parseName s str = withSession s $ \hsc_env -> do
2052 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
2053 case maybe_rdr_name of
2054 Nothing -> return []
2055 Just (L _ rdr_name) -> do
2056 mb_names <- tcRnLookupRdrName hsc_env rdr_name
2057 case mb_names of
2058 Nothing -> return []
2059 Just ns -> return ns
2060 -- ToDo: should return error messages
2061
2062 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
2063 -- entity known to GHC, including 'Name's defined using 'runStmt'.
2064 lookupName :: Session -> Name -> IO (Maybe TyThing)
2065 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
2066
2067 -- -----------------------------------------------------------------------------
2068 -- Getting the type of an expression
2069
2070 -- | Get the type of an expression
2071 exprType :: Session -> String -> IO (Maybe Type)
2072 exprType s expr = withSession s $ \hsc_env -> do
2073 maybe_stuff <- hscTcExpr hsc_env expr
2074 case maybe_stuff of
2075 Nothing -> return Nothing
2076 Just ty -> return (Just tidy_ty)
2077 where
2078 tidy_ty = tidyType emptyTidyEnv ty
2079
2080 -- -----------------------------------------------------------------------------
2081 -- Getting the kind of a type
2082
2083 -- | Get the kind of a type
2084 typeKind :: Session -> String -> IO (Maybe Kind)
2085 typeKind s str = withSession s $ \hsc_env -> do
2086 maybe_stuff <- hscKcType hsc_env str
2087 case maybe_stuff of
2088 Nothing -> return Nothing
2089 Just kind -> return (Just kind)
2090
2091 -----------------------------------------------------------------------------
2092 -- cmCompileExpr: compile an expression and deliver an HValue
2093
2094 compileExpr :: Session -> String -> IO (Maybe HValue)
2095 compileExpr s expr = withSession s $ \hsc_env -> do
2096 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
2097 case maybe_stuff of
2098 Nothing -> return Nothing
2099 Just (new_ic, names, hval) -> do
2100 -- Run it!
2101 hvals <- (unsafeCoerce# hval) :: IO [HValue]
2102
2103 case (names,hvals) of
2104 ([n],[hv]) -> return (Just hv)
2105 _ -> panic "compileExpr"
2106
2107 -- -----------------------------------------------------------------------------
2108 -- Compile an expression into a dynamic
2109
2110 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
2111 dynCompileExpr ses expr = do
2112 (full,exports) <- getContext ses
2113 setContext ses full $
2114 (mkModule
2115 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
2116 ):exports
2117 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
2118 res <- withSession ses (flip hscStmt stmt)
2119 setContext ses full exports
2120 case res of
2121 Nothing -> return Nothing
2122 Just (_, names, hvals) -> do
2123 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
2124 case (names,vals) of
2125 (_:[], v:[]) -> return (Just v)
2126 _ -> panic "dynCompileExpr"
2127
2128 -- -----------------------------------------------------------------------------
2129 -- running a statement interactively
2130
2131 data RunResult
2132 = RunOk [Name] -- ^ names bound by this evaluation
2133 | RunFailed -- ^ statement failed compilation
2134 | RunException Exception -- ^ statement raised an exception
2135
2136 -- | Run a statement in the current interactive context. Statemenet
2137 -- may bind multple values.
2138 runStmt :: Session -> String -> IO RunResult
2139 runStmt (Session ref) expr
2140 = do
2141 hsc_env <- readIORef ref
2142
2143 -- Turn off -fwarn-unused-bindings when running a statement, to hide
2144 -- warnings about the implicit bindings we introduce.
2145 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
2146 hsc_env' = hsc_env{ hsc_dflags = dflags' }
2147
2148 maybe_stuff <- hscStmt hsc_env' expr
2149
2150 case maybe_stuff of
2151 Nothing -> return RunFailed
2152 Just (new_hsc_env, names, hval) -> do
2153
2154 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2155 either_hvals <- sandboxIO thing_to_run
2156
2157 case either_hvals of
2158 Left e -> do
2159 -- on error, keep the *old* interactive context,
2160 -- so that 'it' is not bound to something
2161 -- that doesn't exist.
2162 return (RunException e)
2163
2164 Right hvals -> do
2165 -- Get the newly bound things, and bind them.
2166 -- Don't need to delete any shadowed bindings;
2167 -- the new ones override the old ones.
2168 extendLinkEnv (zip names hvals)
2169
2170 writeIORef ref new_hsc_env
2171 return (RunOk names)
2172
2173 -- When running a computation, we redirect ^C exceptions to the running
2174 -- thread. ToDo: we might want a way to continue even if the target
2175 -- thread doesn't die when it receives the exception... "this thread
2176 -- is not responding".
2177 sandboxIO :: IO a -> IO (Either Exception a)
2178 sandboxIO thing = do
2179 m <- newEmptyMVar
2180 ts <- takeMVar interruptTargetThread
2181 child <- forkIO (do res <- Exception.try thing; putMVar m res)
2182 putMVar interruptTargetThread (child:ts)
2183 takeMVar m `finally` modifyMVar_ interruptTargetThread (return.tail)
2184
2185 {-
2186 -- This version of sandboxIO runs the expression in a completely new
2187 -- RTS main thread. It is disabled for now because ^C exceptions
2188 -- won't be delivered to the new thread, instead they'll be delivered
2189 -- to the (blocked) GHCi main thread.
2190
2191 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2192
2193 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2194 sandboxIO thing = do
2195 st_thing <- newStablePtr (Exception.try thing)
2196 alloca $ \ p_st_result -> do
2197 stat <- rts_evalStableIO st_thing p_st_result
2198 freeStablePtr st_thing
2199 if stat == 1
2200 then do st_result <- peek p_st_result
2201 result <- deRefStablePtr st_result
2202 freeStablePtr st_result
2203 return (Right result)
2204 else do
2205 return (Left (fromIntegral stat))
2206
2207 foreign import "rts_evalStableIO" {- safe -}
2208 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2209 -- more informative than the C type!
2210 -}
2211
2212 -----------------------------------------------------------------------------
2213 -- show a module and it's source/object filenames
2214
2215 showModule :: Session -> ModSummary -> IO String
2216 showModule s mod_summary = withSession s $ \hsc_env ->
2217 isModuleInterpreted s mod_summary >>= \interpreted ->
2218 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
2219
2220 isModuleInterpreted :: Session -> ModSummary -> IO Bool
2221 isModuleInterpreted s mod_summary = withSession s $ \hsc_env ->
2222 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
2223 Nothing -> panic "missing linkable"
2224 Just mod_info -> return (not obj_linkable)
2225 where
2226 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
2227
2228 getBreakpointHandler :: Session -> IO (Maybe (BkptHandler Module))
2229 getBreakpointHandler session = getSessionDynFlags session >>= return . bkptHandler
2230
2231 setBreakpointHandler :: Session -> BkptHandler Module -> IO ()
2232 setBreakpointHandler session handler = do
2233 dflags <- getSessionDynFlags session
2234 setSessionDynFlags session dflags{ bkptHandler = Just handler }
2235 let linkEnv = [ ( breakpointJumpName
2236 , unsafeCoerce# (jumpFunction session handler))
2237 , ( breakpointCondJumpName
2238 , unsafeCoerce# (jumpCondFunction session handler))
2239 , ( breakpointAutoJumpName
2240 , unsafeCoerce# (jumpAutoFunction session handler))
2241 ]
2242 writeIORef v_bkptLinkEnv linkEnv
2243 dflags <- getSessionDynFlags session
2244 reinstallBreakpointHandlers session
2245
2246 reinstallBreakpointHandlers :: Session -> IO ()
2247 reinstallBreakpointHandlers session = do
2248 dflags <- getSessionDynFlags session
2249 let mode = ghcMode dflags
2250 when (mode == Interactive) $ do
2251 linkEnv <- readIORef v_bkptLinkEnv
2252 initDynLinker dflags
2253 extendLinkEnv linkEnv
2254
2255 type SiteInfo = (String, String, SiteNumber)
2256 jumpFunction, jumpAutoFunction :: Session -> BkptHandler Module -> Int -> [Opaque]
2257 -> SiteInfo -> String -> b -> b
2258 jumpCondFunction :: Session -> BkptHandler Module -> Int -> [Opaque]
2259 -> SiteInfo -> String -> Bool -> b -> b
2260 jumpFunctionM :: Session -> BkptHandler a -> Int -> [Opaque] -> BkptLocation a
2261 -> String -> b -> IO b
2262
2263 jumpCondFunction _ _ _ _ _ _ False b = b
2264 jumpCondFunction session handler ptr hValues siteInfo locmsg True b
2265 = jumpFunction session handler ptr hValues siteInfo locmsg b
2266
2267 jumpFunction session handler ptr hValues siteInfo locmsg b
2268 | site <- mkSite siteInfo
2269 = unsafePerformIO $ jumpFunctionM session handler ptr hValues site locmsg b
2270
2271 jumpFunctionM session handler (I# idsPtr) wrapped_hValues site locmsg b =
2272 do
2273 ids <- deRefStablePtr (castPtrToStablePtr (Ptr (int2Addr# idsPtr)))
2274 ASSERT (length ids == length wrapped_hValues) return ()
2275 let hValues = [unsafeCoerce# hv | O hv <- wrapped_hValues]
2276 handleBreakpoint handler session (zip ids hValues) site locmsg b
2277
2278 jumpAutoFunction session handler ptr hValues siteInfo locmsg b
2279 | site <- mkSite siteInfo
2280 = unsafePerformIO $ do
2281 break <- isAutoBkptEnabled handler session site
2282 if break
2283 then jumpFunctionM session handler ptr hValues site locmsg b
2284 else return b
2285
2286 jumpStepByStepFunction session handler ptr hValues siteInfo locmsg b
2287 | site <- mkSite siteInfo
2288 = unsafePerformIO $ do
2289 jumpFunctionM session handler ptr hValues site locmsg b
2290
2291 mkSite :: SiteInfo -> BkptLocation Module
2292 mkSite (pkgName, modName, sitenum) =
2293 (mkModule (stringToPackageId pkgName) (mkModuleName modName), sitenum)
2294
2295 obtainTerm :: Session -> Bool -> Id -> IO (Maybe Term)
2296 obtainTerm sess force id = withSession sess $ \hsc_env -> do
2297 mb_v <- getHValue (varName id)
2298 case mb_v of
2299 Just v -> fmap Just$ cvObtainTerm hsc_env force (Just$ idType id) v
2300 Nothing -> return Nothing
2301
2302 #endif /* GHCI */