1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), GhcMode(..), HscTarget(..), dopt,
23 Target(..), TargetId(..), Phase,
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 ()
36 -- * Loading\/compiling the program
38 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
39 workingDirectoryChanged,
40 checkModule, CheckedModule(..),
41 TypecheckedSource, ParsedSource, RenamedSource,
43 -- * Parsing Haddock comments
46 -- * Inspecting the module structure of the program
47 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
52 -- * Inspecting modules
57 modInfoPrintUnqualified,
60 modInfoIsExportedName,
68 PrintUnqualified, alwaysQualify,
70 -- * Interactive evaluation
71 getBindings, getPrintUnqual,
74 setContext, getContext,
86 compileExpr, HValue, dynCompileExpr,
89 getBreakpointHandler, setBreakpointHandler,
90 obtainTerm, obtainTerm1,
93 -- * Abstract syntax elements
99 Module, mkModule, pprModule, moduleName, modulePackageId,
100 ModuleName, mkModuleName, moduleNameString,
104 nameModule, pprParenSymName, nameSrcLoc,
106 RdrName(Qual,Unqual),
110 isImplicitId, isDeadBinder,
111 isExportedId, isLocalId, isGlobalId,
113 isPrimOpId, isFCallId, isClassOpId_maybe,
114 isDataConWorkId, idDataCon,
115 isBottomingId, isDictonaryId,
116 recordSelectorFieldLabel,
118 -- ** Type constructors
120 tyConTyVars, tyConDataCons, tyConArity,
121 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
123 synTyConDefn, synTyConType, synTyConResKind,
129 -- ** Data constructors
131 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
132 dataConIsInfix, isVanillaDataCon,
134 StrictnessMark(..), isMarkedStrict,
138 classMethods, classSCTheta, classTvsFds,
143 instanceDFunId, pprInstance, pprInstanceHdr,
145 -- ** Types and Kinds
146 Type, dropForAlls, splitForAllTys, funResultTy,
147 pprParendType, pprTypeApp,
150 ThetaType, pprThetaArrow,
156 module HsSyn, -- ToDo: remove extraneous bits
160 defaultFixity, maxPrecedence,
164 -- ** Source locations
168 GhcException(..), showGhcException,
178 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
179 * what StaticFlags should we expose, if any?
182 #include "HsVersions.h"
185 import RtClosureInspect ( cvObtainTerm, Term )
186 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
187 tcRnLookupName, getModuleExports )
188 import RdrName ( plusGlobalRdrEnv, Provenance(..),
189 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
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# )
199 import Breakpoints ( SiteNumber, Coord, nullBkptHandler,
200 BkptHandler(..), BkptLocation, noDbgSites )
201 import Linker ( initDynLinker )
202 import PrelNames ( breakpointJumpName, breakpointCondJumpName,
203 breakpointAutoJumpName )
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
212 import Data.Dynamic ( Dynamic )
213 import Linker ( HValue, getHValue, extendLinkEnv )
216 import Packages ( initPackages )
217 import NameSet ( NameSet, nameSetToList, elemNameSet )
218 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..),
219 globalRdrEnvElts, extendGlobalRdrEnv,
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,
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 )
247 import DriverPipeline
248 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
249 import HeaderInfo ( getImports, getOptions )
251 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
254 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
258 import PackageConfig ( PackageId, stringToPackageId, mainPackageId )
262 import Bag ( unitBag, listToBag )
263 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
264 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
266 import qualified ErrUtils
268 import StringBuffer ( StringBuffer, hGetStringBuffer )
271 import TcType ( tcSplitSigmaTy, isDictTy )
272 import Maybes ( expectJust, mapCatMaybes )
273 import HaddockParse ( parseHaddockParagraphs, parseHaddockString )
274 import HaddockLex ( tokenise )
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)
287 import System.IO.Error ( isDoesNotExistError )
288 import Prelude hiding (init)
290 #if __GLASGOW_HASKELL__ < 600
291 import System.IO as System.IO.Error ( try )
293 import System.IO.Error ( try )
296 -- -----------------------------------------------------------------------------
297 -- Exception handlers
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
309 -- an IO exception probably isn't our fault, so don't panic
311 fatalErrorMsg dflags (text (show exception))
312 AsyncException StackOverflow ->
313 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
315 fatalErrorMsg dflags (text (show (Panic (show exception))))
316 exitWith (ExitFailure 1)
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)) $
324 -- error messages propagated as exceptions
325 handleDyn (\dyn -> do
328 PhaseFailed _ code -> exitWith code
329 Interrupted -> exitWith (ExitFailure 1)
330 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
331 exitWith (ExitFailure 1)
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 (do cleanTempFiles dflags
345 -- exceptions will be blocked while we clean the temporary files,
346 -- so there shouldn't be any difficulty if we receive further
352 GLOBAL_VAR(v_bkptLinkEnv, [], [(Name, HValue)])
353 -- stores the current breakpoint handler to help setContext to
354 -- restore it after a context change
357 -- | Starts a new session. A session consists of a set of loaded
358 -- modules, a set of options (DynFlags), and an interactive context.
359 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
361 newSession :: GhcMode -> Maybe FilePath -> IO Session
362 newSession mode mb_top_dir = do
364 main_thread <- myThreadId
365 modifyMVar_ interruptTargetThread (return . (main_thread :))
366 installSignalHandlers
368 dflags0 <- initSysTools mb_top_dir defaultDynFlags
369 dflags <- initDynFlags dflags0
370 env <- newHscEnv dflags{ ghcMode=mode }
374 -- tmp: this breaks the abstraction, but required because DriverMkDepend
375 -- needs to call the Finder. ToDo: untangle this.
376 sessionHscEnv :: Session -> IO HscEnv
377 sessionHscEnv (Session ref) = readIORef ref
379 withSession :: Session -> (HscEnv -> IO a) -> IO a
380 withSession (Session ref) f = do h <- readIORef ref; f h
382 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
383 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
385 -- -----------------------------------------------------------------------------
388 -- | Grabs the DynFlags from the Session
389 getSessionDynFlags :: Session -> IO DynFlags
390 getSessionDynFlags s = withSession s (return . hsc_dflags)
392 -- | Updates the DynFlags in a Session. This also reads
393 -- the package database (unless it has already been read),
394 -- and prepares the compilers knowledge about packages. It
395 -- can be called again to load new packages: just add new
396 -- package flags to (packageFlags dflags).
398 -- Returns a list of new packages that may need to be linked in using
399 -- the dynamic linker (see 'linkPackages') as a result of new package
400 -- flags. If you are not doing linking or doing static linking, you
401 -- can ignore the list of packages returned.
403 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
404 setSessionDynFlags (Session ref) dflags = do
405 hsc_env <- readIORef ref
406 (dflags', preload) <- initPackages dflags
407 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
410 -- | If there is no -o option, guess the name of target executable
411 -- by using top-level source file name as a base.
412 guessOutputFile :: Session -> IO ()
413 guessOutputFile s = modifySession s $ \env ->
414 let dflags = hsc_dflags env
415 mod_graph = hsc_mod_graph env
416 mainModuleSrcPath, guessedName :: Maybe String
417 mainModuleSrcPath = do
418 let isMain = (== mainModIs dflags) . ms_mod
419 [ms] <- return (filter isMain mod_graph)
420 ml_hs_file (ms_location ms)
421 guessedName = fmap basenameOf mainModuleSrcPath
423 case outputFile dflags of
425 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
427 -- -----------------------------------------------------------------------------
430 -- ToDo: think about relative vs. absolute file paths. And what
431 -- happens when the current directory changes.
433 -- | Sets the targets for this session. Each target may be a module name
434 -- or a filename. The targets correspond to the set of root modules for
435 -- the program\/library. Unloading the current program is achieved by
436 -- setting the current set of targets to be empty, followed by load.
437 setTargets :: Session -> [Target] -> IO ()
438 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
440 -- | returns the current set of targets
441 getTargets :: Session -> IO [Target]
442 getTargets s = withSession s (return . hsc_targets)
444 -- | Add another target
445 addTarget :: Session -> Target -> IO ()
447 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
450 removeTarget :: Session -> TargetId -> IO ()
451 removeTarget s target_id
452 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
454 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
456 -- Attempts to guess what Target a string refers to. This function implements
457 -- the --make/GHCi command-line syntax for filenames:
459 -- - if the string looks like a Haskell source filename, then interpret
461 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
463 -- - otherwise interpret the string as a module name
465 guessTarget :: String -> Maybe Phase -> IO Target
466 guessTarget file (Just phase)
467 = return (Target (TargetFile file (Just phase)) Nothing)
468 guessTarget file Nothing
469 | isHaskellSrcFilename file
470 = return (Target (TargetFile file Nothing) Nothing)
472 = do exists <- doesFileExist hs_file
474 then return (Target (TargetFile hs_file Nothing) Nothing)
476 exists <- doesFileExist lhs_file
478 then return (Target (TargetFile lhs_file Nothing) Nothing)
480 return (Target (TargetModule (mkModuleName file)) Nothing)
482 hs_file = file `joinFileExt` "hs"
483 lhs_file = file `joinFileExt` "lhs"
485 -- -----------------------------------------------------------------------------
486 -- Extending the program scope
488 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
489 extendGlobalRdrScope session rdrElts
490 = modifySession session $ \hscEnv ->
491 let global_rdr = hsc_global_rdr_env hscEnv
492 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
494 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
495 setGlobalRdrScope session rdrElts
496 = modifySession session $ \hscEnv ->
497 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
499 extendGlobalTypeScope :: Session -> [Id] -> IO ()
500 extendGlobalTypeScope session ids
501 = modifySession session $ \hscEnv ->
502 let global_type = hsc_global_type_env hscEnv
503 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
505 setGlobalTypeScope :: Session -> [Id] -> IO ()
506 setGlobalTypeScope session ids
507 = modifySession session $ \hscEnv ->
508 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
510 -- -----------------------------------------------------------------------------
511 -- Parsing Haddock comments
513 parseHaddockComment :: String -> Either String (HsDoc RdrName)
514 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
516 -- -----------------------------------------------------------------------------
517 -- Loading the program
519 -- Perform a dependency analysis starting from the current targets
520 -- and update the session with the new module graph.
521 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
522 depanal (Session ref) excluded_mods allow_dup_roots = do
523 hsc_env <- readIORef ref
525 dflags = hsc_dflags hsc_env
526 gmode = ghcMode (hsc_dflags hsc_env)
527 targets = hsc_targets hsc_env
528 old_graph = hsc_mod_graph hsc_env
530 showPass dflags "Chasing dependencies"
531 when (gmode == BatchCompile) $
532 debugTraceMsg dflags 2 (hcat [
533 text "Chasing modules from: ",
534 hcat (punctuate comma (map pprTarget targets))])
536 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
538 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
543 -- | The result of load.
545 = LoadOk Errors -- ^ all specified targets were loaded successfully.
546 | LoadFailed Errors -- ^ not all modules were loaded.
548 type Errors = [String]
550 data ErrMsg = ErrMsg {
551 errMsgSeverity :: Severity, -- warning, error, etc.
552 errMsgSpans :: [SrcSpan],
553 errMsgShortDoc :: Doc,
554 errMsgExtraInfo :: Doc
560 | LoadUpTo ModuleName
561 | LoadDependenciesOf ModuleName
563 -- | Try to load the program. If a Module is supplied, then just
564 -- attempt to load up to this target. If no Module is supplied,
565 -- then try to load all targets.
566 load :: Session -> LoadHowMuch -> IO SuccessFlag
567 load s@(Session ref) how_much
569 -- Dependency analysis first. Note that this fixes the module graph:
570 -- even if we don't get a fully successful upsweep, the full module
571 -- graph is still retained in the Session. We can tell which modules
572 -- were successfully loaded by inspecting the Session's HPT.
573 mb_graph <- depanal s [] False
575 Just mod_graph -> load2 s how_much mod_graph
576 Nothing -> return Failed
578 load2 s@(Session ref) how_much mod_graph = do
580 hsc_env <- readIORef ref
582 let hpt1 = hsc_HPT hsc_env
583 let dflags = hsc_dflags hsc_env
584 let ghci_mode = ghcMode dflags -- this never changes
586 -- The "bad" boot modules are the ones for which we have
587 -- B.hs-boot in the module graph, but no B.hs
588 -- The downsweep should have ensured this does not happen
590 let all_home_mods = [ms_mod_name s
591 | s <- mod_graph, not (isBootSummary s)]
593 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
594 not (ms_mod_name s `elem` all_home_mods)]
596 ASSERT( null bad_boot_mods ) return ()
598 -- mg2_with_srcimps drops the hi-boot nodes, returning a
599 -- graph with cycles. Among other things, it is used for
600 -- backing out partially complete cycles following a failed
601 -- upsweep, and for removing from hpt all the modules
602 -- not in strict downwards closure, during calls to compile.
603 let mg2_with_srcimps :: [SCC ModSummary]
604 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
606 -- If we can determine that any of the {-# SOURCE #-} imports
607 -- are definitely unnecessary, then emit a warning.
608 warnUnnecessarySourceImports dflags mg2_with_srcimps
611 -- check the stability property for each module.
612 stable_mods@(stable_obj,stable_bco)
613 | BatchCompile <- ghci_mode = ([],[])
614 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
616 -- prune bits of the HPT which are definitely redundant now,
618 pruned_hpt = pruneHomePackageTable hpt1
619 (flattenSCCs mg2_with_srcimps)
624 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
625 text "Stable BCO:" <+> ppr stable_bco)
627 -- Unload any modules which are going to be re-linked this time around.
628 let stable_linkables = [ linkable
629 | m <- stable_obj++stable_bco,
630 Just hmi <- [lookupUFM pruned_hpt m],
631 Just linkable <- [hm_linkable hmi] ]
632 unload hsc_env stable_linkables
634 -- We could at this point detect cycles which aren't broken by
635 -- a source-import, and complain immediately, but it seems better
636 -- to let upsweep_mods do this, so at least some useful work gets
637 -- done before the upsweep is abandoned.
638 --hPutStrLn stderr "after tsort:\n"
639 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
641 -- Now do the upsweep, calling compile for each module in
642 -- turn. Final result is version 3 of everything.
644 -- Topologically sort the module graph, this time including hi-boot
645 -- nodes, and possibly just including the portion of the graph
646 -- reachable from the module specified in the 2nd argument to load.
647 -- This graph should be cycle-free.
648 -- If we're restricting the upsweep to a portion of the graph, we
649 -- also want to retain everything that is still stable.
650 let full_mg :: [SCC ModSummary]
651 full_mg = topSortModuleGraph False mod_graph Nothing
653 maybe_top_mod = case how_much of
655 LoadDependenciesOf m -> Just m
658 partial_mg0 :: [SCC ModSummary]
659 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
661 -- LoadDependenciesOf m: we want the upsweep to stop just
662 -- short of the specified module (unless the specified module
665 | LoadDependenciesOf mod <- how_much
666 = ASSERT( case last partial_mg0 of
667 AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
668 List.init partial_mg0
674 | AcyclicSCC ms <- full_mg,
675 ms_mod_name ms `elem` stable_obj++stable_bco,
676 ms_mod_name ms `notElem` [ ms_mod_name ms' |
677 AcyclicSCC ms' <- partial_mg ] ]
679 mg = stable_mg ++ partial_mg
681 -- clean up between compilations
682 let cleanup = cleanTempFilesExcept dflags
683 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
685 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
687 (upsweep_ok, hsc_env1, modsUpswept)
688 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
689 pruned_hpt stable_mods cleanup mg
691 -- Make modsDone be the summaries for each home module now
692 -- available; this should equal the domain of hpt3.
693 -- Get in in a roughly top .. bottom order (hence reverse).
695 let modsDone = reverse modsUpswept
697 -- Try and do linking in some form, depending on whether the
698 -- upsweep was completely or only partially successful.
700 if succeeded upsweep_ok
703 -- Easy; just relink it all.
704 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
706 -- Clean up after ourselves
707 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
709 -- Issue a warning for the confusing case where the user
710 -- said '-o foo' but we're not going to do any linking.
711 -- We attempt linking if either (a) one of the modules is
712 -- called Main, or (b) the user said -no-hs-main, indicating
713 -- that main() is going to come from somewhere else.
715 let ofile = outputFile dflags
716 let no_hs_main = dopt Opt_NoHsMain dflags
718 main_mod = mainModIs dflags
719 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
720 do_linking = a_root_is_Main || no_hs_main
722 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
723 debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
724 "but no output will be generated\n" ++
725 "because there is no " ++ moduleNameString (moduleName main_mod) ++ " module."))
727 -- link everything together
728 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
730 loadFinish Succeeded linkresult ref hsc_env1
733 -- Tricky. We need to back out the effects of compiling any
734 -- half-done cycles, both so as to clean up the top level envs
735 -- and to avoid telling the interactive linker to link them.
736 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
739 = map ms_mod modsDone
740 let mods_to_zap_names
741 = findPartiallyCompletedCycles modsDone_names
744 = filter ((`notElem` mods_to_zap_names).ms_mod)
747 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
750 -- Clean up after ourselves
751 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
753 -- there should be no Nothings where linkables should be, now
754 ASSERT(all (isJust.hm_linkable)
755 (eltsUFM (hsc_HPT hsc_env))) do
757 -- Link everything together
758 linkresult <- link ghci_mode dflags False hpt4
760 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
761 loadFinish Failed linkresult ref hsc_env4
763 -- Finish up after a load.
765 -- If the link failed, unload everything and return.
766 loadFinish all_ok Failed ref hsc_env
767 = do unload hsc_env []
768 writeIORef ref $! discardProg hsc_env
771 -- Empty the interactive context and set the module context to the topmost
772 -- newly loaded module, or the Prelude if none were loaded.
773 loadFinish all_ok Succeeded ref hsc_env
774 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
778 -- Forget the current program, but retain the persistent info in HscEnv
779 discardProg :: HscEnv -> HscEnv
781 = hsc_env { hsc_mod_graph = emptyMG,
782 hsc_IC = emptyInteractiveContext,
783 hsc_HPT = emptyHomePackageTable }
785 -- used to fish out the preprocess output files for the purposes of
786 -- cleaning up. The preprocessed file *might* be the same as the
787 -- source file, but that doesn't do any harm.
788 ppFilesFromSummaries summaries = map ms_hspp_file summaries
790 -- -----------------------------------------------------------------------------
794 CheckedModule { parsedSource :: ParsedSource,
795 renamedSource :: Maybe RenamedSource,
796 typecheckedSource :: Maybe TypecheckedSource,
797 checkedModuleInfo :: Maybe ModuleInfo
799 -- ToDo: improvements that could be made here:
800 -- if the module succeeded renaming but not typechecking,
801 -- we can still get back the GlobalRdrEnv and exports, so
802 -- perhaps the ModuleInfo should be split up into separate
803 -- fields within CheckedModule.
805 type ParsedSource = Located (HsModule RdrName)
806 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
807 Maybe (HsDoc Name), HaddockModInfo Name)
808 type TypecheckedSource = LHsBinds Id
811 -- - things that aren't in the output of the typechecker right now:
815 -- - type/data/newtype declarations
816 -- - class declarations
818 -- - extra things in the typechecker's output:
819 -- - default methods are turned into top-level decls.
820 -- - dictionary bindings
823 -- | This is the way to get access to parsed and typechecked source code
824 -- for a module. 'checkModule' loads all the dependencies of the specified
825 -- module in the Session, and then attempts to typecheck the module. If
826 -- successful, it returns the abstract syntax for the module.
827 checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
828 checkModule session@(Session ref) mod = do
829 -- load up the dependencies first
830 r <- load session (LoadDependenciesOf mod)
831 if (failed r) then return Nothing else do
833 -- now parse & typecheck the module
834 hsc_env <- readIORef ref
835 let mg = hsc_mod_graph hsc_env
836 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
839 mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
841 Nothing -> return Nothing
842 Just (HscChecked parsed renamed Nothing) ->
843 return (Just (CheckedModule {
844 parsedSource = parsed,
845 renamedSource = renamed,
846 typecheckedSource = Nothing,
847 checkedModuleInfo = Nothing }))
848 Just (HscChecked parsed renamed
849 (Just (tc_binds, rdr_env, details))) -> do
850 let minf = ModuleInfo {
851 minf_type_env = md_types details,
852 minf_exports = availsToNameSet $
854 minf_rdr_env = Just rdr_env,
855 minf_instances = md_insts details
857 ,minf_dbg_sites = noDbgSites
860 return (Just (CheckedModule {
861 parsedSource = parsed,
862 renamedSource = renamed,
863 typecheckedSource = Just tc_binds,
864 checkedModuleInfo = Just minf }))
866 -- ---------------------------------------------------------------------------
869 unload :: HscEnv -> [Linkable] -> IO ()
870 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
871 = case ghcMode (hsc_dflags hsc_env) of
872 BatchCompile -> return ()
873 JustTypecheck -> return ()
875 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
877 Interactive -> panic "unload: no interpreter"
879 other -> panic "unload: strange mode"
881 -- -----------------------------------------------------------------------------
885 Stability tells us which modules definitely do not need to be recompiled.
886 There are two main reasons for having stability:
888 - avoid doing a complete upsweep of the module graph in GHCi when
889 modules near the bottom of the tree have not changed.
891 - to tell GHCi when it can load object code: we can only load object code
892 for a module when we also load object code fo all of the imports of the
893 module. So we need to know that we will definitely not be recompiling
894 any of these modules, and we can use the object code.
896 NB. stability is of no importance to BatchCompile at all, only Interactive.
897 (ToDo: what about JustTypecheck?)
899 The stability check is as follows. Both stableObject and
900 stableBCO are used during the upsweep phase later.
903 stable m = stableObject m || stableBCO m
906 all stableObject (imports m)
907 && old linkable does not exist, or is == on-disk .o
908 && date(on-disk .o) > date(.hs)
911 all stable (imports m)
912 && date(BCO) > date(.hs)
915 These properties embody the following ideas:
917 - if a module is stable:
918 - if it has been compiled in a previous pass (present in HPT)
919 then it does not need to be compiled or re-linked.
920 - if it has not been compiled in a previous pass,
921 then we only need to read its .hi file from disk and
922 link it to produce a ModDetails.
924 - if a modules is not stable, we will definitely be at least
925 re-linking, and possibly re-compiling it during the upsweep.
926 All non-stable modules can (and should) therefore be unlinked
929 - Note that objects are only considered stable if they only depend
930 on other objects. We can't link object code against byte code.
934 :: HomePackageTable -- HPT from last compilation
935 -> [SCC ModSummary] -- current module graph (cyclic)
936 -> [ModuleName] -- all home modules
937 -> ([ModuleName], -- stableObject
938 [ModuleName]) -- stableBCO
940 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
942 checkSCC (stable_obj, stable_bco) scc0
943 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
944 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
945 | otherwise = (stable_obj, stable_bco)
947 scc = flattenSCC scc0
948 scc_mods = map ms_mod_name scc
949 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
951 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
952 -- all imports outside the current SCC, but in the home pkg
954 stable_obj_imps = map (`elem` stable_obj) scc_allimps
955 stable_bco_imps = map (`elem` stable_bco) scc_allimps
962 and (zipWith (||) stable_obj_imps stable_bco_imps)
966 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
970 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
971 Just hmi | Just l <- hm_linkable hmi
972 -> isObjectLinkable l && t == linkableTime l
974 -- why '>=' rather than '>' above? If the filesystem stores
975 -- times to the nearset second, we may occasionally find that
976 -- the object & source have the same modification time,
977 -- especially if the source was automatically generated
978 -- and compiled. Using >= is slightly unsafe, but it matches
982 = case lookupUFM hpt (ms_mod_name ms) of
983 Just hmi | Just l <- hm_linkable hmi ->
984 not (isObjectLinkable l) &&
985 linkableTime l >= ms_hs_date ms
988 ms_allimps :: ModSummary -> [ModuleName]
989 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
991 -- -----------------------------------------------------------------------------
992 -- Prune the HomePackageTable
994 -- Before doing an upsweep, we can throw away:
996 -- - For non-stable modules:
997 -- - all ModDetails, all linked code
998 -- - all unlinked code that is out of date with respect to
1001 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1002 -- space at the end of the upsweep, because the topmost ModDetails of the
1003 -- old HPT holds on to the entire type environment from the previous
1006 pruneHomePackageTable
1009 -> ([ModuleName],[ModuleName])
1012 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1015 | is_stable modl = hmi'
1016 | otherwise = hmi'{ hm_details = emptyModDetails }
1018 modl = moduleName (mi_module (hm_iface hmi))
1019 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1020 = hmi{ hm_linkable = Nothing }
1023 where ms = expectJust "prune" (lookupUFM ms_map modl)
1025 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1027 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1029 -- -----------------------------------------------------------------------------
1031 -- Return (names of) all those in modsDone who are part of a cycle
1032 -- as defined by theGraph.
1033 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1034 findPartiallyCompletedCycles modsDone theGraph
1038 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
1039 chew ((CyclicSCC vs):rest)
1040 = let names_in_this_cycle = nub (map ms_mod vs)
1042 = nub ([done | done <- modsDone,
1043 done `elem` names_in_this_cycle])
1044 chewed_rest = chew rest
1046 if notNull mods_in_this_cycle
1047 && length mods_in_this_cycle < length names_in_this_cycle
1048 then mods_in_this_cycle ++ chewed_rest
1051 -- -----------------------------------------------------------------------------
1054 -- This is where we compile each module in the module graph, in a pass
1055 -- from the bottom to the top of the graph.
1057 -- There better had not be any cyclic groups here -- we check for them.
1060 :: HscEnv -- Includes initially-empty HPT
1061 -> HomePackageTable -- HPT from last time round (pruned)
1062 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1063 -> IO () -- How to clean up unwanted tmp files
1064 -> [SCC ModSummary] -- Mods to do (the worklist)
1066 HscEnv, -- With an updated HPT
1067 [ModSummary]) -- Mods which succeeded
1069 upsweep hsc_env old_hpt stable_mods cleanup mods
1070 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1072 upsweep' hsc_env old_hpt stable_mods cleanup
1074 = return (Succeeded, hsc_env, [])
1076 upsweep' hsc_env old_hpt stable_mods cleanup
1077 (CyclicSCC ms:_) _ _
1078 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1079 return (Failed, hsc_env, [])
1081 upsweep' hsc_env old_hpt stable_mods cleanup
1082 (AcyclicSCC mod:mods) mod_index nmods
1083 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1084 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1085 -- (moduleEnvElts (hsc_HPT hsc_env)))
1087 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1090 cleanup -- Remove unwanted tmp files between compilations
1093 Nothing -> return (Failed, hsc_env, [])
1095 { let this_mod = ms_mod_name mod
1097 -- Add new info to hsc_env
1098 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1099 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1101 -- Space-saving: delete the old HPT entry
1102 -- for mod BUT if mod is a hs-boot
1103 -- node, don't delete it. For the
1104 -- interface, the HPT entry is probaby for the
1105 -- main Haskell source file. Deleting it
1106 -- would force .. (what?? --SDM)
1107 old_hpt1 | isBootSummary mod = old_hpt
1108 | otherwise = delFromUFM old_hpt this_mod
1110 ; (restOK, hsc_env2, modOKs)
1111 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1112 mods (mod_index+1) nmods
1113 ; return (restOK, hsc_env2, mod:modOKs)
1117 -- Compile a single module. Always produce a Linkable for it if
1118 -- successful. If no compilation happened, return the old Linkable.
1119 upsweep_mod :: HscEnv
1121 -> ([ModuleName],[ModuleName])
1123 -> Int -- index of module
1124 -> Int -- total number of modules
1125 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1127 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1130 this_mod_name = ms_mod_name summary
1131 this_mod = ms_mod summary
1132 mb_obj_date = ms_obj_date summary
1133 obj_fn = ml_obj_file (ms_location summary)
1134 hs_date = ms_hs_date summary
1136 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1137 compile_it = upsweep_compile hsc_env old_hpt this_mod_name
1138 summary mod_index nmods
1140 case ghcMode (hsc_dflags hsc_env) of
1143 -- Batch-compilating is easy: just check whether we have
1144 -- an up-to-date object file. If we do, then the compiler
1145 -- needs to do a recompilation check.
1146 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1148 findObjectLinkable this_mod obj_fn obj_date
1149 compile_it (Just linkable)
1156 _ | is_stable_obj, isJust old_hmi ->
1158 -- object is stable, and we have an entry in the
1159 -- old HPT: nothing to do
1161 | is_stable_obj, isNothing old_hmi -> do
1163 findObjectLinkable this_mod obj_fn
1164 (expectJust "upseep1" mb_obj_date)
1165 compile_it (Just linkable)
1166 -- object is stable, but we need to load the interface
1167 -- off disk to make a HMI.
1170 ASSERT(isJust old_hmi) -- must be in the old_hpt
1172 -- BCO is stable: nothing to do
1174 | Just hmi <- old_hmi,
1175 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1176 linkableTime l >= ms_hs_date summary ->
1178 -- we have an old BCO that is up to date with respect
1179 -- to the source: do a recompilation check as normal.
1183 -- no existing code at all: we must recompile.
1185 is_stable_obj = this_mod_name `elem` stable_obj
1186 is_stable_bco = this_mod_name `elem` stable_bco
1188 old_hmi = lookupUFM old_hpt this_mod_name
1190 -- Run hsc to compile a module
1191 upsweep_compile hsc_env old_hpt this_mod summary
1193 mb_old_linkable = do
1195 -- The old interface is ok if it's in the old HPT
1196 -- a) we're compiling a source file, and the old HPT
1197 -- entry is for a source file
1198 -- b) we're compiling a hs-boot file
1199 -- Case (b) allows an hs-boot file to get the interface of its
1200 -- real source file on the second iteration of the compilation
1201 -- manager, but that does no harm. Otherwise the hs-boot file
1202 -- will always be recompiled
1205 = case lookupUFM old_hpt this_mod of
1207 Just hm_info | isBootSummary summary -> Just iface
1208 | not (mi_boot iface) -> Just iface
1209 | otherwise -> Nothing
1211 iface = hm_iface hm_info
1213 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1217 -- Compilation failed. Compile may still have updated the PCS, tho.
1218 CompErrs -> return Nothing
1220 -- Compilation "succeeded", and may or may not have returned a new
1221 -- linkable (depending on whether compilation was actually performed
1223 CompOK new_details new_iface new_linkable
1224 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1225 hm_details = new_details,
1226 hm_linkable = new_linkable }
1227 return (Just new_info)
1230 -- Filter modules in the HPT
1231 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1232 retainInTopLevelEnvs keep_these hpt
1233 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1235 , let mb_mod_info = lookupUFM hpt mod
1236 , isJust mb_mod_info ]
1238 -- ---------------------------------------------------------------------------
1239 -- Topological sort of the module graph
1242 :: Bool -- Drop hi-boot nodes? (see below)
1246 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1247 -- The resulting list of strongly-connected-components is in topologically
1248 -- sorted order, starting with the module(s) at the bottom of the
1249 -- dependency graph (ie compile them first) and ending with the ones at
1252 -- Drop hi-boot nodes (first boolean arg)?
1254 -- False: treat the hi-boot summaries as nodes of the graph,
1255 -- so the graph must be acyclic
1257 -- True: eliminate the hi-boot nodes, and instead pretend
1258 -- the a source-import of Foo is an import of Foo
1259 -- The resulting graph has no hi-boot nodes, but can by cyclic
1261 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1262 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1263 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1264 = stronglyConnComp (map vertex_fn (reachable graph root))
1266 -- restrict the graph to just those modules reachable from
1267 -- the specified module. We do this by building a graph with
1268 -- the full set of nodes, and determining the reachable set from
1269 -- the specified node.
1270 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1271 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1273 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1274 | otherwise = throwDyn (ProgramError "module does not exist")
1276 moduleGraphNodes :: Bool -> [ModSummary]
1277 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1278 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1280 -- Drop hs-boot nodes by using HsSrcFile as the key
1281 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1282 | otherwise = HsBootFile
1284 -- We use integers as the keys for the SCC algorithm
1285 nodes :: [(ModSummary, Int, [Int])]
1286 nodes = [(s, expectJust "topSort" $
1287 lookup_key (ms_hsc_src s) (ms_mod_name s),
1288 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1289 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1290 (-- see [boot-edges] below
1291 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1293 else case lookup_key HsBootFile (ms_mod_name s) of
1298 , not (isBootSummary s && drop_hs_boot_nodes) ]
1299 -- Drop the hi-boot ones if told to do so
1301 -- [boot-edges] if this is a .hs and there is an equivalent
1302 -- .hs-boot, add a link from the former to the latter. This
1303 -- has the effect of detecting bogus cases where the .hs-boot
1304 -- depends on the .hs, by introducing a cycle. Additionally,
1305 -- it ensures that we will always process the .hs-boot before
1306 -- the .hs, and so the HomePackageTable will always have the
1307 -- most up to date information.
1309 key_map :: NodeMap Int
1310 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1314 lookup_key :: HscSource -> ModuleName -> Maybe Int
1315 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1317 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1318 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1319 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1320 -- the IsBootInterface parameter True; else False
1323 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1324 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1326 msKey :: ModSummary -> NodeKey
1327 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1329 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1330 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1332 nodeMapElts :: NodeMap a -> [a]
1333 nodeMapElts = eltsFM
1335 ms_mod_name :: ModSummary -> ModuleName
1336 ms_mod_name = moduleName . ms_mod
1338 -- If there are {-# SOURCE #-} imports between strongly connected
1339 -- components in the topological sort, then those imports can
1340 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1341 -- were necessary, then the edge would be part of a cycle.
1342 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1343 warnUnnecessarySourceImports dflags sccs =
1344 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1346 let mods_in_this_cycle = map ms_mod_name ms in
1347 [ warn m i | m <- ms, i <- ms_srcimps m,
1348 unLoc i `notElem` mods_in_this_cycle ]
1350 warn :: ModSummary -> Located ModuleName -> WarnMsg
1351 warn ms (L loc mod) =
1353 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1354 <+> quotes (ppr mod))
1356 -----------------------------------------------------------------------------
1357 -- Downsweep (dependency analysis)
1359 -- Chase downwards from the specified root set, returning summaries
1360 -- for all home modules encountered. Only follow source-import
1363 -- We pass in the previous collection of summaries, which is used as a
1364 -- cache to avoid recalculating a module summary if the source is
1367 -- The returned list of [ModSummary] nodes has one node for each home-package
1368 -- module, plus one for any hs-boot files. The imports of these nodes
1369 -- are all there, including the imports of non-home-package modules.
1372 -> [ModSummary] -- Old summaries
1373 -> [ModuleName] -- Ignore dependencies on these; treat
1374 -- them as if they were package modules
1375 -> Bool -- True <=> allow multiple targets to have
1376 -- the same module name; this is
1377 -- very useful for ghc -M
1378 -> IO (Maybe [ModSummary])
1379 -- The elts of [ModSummary] all have distinct
1380 -- (Modules, IsBoot) identifiers, unless the Bool is true
1381 -- in which case there can be repeats
1382 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1383 = -- catch error messages and return them
1384 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1385 rootSummaries <- mapM getRootSummary roots
1386 let root_map = mkRootMap rootSummaries
1387 checkDuplicates root_map
1388 summs <- loop (concatMap msDeps rootSummaries) root_map
1391 roots = hsc_targets hsc_env
1393 old_summary_map :: NodeMap ModSummary
1394 old_summary_map = mkNodeMap old_summaries
1396 getRootSummary :: Target -> IO ModSummary
1397 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1398 = do exists <- doesFileExist file
1400 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1401 else throwDyn $ mkPlainErrMsg noSrcSpan $
1402 text "can't find file:" <+> text file
1403 getRootSummary (Target (TargetModule modl) maybe_buf)
1404 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1405 (L rootLoc modl) maybe_buf excl_mods
1406 case maybe_summary of
1407 Nothing -> packageModErr modl
1410 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1412 -- In a root module, the filename is allowed to diverge from the module
1413 -- name, so we have to check that there aren't multiple root files
1414 -- defining the same module (otherwise the duplicates will be silently
1415 -- ignored, leading to confusing behaviour).
1416 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1417 checkDuplicates root_map
1418 | allow_dup_roots = return ()
1419 | null dup_roots = return ()
1420 | otherwise = multiRootsErr (head dup_roots)
1422 dup_roots :: [[ModSummary]] -- Each at least of length 2
1423 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1425 loop :: [(Located ModuleName,IsBootInterface)]
1426 -- Work list: process these modules
1427 -> NodeMap [ModSummary]
1428 -- Visited set; the range is a list because
1429 -- the roots can have the same module names
1430 -- if allow_dup_roots is True
1432 -- The result includes the worklist, except
1433 -- for those mentioned in the visited set
1434 loop [] done = return (concat (nodeMapElts done))
1435 loop ((wanted_mod, is_boot) : ss) done
1436 | Just summs <- lookupFM done key
1437 = if isSingleton summs then
1440 do { multiRootsErr summs; return [] }
1441 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1442 is_boot wanted_mod Nothing excl_mods
1444 Nothing -> loop ss done
1445 Just s -> loop (msDeps s ++ ss)
1446 (addToFM done key [s]) }
1448 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1450 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1451 mkRootMap summaries = addListToFM_C (++) emptyFM
1452 [ (msKey s, [s]) | s <- summaries ]
1454 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1455 -- (msDeps s) returns the dependencies of the ModSummary s.
1456 -- A wrinkle is that for a {-# SOURCE #-} import we return
1457 -- *both* the hs-boot file
1458 -- *and* the source file
1459 -- as "dependencies". That ensures that the list of all relevant
1460 -- modules always contains B.hs if it contains B.hs-boot.
1461 -- Remember, this pass isn't doing the topological sort. It's
1462 -- just gathering the list of all relevant ModSummaries
1464 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1465 ++ [ (m,False) | m <- ms_imps s ]
1467 -----------------------------------------------------------------------------
1468 -- Summarising modules
1470 -- We have two types of summarisation:
1472 -- * Summarise a file. This is used for the root module(s) passed to
1473 -- cmLoadModules. The file is read, and used to determine the root
1474 -- module name. The module name may differ from the filename.
1476 -- * Summarise a module. We are given a module name, and must provide
1477 -- a summary. The finder is used to locate the file in which the module
1482 -> [ModSummary] -- old summaries
1483 -> FilePath -- source file name
1484 -> Maybe Phase -- start phase
1485 -> Maybe (StringBuffer,ClockTime)
1488 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1489 -- we can use a cached summary if one is available and the
1490 -- source file hasn't changed, But we have to look up the summary
1491 -- by source file, rather than module name as we do in summarise.
1492 | Just old_summary <- findSummaryBySourceFile old_summaries file
1494 let location = ms_location old_summary
1496 -- return the cached summary if the source didn't change
1497 src_timestamp <- case maybe_buf of
1498 Just (_,t) -> return t
1499 Nothing -> getModificationTime file
1500 -- The file exists; we checked in getRootSummary above.
1501 -- If it gets removed subsequently, then this
1502 -- getModificationTime may fail, but that's the right
1505 if ms_hs_date old_summary == src_timestamp
1506 then do -- update the object-file timestamp
1507 obj_timestamp <- getObjTimestamp location False
1508 return old_summary{ ms_obj_date = obj_timestamp }
1516 let dflags = hsc_dflags hsc_env
1518 (dflags', hspp_fn, buf)
1519 <- preprocessFile dflags file mb_phase maybe_buf
1521 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1523 -- Make a ModLocation for this file
1524 location <- mkHomeModLocation dflags mod_name file
1526 -- Tell the Finder cache where it is, so that subsequent calls
1527 -- to findModule will find it, even if it's not on any search path
1528 mod <- addHomeModuleToFinder hsc_env mod_name location
1530 src_timestamp <- case maybe_buf of
1531 Just (_,t) -> return t
1532 Nothing -> getModificationTime file
1533 -- getMofificationTime may fail
1535 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1537 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1538 ms_location = location,
1539 ms_hspp_file = hspp_fn,
1540 ms_hspp_opts = dflags',
1541 ms_hspp_buf = Just buf,
1542 ms_srcimps = srcimps, ms_imps = the_imps,
1543 ms_hs_date = src_timestamp,
1544 ms_obj_date = obj_timestamp })
1546 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1547 findSummaryBySourceFile summaries file
1548 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1549 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1553 -- Summarise a module, and pick up source and timestamp.
1556 -> NodeMap ModSummary -- Map of old summaries
1557 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1558 -> Located ModuleName -- Imported module to be summarised
1559 -> Maybe (StringBuffer, ClockTime)
1560 -> [ModuleName] -- Modules to exclude
1561 -> IO (Maybe ModSummary) -- Its new summary
1563 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1564 | wanted_mod `elem` excl_mods
1567 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1568 = do -- Find its new timestamp; all the
1569 -- ModSummaries in the old map have valid ml_hs_files
1570 let location = ms_location old_summary
1571 src_fn = expectJust "summariseModule" (ml_hs_file location)
1573 -- check the modification time on the source file, and
1574 -- return the cached summary if it hasn't changed. If the
1575 -- file has disappeared, we need to call the Finder again.
1577 Just (_,t) -> check_timestamp old_summary location src_fn t
1579 m <- System.IO.Error.try (getModificationTime src_fn)
1581 Right t -> check_timestamp old_summary location src_fn t
1582 Left e | isDoesNotExistError e -> find_it
1583 | otherwise -> ioError e
1585 | otherwise = find_it
1587 dflags = hsc_dflags hsc_env
1589 hsc_src = if is_boot then HsBootFile else HsSrcFile
1591 check_timestamp old_summary location src_fn src_timestamp
1592 | ms_hs_date old_summary == src_timestamp = do
1593 -- update the object-file timestamp
1594 obj_timestamp <- getObjTimestamp location is_boot
1595 return (Just old_summary{ ms_obj_date = obj_timestamp })
1597 -- source changed: re-summarise.
1598 new_summary location (ms_mod old_summary) src_fn src_timestamp
1601 -- Don't use the Finder's cache this time. If the module was
1602 -- previously a package module, it may have now appeared on the
1603 -- search path, so we want to consider it to be a home module. If
1604 -- the module was previously a home module, it may have moved.
1605 uncacheModule hsc_env wanted_mod
1606 found <- findImportedModule hsc_env wanted_mod Nothing
1609 | isJust (ml_hs_file location) ->
1611 just_found location mod
1613 -- Drop external-pkg
1614 ASSERT(modulePackageId mod /= thisPackage dflags)
1618 err -> noModError dflags loc wanted_mod err
1621 just_found location mod = do
1622 -- Adjust location to point to the hs-boot source file,
1623 -- hi file, object file, when is_boot says so
1624 let location' | is_boot = addBootSuffixLocn location
1625 | otherwise = location
1626 src_fn = expectJust "summarise2" (ml_hs_file location')
1628 -- Check that it exists
1629 -- It might have been deleted since the Finder last found it
1630 maybe_t <- modificationTimeIfExists src_fn
1632 Nothing -> noHsFileErr loc src_fn
1633 Just t -> new_summary location' mod src_fn t
1636 new_summary location mod src_fn src_timestamp
1638 -- Preprocess the source file and get its imports
1639 -- The dflags' contains the OPTIONS pragmas
1640 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1641 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1643 when (mod_name /= wanted_mod) $
1644 throwDyn $ mkPlainErrMsg mod_loc $
1645 text "file name does not match module name"
1646 <+> quotes (ppr mod_name)
1648 -- Find the object timestamp, and return the summary
1649 obj_timestamp <- getObjTimestamp location is_boot
1651 return (Just ( ModSummary { ms_mod = mod,
1652 ms_hsc_src = hsc_src,
1653 ms_location = location,
1654 ms_hspp_file = hspp_fn,
1655 ms_hspp_opts = dflags',
1656 ms_hspp_buf = Just buf,
1657 ms_srcimps = srcimps,
1659 ms_hs_date = src_timestamp,
1660 ms_obj_date = obj_timestamp }))
1663 getObjTimestamp location is_boot
1664 = if is_boot then return Nothing
1665 else modificationTimeIfExists (ml_obj_file location)
1668 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1669 -> IO (DynFlags, FilePath, StringBuffer)
1670 preprocessFile dflags src_fn mb_phase Nothing
1672 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1673 buf <- hGetStringBuffer hspp_fn
1674 return (dflags', hspp_fn, buf)
1676 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1678 -- case we bypass the preprocessing stage?
1680 local_opts = getOptions buf src_fn
1682 (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1686 | Just (Unlit _) <- mb_phase = True
1687 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1688 -- note: local_opts is only required if there's no Unlit phase
1689 | dopt Opt_Cpp dflags' = True
1690 | dopt Opt_Pp dflags' = True
1693 when needs_preprocessing $
1694 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1696 return (dflags', src_fn, buf)
1699 -----------------------------------------------------------------------------
1701 -----------------------------------------------------------------------------
1703 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1704 -- ToDo: we don't have a proper line number for this error
1705 noModError dflags loc wanted_mod err
1706 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1708 noHsFileErr loc path
1709 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1712 = throwDyn $ mkPlainErrMsg noSrcSpan $
1713 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1715 multiRootsErr :: [ModSummary] -> IO ()
1716 multiRootsErr summs@(summ1:_)
1717 = throwDyn $ mkPlainErrMsg noSrcSpan $
1718 text "module" <+> quotes (ppr mod) <+>
1719 text "is defined in multiple files:" <+>
1720 sep (map text files)
1723 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1725 cyclicModuleErr :: [ModSummary] -> SDoc
1727 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1728 2 (vcat (map show_one ms))
1730 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1731 nest 2 $ ptext SLIT("imports:") <+>
1732 (pp_imps HsBootFile (ms_srcimps ms)
1733 $$ pp_imps HsSrcFile (ms_imps ms))]
1734 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1735 pp_imps src mods = fsep (map (show_mod src) mods)
1738 -- | Inform GHC that the working directory has changed. GHC will flush
1739 -- its cache of module locations, since it may no longer be valid.
1740 -- Note: if you change the working directory, you should also unload
1741 -- the current program (set targets to empty, followed by load).
1742 workingDirectoryChanged :: Session -> IO ()
1743 workingDirectoryChanged s = withSession s $ flushFinderCaches
1745 -- -----------------------------------------------------------------------------
1746 -- inspecting the session
1748 -- | Get the module dependency graph.
1749 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1750 getModuleGraph s = withSession s (return . hsc_mod_graph)
1752 isLoaded :: Session -> ModuleName -> IO Bool
1753 isLoaded s m = withSession s $ \hsc_env ->
1754 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1756 getBindings :: Session -> IO [TyThing]
1757 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1759 getPrintUnqual :: Session -> IO PrintUnqualified
1760 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1762 -- | Container for information about a 'Module'.
1763 data ModuleInfo = ModuleInfo {
1764 minf_type_env :: TypeEnv,
1765 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1766 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1767 minf_instances :: [Instance]
1769 ,minf_dbg_sites :: [(SiteNumber,Coord)]
1771 -- ToDo: this should really contain the ModIface too
1773 -- We don't want HomeModInfo here, because a ModuleInfo applies
1774 -- to package modules too.
1776 -- | Request information about a loaded 'Module'
1777 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1778 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1779 let mg = hsc_mod_graph hsc_env
1780 if mdl `elem` map ms_mod mg
1781 then getHomeModuleInfo hsc_env (moduleName mdl)
1783 {- if isHomeModule (hsc_dflags hsc_env) mdl
1785 else -} getPackageModuleInfo hsc_env mdl
1786 -- getPackageModuleInfo will attempt to find the interface, so
1787 -- we don't want to call it for a home module, just in case there
1788 -- was a problem loading the module and the interface doesn't
1789 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1791 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1792 getPackageModuleInfo hsc_env mdl = do
1794 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1796 Nothing -> return Nothing
1798 eps <- readIORef (hsc_EPS hsc_env)
1800 names = availsToNameSet avails
1802 tys = [ ty | name <- concatMap availNames avails,
1803 Just ty <- [lookupTypeEnv pte name] ]
1805 return (Just (ModuleInfo {
1806 minf_type_env = mkTypeEnv tys,
1807 minf_exports = names,
1808 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1809 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1810 minf_dbg_sites = noDbgSites
1813 -- bogusly different for non-GHCI (ToDo)
1817 getHomeModuleInfo hsc_env mdl =
1818 case lookupUFM (hsc_HPT hsc_env) mdl of
1819 Nothing -> return Nothing
1821 let details = hm_details hmi
1822 return (Just (ModuleInfo {
1823 minf_type_env = md_types details,
1824 minf_exports = availsToNameSet (md_exports details),
1825 minf_rdr_env = mi_globals $! hm_iface hmi,
1826 minf_instances = md_insts details
1828 ,minf_dbg_sites = md_dbg_sites details
1832 -- | The list of top-level entities defined in a module
1833 modInfoTyThings :: ModuleInfo -> [TyThing]
1834 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1836 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1837 modInfoTopLevelScope minf
1838 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1840 modInfoExports :: ModuleInfo -> [Name]
1841 modInfoExports minf = nameSetToList $! minf_exports minf
1843 -- | Returns the instances defined by the specified module.
1844 -- Warning: currently unimplemented for package modules.
1845 modInfoInstances :: ModuleInfo -> [Instance]
1846 modInfoInstances = minf_instances
1848 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1849 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1851 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1852 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1854 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1855 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1856 case lookupTypeEnv (minf_type_env minf) name of
1857 Just tyThing -> return (Just tyThing)
1859 eps <- readIORef (hsc_EPS hsc_env)
1860 return $! lookupType (hsc_dflags hsc_env)
1861 (hsc_HPT hsc_env) (eps_PTE eps) name
1864 modInfoBkptSites = minf_dbg_sites
1867 isDictonaryId :: Id -> Bool
1869 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1871 -- | Looks up a global name: that is, any top-level name in any
1872 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1873 -- the interactive context, and therefore does not require a preceding
1875 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1876 lookupGlobalName s name = withSession s $ \hsc_env -> do
1877 eps <- readIORef (hsc_EPS hsc_env)
1878 return $! lookupType (hsc_dflags hsc_env)
1879 (hsc_HPT hsc_env) (eps_PTE eps) name
1881 -- -----------------------------------------------------------------------------
1882 -- Misc exported utils
1884 dataConType :: DataCon -> Type
1885 dataConType dc = idType (dataConWrapId dc)
1887 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1888 pprParenSymName :: NamedThing a => a -> SDoc
1889 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1891 -- ----------------------------------------------------------------------------
1896 -- - Data and Typeable instances for HsSyn.
1898 -- ToDo: check for small transformations that happen to the syntax in
1899 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1901 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1902 -- to get from TyCons, Ids etc. to TH syntax (reify).
1904 -- :browse will use either lm_toplev or inspect lm_interface, depending
1905 -- on whether the module is interpreted or not.
1907 -- This is for reconstructing refactored source code
1908 -- Calls the lexer repeatedly.
1909 -- ToDo: add comment tokens to token stream
1910 getTokenStream :: Session -> Module -> IO [Located Token]
1913 -- -----------------------------------------------------------------------------
1914 -- Interactive evaluation
1916 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1917 -- filesystem and package database to find the corresponding 'Module',
1918 -- using the algorithm that is used for an @import@ declaration.
1919 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1920 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1921 findModule' hsc_env mod_name maybe_pkg
1923 findModule' hsc_env mod_name maybe_pkg =
1925 dflags = hsc_dflags hsc_env
1926 hpt = hsc_HPT hsc_env
1927 this_pkg = thisPackage dflags
1929 case lookupUFM hpt mod_name of
1930 Just mod_info -> return (mi_module (hm_iface mod_info))
1931 _not_a_home_module -> do
1932 res <- findImportedModule hsc_env mod_name Nothing
1934 Found _ m | modulePackageId m /= this_pkg -> return m
1935 | otherwise -> throwDyn (CmdLineError (showSDoc $
1936 text "module" <+> pprModule m <+>
1937 text "is not loaded"))
1938 err -> let msg = cannotFindModule dflags mod_name err in
1939 throwDyn (CmdLineError (showSDoc msg))
1943 -- | Set the interactive evaluation context.
1945 -- Setting the context doesn't throw away any bindings; the bindings
1946 -- we've built up in the InteractiveContext simply move to the new
1947 -- module. They always shadow anything in scope in the current context.
1948 setContext :: Session
1949 -> [Module] -- entire top level scope of these modules
1950 -> [Module] -- exports only of these modules
1952 setContext sess@(Session ref) toplev_mods export_mods = do
1953 hsc_env <- readIORef ref
1954 let old_ic = hsc_IC hsc_env
1955 hpt = hsc_HPT hsc_env
1957 export_env <- mkExportEnv hsc_env export_mods
1958 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
1959 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1960 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
1961 ic_exports = export_mods,
1962 ic_rn_gbl_env = all_env }}
1963 reinstallBreakpointHandlers sess
1965 -- Make a GlobalRdrEnv based on the exports of the modules only.
1966 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1967 mkExportEnv hsc_env mods = do
1968 stuff <- mapM (getModuleExports hsc_env) mods
1970 (_msgs, mb_name_sets) = unzip stuff
1971 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
1972 | (Just avails, mod) <- zip mb_name_sets mods ]
1974 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1976 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
1977 nameSetToGlobalRdrEnv names mod =
1978 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1979 | name <- nameSetToList names ]
1981 vanillaProv :: ModuleName -> Provenance
1982 -- We're building a GlobalRdrEnv as if the user imported
1983 -- all the specified modules into the global interactive module
1984 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1986 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
1988 is_dloc = srcLocSpan interactiveSrcLoc }
1990 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1991 mkTopLevEnv hpt modl
1992 = case lookupUFM hpt (moduleName modl) of
1993 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
1994 showSDoc (ppr modl)))
1996 case mi_globals (hm_iface details) of
1998 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1999 ++ showSDoc (ppr modl)))
2000 Just env -> return env
2002 -- | Get the interactive evaluation context, consisting of a pair of the
2003 -- set of modules from which we take the full top-level scope, and the set
2004 -- of modules from which we take just the exports respectively.
2005 getContext :: Session -> IO ([Module],[Module])
2006 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
2007 return (ic_toplev_scope ic, ic_exports ic))
2009 -- | Returns 'True' if the specified module is interpreted, and hence has
2010 -- its full top-level scope available.
2011 moduleIsInterpreted :: Session -> Module -> IO Bool
2012 moduleIsInterpreted s modl = withSession s $ \h ->
2013 if modulePackageId modl /= thisPackage (hsc_dflags h)
2015 else case lookupUFM (hsc_HPT h) (moduleName modl) of
2016 Just details -> return (isJust (mi_globals (hm_iface details)))
2017 _not_a_home_module -> return False
2019 -- | Looks up an identifier in the current interactive context (for :info)
2020 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
2021 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
2023 -- | Returns all names in scope in the current interactive context
2024 getNamesInScope :: Session -> IO [Name]
2025 getNamesInScope s = withSession s $ \hsc_env -> do
2026 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
2028 getRdrNamesInScope :: Session -> IO [RdrName]
2029 getRdrNamesInScope s = withSession s $ \hsc_env -> do
2030 let env = ic_rn_gbl_env (hsc_IC hsc_env)
2031 return (concat (map greToRdrNames (globalRdrEnvElts env)))
2033 -- ToDo: move to RdrName
2034 greToRdrNames :: GlobalRdrElt -> [RdrName]
2035 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
2037 LocalDef -> [unqual]
2038 Imported specs -> concat (map do_spec (map is_decl specs))
2040 occ = nameOccName name
2043 | is_qual decl_spec = [qual]
2044 | otherwise = [unqual,qual]
2045 where qual = Qual (is_as decl_spec) occ
2047 -- | Parses a string as an identifier, and returns the list of 'Name's that
2048 -- the identifier can refer to in the current interactive context.
2049 parseName :: Session -> String -> IO [Name]
2050 parseName s str = withSession s $ \hsc_env -> do
2051 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
2052 case maybe_rdr_name of
2053 Nothing -> return []
2054 Just (L _ rdr_name) -> do
2055 mb_names <- tcRnLookupRdrName hsc_env rdr_name
2057 Nothing -> return []
2058 Just ns -> return ns
2059 -- ToDo: should return error messages
2061 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
2062 -- entity known to GHC, including 'Name's defined using 'runStmt'.
2063 lookupName :: Session -> Name -> IO (Maybe TyThing)
2064 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
2066 -- -----------------------------------------------------------------------------
2067 -- Getting the type of an expression
2069 -- | Get the type of an expression
2070 exprType :: Session -> String -> IO (Maybe Type)
2071 exprType s expr = withSession s $ \hsc_env -> do
2072 maybe_stuff <- hscTcExpr hsc_env expr
2074 Nothing -> return Nothing
2075 Just ty -> return (Just tidy_ty)
2077 tidy_ty = tidyType emptyTidyEnv ty
2079 -- -----------------------------------------------------------------------------
2080 -- Getting the kind of a type
2082 -- | Get the kind of a type
2083 typeKind :: Session -> String -> IO (Maybe Kind)
2084 typeKind s str = withSession s $ \hsc_env -> do
2085 maybe_stuff <- hscKcType hsc_env str
2087 Nothing -> return Nothing
2088 Just kind -> return (Just kind)
2090 -----------------------------------------------------------------------------
2091 -- cmCompileExpr: compile an expression and deliver an HValue
2093 compileExpr :: Session -> String -> IO (Maybe HValue)
2094 compileExpr s expr = withSession s $ \hsc_env -> do
2095 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
2097 Nothing -> return Nothing
2098 Just (new_ic, names, hval) -> do
2100 hvals <- (unsafeCoerce# hval) :: IO [HValue]
2102 case (names,hvals) of
2103 ([n],[hv]) -> return (Just hv)
2104 _ -> panic "compileExpr"
2106 -- -----------------------------------------------------------------------------
2107 -- Compile an expression into a dynamic
2109 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
2110 dynCompileExpr ses expr = do
2111 (full,exports) <- getContext ses
2112 setContext ses full $
2114 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
2116 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
2117 res <- withSession ses (flip hscStmt stmt)
2118 setContext ses full exports
2120 Nothing -> return Nothing
2121 Just (_, names, hvals) -> do
2122 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
2123 case (names,vals) of
2124 (_:[], v:[]) -> return (Just v)
2125 _ -> panic "dynCompileExpr"
2127 -- -----------------------------------------------------------------------------
2128 -- running a statement interactively
2131 = RunOk [Name] -- ^ names bound by this evaluation
2132 | RunFailed -- ^ statement failed compilation
2133 | RunException Exception -- ^ statement raised an exception
2135 -- | Run a statement in the current interactive context. Statemenet
2136 -- may bind multple values.
2137 runStmt :: Session -> String -> IO RunResult
2138 runStmt (Session ref) expr
2140 hsc_env <- readIORef ref
2142 -- Turn off -fwarn-unused-bindings when running a statement, to hide
2143 -- warnings about the implicit bindings we introduce.
2144 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
2145 hsc_env' = hsc_env{ hsc_dflags = dflags' }
2147 maybe_stuff <- hscStmt hsc_env' expr
2150 Nothing -> return RunFailed
2151 Just (new_hsc_env, names, hval) -> do
2153 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2154 either_hvals <- sandboxIO thing_to_run
2156 case either_hvals of
2158 -- on error, keep the *old* interactive context,
2159 -- so that 'it' is not bound to something
2160 -- that doesn't exist.
2161 return (RunException e)
2164 -- Get the newly bound things, and bind them.
2165 -- Don't need to delete any shadowed bindings;
2166 -- the new ones override the old ones.
2167 extendLinkEnv (zip names hvals)
2169 writeIORef ref new_hsc_env
2170 return (RunOk names)
2172 -- When running a computation, we redirect ^C exceptions to the running
2173 -- thread. ToDo: we might want a way to continue even if the target
2174 -- thread doesn't die when it receives the exception... "this thread
2175 -- is not responding".
2176 sandboxIO :: IO a -> IO (Either Exception a)
2177 sandboxIO thing = do
2179 ts <- takeMVar interruptTargetThread
2180 child <- forkIO (do res <- Exception.try thing; putMVar m res)
2181 putMVar interruptTargetThread (child:ts)
2182 takeMVar m `finally` modifyMVar_ interruptTargetThread (return.tail)
2185 -- This version of sandboxIO runs the expression in a completely new
2186 -- RTS main thread. It is disabled for now because ^C exceptions
2187 -- won't be delivered to the new thread, instead they'll be delivered
2188 -- to the (blocked) GHCi main thread.
2190 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2192 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2193 sandboxIO thing = do
2194 st_thing <- newStablePtr (Exception.try thing)
2195 alloca $ \ p_st_result -> do
2196 stat <- rts_evalStableIO st_thing p_st_result
2197 freeStablePtr st_thing
2199 then do st_result <- peek p_st_result
2200 result <- deRefStablePtr st_result
2201 freeStablePtr st_result
2202 return (Right result)
2204 return (Left (fromIntegral stat))
2206 foreign import "rts_evalStableIO" {- safe -}
2207 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2208 -- more informative than the C type!
2212 -----------------------------------------------------------------------------
2213 -- show a module and it's source/object filenames
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)
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)
2226 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
2228 -----------------------------------------------------------------------------
2229 -- Breakpoint handlers
2231 getBreakpointHandler :: Session -> IO (Maybe (BkptHandler Module))
2232 getBreakpointHandler session = getSessionDynFlags session >>= return . bkptHandler
2234 setBreakpointHandler :: Session -> BkptHandler Module -> IO ()
2235 setBreakpointHandler session handler = do
2236 dflags <- getSessionDynFlags session
2237 setSessionDynFlags session dflags{ bkptHandler = Just handler }
2238 let linkEnv = [ ( breakpointJumpName
2239 , unsafeCoerce# (jumpFunction session handler))
2240 , ( breakpointCondJumpName
2241 , unsafeCoerce# (jumpCondFunction session handler))
2242 , ( breakpointAutoJumpName
2243 , unsafeCoerce# (jumpAutoFunction session handler))
2245 writeIORef v_bkptLinkEnv linkEnv
2246 dflags <- getSessionDynFlags session
2247 reinstallBreakpointHandlers session
2249 reinstallBreakpointHandlers :: Session -> IO ()
2250 reinstallBreakpointHandlers session = do
2251 dflags <- getSessionDynFlags session
2252 let mode = ghcMode dflags
2253 when (mode == Interactive) $ do
2254 linkEnv <- readIORef v_bkptLinkEnv
2255 initDynLinker dflags
2256 extendLinkEnv linkEnv
2258 -----------------------------------------------------------------------
2261 type SiteInfo = (String, SiteNumber)
2262 jumpFunction, jumpAutoFunction :: Session -> BkptHandler Module -> SiteInfo -> (Int, [Opaque], String) -> b -> b
2263 jumpCondFunction :: Session -> BkptHandler Module -> SiteInfo -> (Int, [Opaque], String) -> Bool -> b -> b
2264 jumpFunctionM :: Session -> BkptHandler a -> BkptLocation a -> (Int, [Opaque], String) -> b -> IO b
2266 jumpCondFunction _ _ _ _ False b = b
2267 jumpCondFunction session handler site args True b
2268 = jumpFunction session handler site args b
2270 jumpFunction session handler siteInfo args b
2271 | site <- mkSite siteInfo
2272 = unsafePerformIO $ jumpFunctionM session handler site args b
2274 jumpFunctionM session handler site (I# idsPtr, wrapped_hValues, locmsg) b =
2276 ids <- deRefStablePtr (castPtrToStablePtr (Ptr (int2Addr# idsPtr)))
2277 let hValues = unsafeCoerce# b : [unsafeCoerce# hv | O hv <- wrapped_hValues]
2278 handleBreakpoint handler session (zip ids hValues) site locmsg b
2280 jumpAutoFunction session handler siteInfo args b
2281 | site <- mkSite siteInfo
2282 = unsafePerformIO $ do
2283 break <- isAutoBkptEnabled handler session site
2285 then jumpFunctionM session handler site args b
2288 jumpStepByStepFunction session handler siteInfo args b
2289 | site <- mkSite siteInfo
2290 = unsafePerformIO $ do
2291 jumpFunctionM session handler site args b
2293 mkSite :: SiteInfo -> BkptLocation Module
2294 mkSite ( modName, sitenum) =
2295 (mkModule mainPackageId (mkModuleName modName), sitenum)
2297 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2298 obtainTerm1 sess force mb_ty x = withSession sess $ \hsc_env -> cvObtainTerm hsc_env force mb_ty (unsafeCoerce# x)
2300 obtainTerm :: Session -> Bool -> Id -> IO (Maybe Term)
2301 obtainTerm sess force id = withSession sess $ \hsc_env -> do
2302 mb_v <- getHValue (varName id)
2304 Just v -> fmap Just$ cvObtainTerm hsc_env force (Just$ idType id) v
2305 Nothing -> return Nothing