1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
18 GhcMode(..), GhcLink(..),
24 Target(..), TargetId(..), Phase,
31 -- * Extending the program scope
32 extendGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
33 setGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
34 extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
35 setGlobalTypeScope, -- :: Session -> [Id] -> IO ()
37 -- * Loading\/compiling the program
39 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
40 workingDirectoryChanged,
41 checkModule, CheckedModule(..),
42 TypecheckedSource, ParsedSource, RenamedSource,
44 -- * Parsing Haddock comments
47 -- * Inspecting the module structure of the program
48 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
53 -- * Inspecting modules
58 modInfoPrintUnqualified,
61 modInfoIsExportedName,
69 PrintUnqualified, alwaysQualify,
71 -- * Interactive evaluation
72 getBindings, getPrintUnqual,
75 setContext, getContext,
87 compileExpr, HValue, dynCompileExpr,
90 getBreakpointHandler, setBreakpointHandler,
91 obtainTerm, obtainTerm1,
94 -- * Abstract syntax elements
100 Module, mkModule, pprModule, moduleName, modulePackageId,
101 ModuleName, mkModuleName, moduleNameString,
105 nameModule, pprParenSymName, nameSrcLoc,
107 RdrName(Qual,Unqual),
111 isImplicitId, isDeadBinder,
112 isExportedId, isLocalId, isGlobalId,
114 isPrimOpId, isFCallId, isClassOpId_maybe,
115 isDataConWorkId, idDataCon,
116 isBottomingId, isDictonaryId,
117 recordSelectorFieldLabel,
119 -- ** Type constructors
121 tyConTyVars, tyConDataCons, tyConArity,
122 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
124 synTyConDefn, synTyConType, synTyConResKind,
130 -- ** Data constructors
132 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
133 dataConIsInfix, isVanillaDataCon,
135 StrictnessMark(..), isMarkedStrict,
139 classMethods, classSCTheta, classTvsFds,
144 instanceDFunId, pprInstance, pprInstanceHdr,
146 -- ** Types and Kinds
147 Type, dropForAlls, splitForAllTys, funResultTy,
148 pprParendType, pprTypeApp,
151 ThetaType, pprThetaArrow,
157 module HsSyn, -- ToDo: remove extraneous bits
161 defaultFixity, maxPrecedence,
165 -- ** Source locations
169 GhcException(..), showGhcException,
179 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
180 * what StaticFlags should we expose, if any?
183 #include "HsVersions.h"
186 import RtClosureInspect ( cvObtainTerm, Term )
187 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
188 tcRnLookupName, getModuleExports )
189 import RdrName ( plusGlobalRdrEnv, Provenance(..),
190 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
192 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
193 import Name ( nameOccName )
194 import Type ( tidyType )
195 import Var ( varName )
196 import VarEnv ( emptyTidyEnv )
197 import GHC.Exts ( unsafeCoerce# )
200 import Breakpoints ( SiteNumber, Coord, nullBkptHandler,
201 BkptHandler(..), BkptLocation, noDbgSites )
202 import Linker ( initDynLinker )
203 import PrelNames ( breakpointJumpName, breakpointCondJumpName,
204 breakpointAutoJumpName )
206 import GHC.Exts ( Int(..), Ptr(..), int2Addr#, indexArray# )
207 import GHC.Base ( Opaque(..) )
208 import Foreign.StablePtr( deRefStablePtr, castPtrToStablePtr )
209 import Foreign ( unsafePerformIO )
210 import Data.Maybe ( fromMaybe)
211 import qualified Linker
213 import Data.Dynamic ( Dynamic )
214 import Linker ( HValue, getHValue, extendLinkEnv )
217 import Packages ( initPackages )
218 import NameSet ( NameSet, nameSetToList, elemNameSet )
219 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..),
220 globalRdrEnvElts, extendGlobalRdrEnv,
223 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
224 pprThetaArrow, pprParendType, splitForAllTys,
225 pprTypeApp, funResultTy )
226 import Id ( Id, idType, isImplicitId, isDeadBinder,
227 isExportedId, isLocalId, isGlobalId,
228 isRecordSelector, recordSelectorFieldLabel,
229 isPrimOpId, isFCallId, isClassOpId_maybe,
230 isDataConWorkId, idDataCon,
233 import TysPrim ( alphaTyVars )
234 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
235 isPrimTyCon, isFunTyCon, isOpenTyCon, tyConArity,
236 tyConTyVars, tyConDataCons, synTyConDefn,
237 synTyConType, synTyConResKind )
238 import Class ( Class, classSCTheta, classTvsFds, classMethods )
239 import FunDeps ( pprFundeps )
240 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
241 dataConFieldLabels, dataConStrictMarks,
242 dataConIsInfix, isVanillaDataCon )
243 import Name ( Name, nameModule, NamedThing(..), nameSrcLoc )
244 import OccName ( parenSymOcc )
245 import NameEnv ( nameEnvElts )
246 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
248 import DriverPipeline
249 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
250 import HeaderInfo ( getImports, getOptions )
252 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
255 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
259 import PackageConfig ( PackageId, stringToPackageId, mainPackageId )
263 import Bag ( unitBag, listToBag )
264 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
265 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
267 import qualified ErrUtils
269 import StringBuffer ( StringBuffer, hGetStringBuffer )
272 import TcType ( tcSplitSigmaTy, isDictTy )
273 import Maybes ( expectJust, mapCatMaybes )
274 import HaddockParse ( parseHaddockParagraphs, parseHaddockString )
275 import HaddockLex ( tokenise )
277 import Control.Concurrent
278 import System.Directory ( getModificationTime, doesFileExist )
279 import Data.Maybe ( isJust, isNothing )
280 import Data.List ( partition, nub )
281 import qualified Data.List as List
282 import Control.Monad ( unless, when )
283 import System.Exit ( exitWith, ExitCode(..) )
284 import System.Time ( ClockTime )
285 import Control.Exception as Exception hiding (handle)
288 import System.IO.Error ( isDoesNotExistError )
289 import Prelude hiding (init)
291 #if __GLASGOW_HASKELL__ < 600
292 import System.IO as System.IO.Error ( try )
294 import System.IO.Error ( try )
297 -- -----------------------------------------------------------------------------
298 -- Exception handlers
300 -- | Install some default exception handlers and run the inner computation.
301 -- Unless you want to handle exceptions yourself, you should wrap this around
302 -- the top level of your program. The default handlers output the error
303 -- message(s) to stderr and exit cleanly.
304 defaultErrorHandler :: DynFlags -> IO a -> IO a
305 defaultErrorHandler dflags inner =
306 -- top-level exception handler: any unrecognised exception is a compiler bug.
307 handle (\exception -> do
310 -- an IO exception probably isn't our fault, so don't panic
312 fatalErrorMsg dflags (text (show exception))
313 AsyncException StackOverflow ->
314 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
316 fatalErrorMsg dflags (text (show (Panic (show exception))))
317 exitWith (ExitFailure 1)
320 -- program errors: messages with locations attached. Sometimes it is
321 -- convenient to just throw these as exceptions.
322 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
323 exitWith (ExitFailure 1)) $
325 -- error messages propagated as exceptions
326 handleDyn (\dyn -> do
329 PhaseFailed _ code -> exitWith code
330 Interrupted -> exitWith (ExitFailure 1)
331 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
332 exitWith (ExitFailure 1)
336 -- | Install a default cleanup handler to remove temporary files
337 -- deposited by a GHC run. This is seperate from
338 -- 'defaultErrorHandler', because you might want to override the error
339 -- handling, but still get the ordinary cleanup behaviour.
340 defaultCleanupHandler :: DynFlags -> IO a -> IO a
341 defaultCleanupHandler dflags inner =
342 -- make sure we clean up after ourselves
343 later (do cleanTempFiles dflags
346 -- exceptions will be blocked while we clean the temporary files,
347 -- so there shouldn't be any difficulty if we receive further
353 GLOBAL_VAR(v_bkptLinkEnv, [], [(Name, HValue)])
354 -- stores the current breakpoint handler to help setContext to
355 -- restore it after a context change
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 newSession :: Maybe FilePath -> IO Session
361 newSession mb_top_dir = do
363 main_thread <- myThreadId
364 modifyMVar_ interruptTargetThread (return . (main_thread :))
365 installSignalHandlers
367 dflags0 <- initSysTools mb_top_dir defaultDynFlags
368 dflags <- initDynFlags dflags0
369 env <- newHscEnv dflags
373 -- tmp: this breaks the abstraction, but required because DriverMkDepend
374 -- needs to call the Finder. ToDo: untangle this.
375 sessionHscEnv :: Session -> IO HscEnv
376 sessionHscEnv (Session ref) = readIORef ref
378 withSession :: Session -> (HscEnv -> IO a) -> IO a
379 withSession (Session ref) f = do h <- readIORef ref; f h
381 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
382 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
384 -- -----------------------------------------------------------------------------
387 -- | Grabs the DynFlags from the Session
388 getSessionDynFlags :: Session -> IO DynFlags
389 getSessionDynFlags s = withSession s (return . hsc_dflags)
391 -- | Updates the DynFlags in a Session. This also reads
392 -- the package database (unless it has already been read),
393 -- and prepares the compilers knowledge about packages. It
394 -- can be called again to load new packages: just add new
395 -- package flags to (packageFlags dflags).
397 -- Returns a list of new packages that may need to be linked in using
398 -- the dynamic linker (see 'linkPackages') as a result of new package
399 -- flags. If you are not doing linking or doing static linking, you
400 -- can ignore the list of packages returned.
402 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
403 setSessionDynFlags (Session ref) dflags = do
404 hsc_env <- readIORef ref
405 (dflags', preload) <- initPackages dflags
406 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
409 -- | If there is no -o option, guess the name of target executable
410 -- by using top-level source file name as a base.
411 guessOutputFile :: Session -> IO ()
412 guessOutputFile s = modifySession s $ \env ->
413 let dflags = hsc_dflags env
414 mod_graph = hsc_mod_graph env
415 mainModuleSrcPath, guessedName :: Maybe String
416 mainModuleSrcPath = do
417 let isMain = (== mainModIs dflags) . ms_mod
418 [ms] <- return (filter isMain mod_graph)
419 ml_hs_file (ms_location ms)
420 guessedName = fmap basenameOf mainModuleSrcPath
422 case outputFile dflags of
424 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
426 -- -----------------------------------------------------------------------------
429 -- ToDo: think about relative vs. absolute file paths. And what
430 -- happens when the current directory changes.
432 -- | Sets the targets for this session. Each target may be a module name
433 -- or a filename. The targets correspond to the set of root modules for
434 -- the program\/library. Unloading the current program is achieved by
435 -- setting the current set of targets to be empty, followed by load.
436 setTargets :: Session -> [Target] -> IO ()
437 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
439 -- | returns the current set of targets
440 getTargets :: Session -> IO [Target]
441 getTargets s = withSession s (return . hsc_targets)
443 -- | Add another target
444 addTarget :: Session -> Target -> IO ()
446 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
449 removeTarget :: Session -> TargetId -> IO ()
450 removeTarget s target_id
451 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
453 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
455 -- Attempts to guess what Target a string refers to. This function implements
456 -- the --make/GHCi command-line syntax for filenames:
458 -- - if the string looks like a Haskell source filename, then interpret
460 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
462 -- - otherwise interpret the string as a module name
464 guessTarget :: String -> Maybe Phase -> IO Target
465 guessTarget file (Just phase)
466 = return (Target (TargetFile file (Just phase)) Nothing)
467 guessTarget file Nothing
468 | isHaskellSrcFilename file
469 = return (Target (TargetFile file Nothing) Nothing)
471 = do exists <- doesFileExist hs_file
473 then return (Target (TargetFile hs_file Nothing) Nothing)
475 exists <- doesFileExist lhs_file
477 then return (Target (TargetFile lhs_file Nothing) Nothing)
479 return (Target (TargetModule (mkModuleName file)) Nothing)
481 hs_file = file `joinFileExt` "hs"
482 lhs_file = file `joinFileExt` "lhs"
484 -- -----------------------------------------------------------------------------
485 -- Extending the program scope
487 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
488 extendGlobalRdrScope session rdrElts
489 = modifySession session $ \hscEnv ->
490 let global_rdr = hsc_global_rdr_env hscEnv
491 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
493 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
494 setGlobalRdrScope session rdrElts
495 = modifySession session $ \hscEnv ->
496 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
498 extendGlobalTypeScope :: Session -> [Id] -> IO ()
499 extendGlobalTypeScope session ids
500 = modifySession session $ \hscEnv ->
501 let global_type = hsc_global_type_env hscEnv
502 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
504 setGlobalTypeScope :: Session -> [Id] -> IO ()
505 setGlobalTypeScope session ids
506 = modifySession session $ \hscEnv ->
507 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
509 -- -----------------------------------------------------------------------------
510 -- Parsing Haddock comments
512 parseHaddockComment :: String -> Either String (HsDoc RdrName)
513 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
515 -- -----------------------------------------------------------------------------
516 -- Loading the program
518 -- Perform a dependency analysis starting from the current targets
519 -- and update the session with the new module graph.
520 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
521 depanal (Session ref) excluded_mods allow_dup_roots = do
522 hsc_env <- readIORef ref
524 dflags = hsc_dflags hsc_env
525 gmode = ghcMode (hsc_dflags hsc_env)
526 targets = hsc_targets hsc_env
527 old_graph = hsc_mod_graph hsc_env
529 showPass dflags "Chasing dependencies"
530 debugTraceMsg dflags 2 (hcat [
531 text "Chasing modules from: ",
532 hcat (punctuate comma (map pprTarget targets))])
534 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
536 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
541 -- | The result of load.
543 = LoadOk Errors -- ^ all specified targets were loaded successfully.
544 | LoadFailed Errors -- ^ not all modules were loaded.
546 type Errors = [String]
548 data ErrMsg = ErrMsg {
549 errMsgSeverity :: Severity, -- warning, error, etc.
550 errMsgSpans :: [SrcSpan],
551 errMsgShortDoc :: Doc,
552 errMsgExtraInfo :: Doc
558 | LoadUpTo ModuleName
559 | LoadDependenciesOf ModuleName
561 -- | Try to load the program. If a Module is supplied, then just
562 -- attempt to load up to this target. If no Module is supplied,
563 -- then try to load all targets.
564 load :: Session -> LoadHowMuch -> IO SuccessFlag
565 load s@(Session ref) how_much
567 -- Dependency analysis first. Note that this fixes the module graph:
568 -- even if we don't get a fully successful upsweep, the full module
569 -- graph is still retained in the Session. We can tell which modules
570 -- were successfully loaded by inspecting the Session's HPT.
571 mb_graph <- depanal s [] False
573 Just mod_graph -> load2 s how_much mod_graph
574 Nothing -> return Failed
576 load2 s@(Session ref) how_much mod_graph = do
578 hsc_env <- readIORef ref
580 let hpt1 = hsc_HPT hsc_env
581 let dflags = hsc_dflags hsc_env
582 let ghci_mode = ghcMode dflags -- this never changes
584 -- The "bad" boot modules are the ones for which we have
585 -- B.hs-boot in the module graph, but no B.hs
586 -- The downsweep should have ensured this does not happen
588 let all_home_mods = [ms_mod_name s
589 | s <- mod_graph, not (isBootSummary s)]
591 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
592 not (ms_mod_name s `elem` all_home_mods)]
594 ASSERT( null bad_boot_mods ) return ()
596 -- mg2_with_srcimps drops the hi-boot nodes, returning a
597 -- graph with cycles. Among other things, it is used for
598 -- backing out partially complete cycles following a failed
599 -- upsweep, and for removing from hpt all the modules
600 -- not in strict downwards closure, during calls to compile.
601 let mg2_with_srcimps :: [SCC ModSummary]
602 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
604 -- If we can determine that any of the {-# SOURCE #-} imports
605 -- are definitely unnecessary, then emit a warning.
606 warnUnnecessarySourceImports dflags mg2_with_srcimps
609 -- check the stability property for each module.
610 stable_mods@(stable_obj,stable_bco)
611 = checkStability hpt1 mg2_with_srcimps all_home_mods
613 -- prune bits of the HPT which are definitely redundant now,
615 pruned_hpt = pruneHomePackageTable hpt1
616 (flattenSCCs mg2_with_srcimps)
621 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
622 text "Stable BCO:" <+> ppr stable_bco)
624 -- Unload any modules which are going to be re-linked this time around.
625 let stable_linkables = [ linkable
626 | m <- stable_obj++stable_bco,
627 Just hmi <- [lookupUFM pruned_hpt m],
628 Just linkable <- [hm_linkable hmi] ]
629 unload hsc_env stable_linkables
631 -- We could at this point detect cycles which aren't broken by
632 -- a source-import, and complain immediately, but it seems better
633 -- to let upsweep_mods do this, so at least some useful work gets
634 -- done before the upsweep is abandoned.
635 --hPutStrLn stderr "after tsort:\n"
636 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
638 -- Now do the upsweep, calling compile for each module in
639 -- turn. Final result is version 3 of everything.
641 -- Topologically sort the module graph, this time including hi-boot
642 -- nodes, and possibly just including the portion of the graph
643 -- reachable from the module specified in the 2nd argument to load.
644 -- This graph should be cycle-free.
645 -- If we're restricting the upsweep to a portion of the graph, we
646 -- also want to retain everything that is still stable.
647 let full_mg :: [SCC ModSummary]
648 full_mg = topSortModuleGraph False mod_graph Nothing
650 maybe_top_mod = case how_much of
652 LoadDependenciesOf m -> Just m
655 partial_mg0 :: [SCC ModSummary]
656 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
658 -- LoadDependenciesOf m: we want the upsweep to stop just
659 -- short of the specified module (unless the specified module
662 | LoadDependenciesOf mod <- how_much
663 = ASSERT( case last partial_mg0 of
664 AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
665 List.init partial_mg0
671 | AcyclicSCC ms <- full_mg,
672 ms_mod_name ms `elem` stable_obj++stable_bco,
673 ms_mod_name ms `notElem` [ ms_mod_name ms' |
674 AcyclicSCC ms' <- partial_mg ] ]
676 mg = stable_mg ++ partial_mg
678 -- clean up between compilations
679 let cleanup = cleanTempFilesExcept dflags
680 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
682 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
684 (upsweep_ok, hsc_env1, modsUpswept)
685 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
686 pruned_hpt stable_mods cleanup mg
688 -- Make modsDone be the summaries for each home module now
689 -- available; this should equal the domain of hpt3.
690 -- Get in in a roughly top .. bottom order (hence reverse).
692 let modsDone = reverse modsUpswept
694 -- Try and do linking in some form, depending on whether the
695 -- upsweep was completely or only partially successful.
697 if succeeded upsweep_ok
700 -- Easy; just relink it all.
701 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
703 -- Clean up after ourselves
704 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
706 -- Issue a warning for the confusing case where the user
707 -- said '-o foo' but we're not going to do any linking.
708 -- We attempt linking if either (a) one of the modules is
709 -- called Main, or (b) the user said -no-hs-main, indicating
710 -- that main() is going to come from somewhere else.
712 let ofile = outputFile dflags
713 let no_hs_main = dopt Opt_NoHsMain dflags
715 main_mod = mainModIs dflags
716 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
717 do_linking = a_root_is_Main || no_hs_main
719 when (ghcLink dflags == LinkBinary
720 && isJust ofile && not do_linking) $
721 debugTraceMsg dflags 1 $
722 text ("Warning: output was redirected with -o, " ++
723 "but no output will be generated\n" ++
724 "because there is no " ++
725 moduleNameString (moduleName main_mod) ++ " module.")
727 -- link everything together
728 linkresult <- link (ghcLink dflags) 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 (ghcLink dflags) 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 ghcLink (hsc_dflags hsc_env) of
873 LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
875 LinkInMemory -> panic "unload: no interpreter"
879 -- -----------------------------------------------------------------------------
883 Stability tells us which modules definitely do not need to be recompiled.
884 There are two main reasons for having stability:
886 - avoid doing a complete upsweep of the module graph in GHCi when
887 modules near the bottom of the tree have not changed.
889 - to tell GHCi when it can load object code: we can only load object code
890 for a module when we also load object code fo all of the imports of the
891 module. So we need to know that we will definitely not be recompiling
892 any of these modules, and we can use the object code.
894 The stability check is as follows. Both stableObject and
895 stableBCO are used during the upsweep phase later.
898 stable m = stableObject m || stableBCO m
901 all stableObject (imports m)
902 && old linkable does not exist, or is == on-disk .o
903 && date(on-disk .o) > date(.hs)
906 all stable (imports m)
907 && date(BCO) > date(.hs)
910 These properties embody the following ideas:
912 - if a module is stable, then:
913 - if it has been compiled in a previous pass (present in HPT)
914 then it does not need to be compiled or re-linked.
915 - if it has not been compiled in a previous pass,
916 then we only need to read its .hi file from disk and
917 link it to produce a ModDetails.
919 - if a modules is not stable, we will definitely be at least
920 re-linking, and possibly re-compiling it during the upsweep.
921 All non-stable modules can (and should) therefore be unlinked
924 - Note that objects are only considered stable if they only depend
925 on other objects. We can't link object code against byte code.
929 :: HomePackageTable -- HPT from last compilation
930 -> [SCC ModSummary] -- current module graph (cyclic)
931 -> [ModuleName] -- all home modules
932 -> ([ModuleName], -- stableObject
933 [ModuleName]) -- stableBCO
935 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
937 checkSCC (stable_obj, stable_bco) scc0
938 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
939 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
940 | otherwise = (stable_obj, stable_bco)
942 scc = flattenSCC scc0
943 scc_mods = map ms_mod_name scc
944 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
946 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
947 -- all imports outside the current SCC, but in the home pkg
949 stable_obj_imps = map (`elem` stable_obj) scc_allimps
950 stable_bco_imps = map (`elem` stable_bco) scc_allimps
957 and (zipWith (||) stable_obj_imps stable_bco_imps)
961 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
965 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
966 Just hmi | Just l <- hm_linkable hmi
967 -> isObjectLinkable l && t == linkableTime l
969 -- why '>=' rather than '>' above? If the filesystem stores
970 -- times to the nearset second, we may occasionally find that
971 -- the object & source have the same modification time,
972 -- especially if the source was automatically generated
973 -- and compiled. Using >= is slightly unsafe, but it matches
977 = case lookupUFM hpt (ms_mod_name ms) of
978 Just hmi | Just l <- hm_linkable hmi ->
979 not (isObjectLinkable l) &&
980 linkableTime l >= ms_hs_date ms
983 ms_allimps :: ModSummary -> [ModuleName]
984 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
986 -- -----------------------------------------------------------------------------
987 -- Prune the HomePackageTable
989 -- Before doing an upsweep, we can throw away:
991 -- - For non-stable modules:
992 -- - all ModDetails, all linked code
993 -- - all unlinked code that is out of date with respect to
996 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
997 -- space at the end of the upsweep, because the topmost ModDetails of the
998 -- old HPT holds on to the entire type environment from the previous
1001 pruneHomePackageTable
1004 -> ([ModuleName],[ModuleName])
1007 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1010 | is_stable modl = hmi'
1011 | otherwise = hmi'{ hm_details = emptyModDetails }
1013 modl = moduleName (mi_module (hm_iface hmi))
1014 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1015 = hmi{ hm_linkable = Nothing }
1018 where ms = expectJust "prune" (lookupUFM ms_map modl)
1020 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1022 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1024 -- -----------------------------------------------------------------------------
1026 -- Return (names of) all those in modsDone who are part of a cycle
1027 -- as defined by theGraph.
1028 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1029 findPartiallyCompletedCycles modsDone theGraph
1033 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
1034 chew ((CyclicSCC vs):rest)
1035 = let names_in_this_cycle = nub (map ms_mod vs)
1037 = nub ([done | done <- modsDone,
1038 done `elem` names_in_this_cycle])
1039 chewed_rest = chew rest
1041 if notNull mods_in_this_cycle
1042 && length mods_in_this_cycle < length names_in_this_cycle
1043 then mods_in_this_cycle ++ chewed_rest
1046 -- -----------------------------------------------------------------------------
1049 -- This is where we compile each module in the module graph, in a pass
1050 -- from the bottom to the top of the graph.
1052 -- There better had not be any cyclic groups here -- we check for them.
1055 :: HscEnv -- Includes initially-empty HPT
1056 -> HomePackageTable -- HPT from last time round (pruned)
1057 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1058 -> IO () -- How to clean up unwanted tmp files
1059 -> [SCC ModSummary] -- Mods to do (the worklist)
1061 HscEnv, -- With an updated HPT
1062 [ModSummary]) -- Mods which succeeded
1064 upsweep hsc_env old_hpt stable_mods cleanup mods
1065 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1067 upsweep' hsc_env old_hpt stable_mods cleanup
1069 = return (Succeeded, hsc_env, [])
1071 upsweep' hsc_env old_hpt stable_mods cleanup
1072 (CyclicSCC ms:_) _ _
1073 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1074 return (Failed, hsc_env, [])
1076 upsweep' hsc_env old_hpt stable_mods cleanup
1077 (AcyclicSCC mod:mods) mod_index nmods
1078 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1079 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1080 -- (moduleEnvElts (hsc_HPT hsc_env)))
1082 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1085 cleanup -- Remove unwanted tmp files between compilations
1088 Nothing -> return (Failed, hsc_env, [])
1090 { let this_mod = ms_mod_name mod
1092 -- Add new info to hsc_env
1093 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1094 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1096 -- Space-saving: delete the old HPT entry
1097 -- for mod BUT if mod is a hs-boot
1098 -- node, don't delete it. For the
1099 -- interface, the HPT entry is probaby for the
1100 -- main Haskell source file. Deleting it
1101 -- would force .. (what?? --SDM)
1102 old_hpt1 | isBootSummary mod = old_hpt
1103 | otherwise = delFromUFM old_hpt this_mod
1105 ; (restOK, hsc_env2, modOKs)
1106 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1107 mods (mod_index+1) nmods
1108 ; return (restOK, hsc_env2, mod:modOKs)
1112 -- Compile a single module. Always produce a Linkable for it if
1113 -- successful. If no compilation happened, return the old Linkable.
1114 upsweep_mod :: HscEnv
1116 -> ([ModuleName],[ModuleName])
1118 -> Int -- index of module
1119 -> Int -- total number of modules
1120 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1122 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1124 this_mod_name = ms_mod_name summary
1125 this_mod = ms_mod summary
1126 mb_obj_date = ms_obj_date summary
1127 obj_fn = ml_obj_file (ms_location summary)
1128 hs_date = ms_hs_date summary
1130 is_stable_obj = this_mod_name `elem` stable_obj
1131 is_stable_bco = this_mod_name `elem` stable_bco
1133 old_hmi = lookupUFM old_hpt this_mod_name
1135 -- We're using the dflags for this module now, obtained by
1136 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1137 dflags = ms_hspp_opts summary
1138 prevailing_target = hscTarget (hsc_dflags hsc_env)
1139 local_target = hscTarget dflags
1141 -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1142 -- we don't do anything dodgy: these should only work to change
1143 -- from -fvia-C to -fasm and vice-versa, otherwise we could
1144 -- end up trying to link object code to byte code.
1145 target = if prevailing_target /= local_target
1146 && (not (isObjectTarget prevailing_target)
1147 || not (isObjectTarget local_target))
1148 then prevailing_target
1151 -- store the corrected hscTarget into the summary
1152 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1154 -- The old interface is ok if
1155 -- a) we're compiling a source file, and the old HPT
1156 -- entry is for a source file
1157 -- b) we're compiling a hs-boot file
1158 -- Case (b) allows an hs-boot file to get the interface of its
1159 -- real source file on the second iteration of the compilation
1160 -- manager, but that does no harm. Otherwise the hs-boot file
1161 -- will always be recompiled
1166 Just hm_info | isBootSummary summary -> Just iface
1167 | not (mi_boot iface) -> Just iface
1168 | otherwise -> Nothing
1170 iface = hm_iface hm_info
1172 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1173 compile_it = upsweep_compile hsc_env old_hpt this_mod_name
1174 summary' mod_index nmods mb_old_iface
1176 compile_it_discard_iface
1177 = upsweep_compile hsc_env old_hpt this_mod_name
1178 summary' mod_index nmods Nothing
1184 -- Regardless of whether we're generating object code or
1185 -- byte code, we can always use an existing object file
1186 -- if it is *stable* (see checkStability).
1187 | is_stable_obj, isJust old_hmi ->
1189 -- object is stable, and we have an entry in the
1190 -- old HPT: nothing to do
1192 | is_stable_obj, isNothing old_hmi -> do
1193 linkable <- findObjectLinkable this_mod obj_fn
1194 (expectJust "upseep1" mb_obj_date)
1195 compile_it (Just linkable)
1196 -- object is stable, but we need to load the interface
1197 -- off disk to make a HMI.
1201 ASSERT(isJust old_hmi) -- must be in the old_hpt
1203 -- BCO is stable: nothing to do
1205 | Just hmi <- old_hmi,
1206 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1207 linkableTime l >= ms_hs_date summary ->
1209 -- we have an old BCO that is up to date with respect
1210 -- to the source: do a recompilation check as normal.
1214 -- no existing code at all: we must recompile.
1216 -- When generating object code, if there's an up-to-date
1217 -- object file on the disk, then we can use it.
1218 -- However, if the object file is new (compared to any
1219 -- linkable we had from a previous compilation), then we
1220 -- must discard any in-memory interface, because this
1221 -- means the user has compiled the source file
1222 -- separately and generated a new interface, that we must
1223 -- read from the disk.
1225 obj | isObjectTarget obj,
1226 Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1229 | Just l <- hm_linkable hmi,
1230 isObjectLinkable l && linkableTime l == obj_date
1231 -> compile_it (Just l)
1233 linkable <- findObjectLinkable this_mod obj_fn obj_date
1234 compile_it_discard_iface (Just linkable)
1240 -- Run hsc to compile a module
1241 upsweep_compile hsc_env old_hpt this_mod summary
1246 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1250 -- Compilation failed. Compile may still have updated the PCS, tho.
1251 CompErrs -> return Nothing
1253 -- Compilation "succeeded", and may or may not have returned a new
1254 -- linkable (depending on whether compilation was actually performed
1256 CompOK new_details new_iface new_linkable
1257 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1258 hm_details = new_details,
1259 hm_linkable = new_linkable }
1260 return (Just new_info)
1263 -- Filter modules in the HPT
1264 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1265 retainInTopLevelEnvs keep_these hpt
1266 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1268 , let mb_mod_info = lookupUFM hpt mod
1269 , isJust mb_mod_info ]
1271 -- ---------------------------------------------------------------------------
1272 -- Topological sort of the module graph
1275 :: Bool -- Drop hi-boot nodes? (see below)
1279 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1280 -- The resulting list of strongly-connected-components is in topologically
1281 -- sorted order, starting with the module(s) at the bottom of the
1282 -- dependency graph (ie compile them first) and ending with the ones at
1285 -- Drop hi-boot nodes (first boolean arg)?
1287 -- False: treat the hi-boot summaries as nodes of the graph,
1288 -- so the graph must be acyclic
1290 -- True: eliminate the hi-boot nodes, and instead pretend
1291 -- the a source-import of Foo is an import of Foo
1292 -- The resulting graph has no hi-boot nodes, but can by cyclic
1294 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1295 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1296 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1297 = stronglyConnComp (map vertex_fn (reachable graph root))
1299 -- restrict the graph to just those modules reachable from
1300 -- the specified module. We do this by building a graph with
1301 -- the full set of nodes, and determining the reachable set from
1302 -- the specified node.
1303 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1304 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1306 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1307 | otherwise = throwDyn (ProgramError "module does not exist")
1309 moduleGraphNodes :: Bool -> [ModSummary]
1310 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1311 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1313 -- Drop hs-boot nodes by using HsSrcFile as the key
1314 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1315 | otherwise = HsBootFile
1317 -- We use integers as the keys for the SCC algorithm
1318 nodes :: [(ModSummary, Int, [Int])]
1319 nodes = [(s, expectJust "topSort" $
1320 lookup_key (ms_hsc_src s) (ms_mod_name s),
1321 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1322 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1323 (-- see [boot-edges] below
1324 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1326 else case lookup_key HsBootFile (ms_mod_name s) of
1331 , not (isBootSummary s && drop_hs_boot_nodes) ]
1332 -- Drop the hi-boot ones if told to do so
1334 -- [boot-edges] if this is a .hs and there is an equivalent
1335 -- .hs-boot, add a link from the former to the latter. This
1336 -- has the effect of detecting bogus cases where the .hs-boot
1337 -- depends on the .hs, by introducing a cycle. Additionally,
1338 -- it ensures that we will always process the .hs-boot before
1339 -- the .hs, and so the HomePackageTable will always have the
1340 -- most up to date information.
1342 key_map :: NodeMap Int
1343 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1347 lookup_key :: HscSource -> ModuleName -> Maybe Int
1348 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1350 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1351 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1352 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1353 -- the IsBootInterface parameter True; else False
1356 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1357 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1359 msKey :: ModSummary -> NodeKey
1360 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1362 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1363 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1365 nodeMapElts :: NodeMap a -> [a]
1366 nodeMapElts = eltsFM
1368 ms_mod_name :: ModSummary -> ModuleName
1369 ms_mod_name = moduleName . ms_mod
1371 -- If there are {-# SOURCE #-} imports between strongly connected
1372 -- components in the topological sort, then those imports can
1373 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1374 -- were necessary, then the edge would be part of a cycle.
1375 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1376 warnUnnecessarySourceImports dflags sccs =
1377 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1379 let mods_in_this_cycle = map ms_mod_name ms in
1380 [ warn m i | m <- ms, i <- ms_srcimps m,
1381 unLoc i `notElem` mods_in_this_cycle ]
1383 warn :: ModSummary -> Located ModuleName -> WarnMsg
1384 warn ms (L loc mod) =
1386 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1387 <+> quotes (ppr mod))
1389 -----------------------------------------------------------------------------
1390 -- Downsweep (dependency analysis)
1392 -- Chase downwards from the specified root set, returning summaries
1393 -- for all home modules encountered. Only follow source-import
1396 -- We pass in the previous collection of summaries, which is used as a
1397 -- cache to avoid recalculating a module summary if the source is
1400 -- The returned list of [ModSummary] nodes has one node for each home-package
1401 -- module, plus one for any hs-boot files. The imports of these nodes
1402 -- are all there, including the imports of non-home-package modules.
1405 -> [ModSummary] -- Old summaries
1406 -> [ModuleName] -- Ignore dependencies on these; treat
1407 -- them as if they were package modules
1408 -> Bool -- True <=> allow multiple targets to have
1409 -- the same module name; this is
1410 -- very useful for ghc -M
1411 -> IO (Maybe [ModSummary])
1412 -- The elts of [ModSummary] all have distinct
1413 -- (Modules, IsBoot) identifiers, unless the Bool is true
1414 -- in which case there can be repeats
1415 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1416 = -- catch error messages and return them
1417 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1418 rootSummaries <- mapM getRootSummary roots
1419 let root_map = mkRootMap rootSummaries
1420 checkDuplicates root_map
1421 summs <- loop (concatMap msDeps rootSummaries) root_map
1424 roots = hsc_targets hsc_env
1426 old_summary_map :: NodeMap ModSummary
1427 old_summary_map = mkNodeMap old_summaries
1429 getRootSummary :: Target -> IO ModSummary
1430 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1431 = do exists <- doesFileExist file
1433 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1434 else throwDyn $ mkPlainErrMsg noSrcSpan $
1435 text "can't find file:" <+> text file
1436 getRootSummary (Target (TargetModule modl) maybe_buf)
1437 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1438 (L rootLoc modl) maybe_buf excl_mods
1439 case maybe_summary of
1440 Nothing -> packageModErr modl
1443 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1445 -- In a root module, the filename is allowed to diverge from the module
1446 -- name, so we have to check that there aren't multiple root files
1447 -- defining the same module (otherwise the duplicates will be silently
1448 -- ignored, leading to confusing behaviour).
1449 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1450 checkDuplicates root_map
1451 | allow_dup_roots = return ()
1452 | null dup_roots = return ()
1453 | otherwise = multiRootsErr (head dup_roots)
1455 dup_roots :: [[ModSummary]] -- Each at least of length 2
1456 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1458 loop :: [(Located ModuleName,IsBootInterface)]
1459 -- Work list: process these modules
1460 -> NodeMap [ModSummary]
1461 -- Visited set; the range is a list because
1462 -- the roots can have the same module names
1463 -- if allow_dup_roots is True
1465 -- The result includes the worklist, except
1466 -- for those mentioned in the visited set
1467 loop [] done = return (concat (nodeMapElts done))
1468 loop ((wanted_mod, is_boot) : ss) done
1469 | Just summs <- lookupFM done key
1470 = if isSingleton summs then
1473 do { multiRootsErr summs; return [] }
1474 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1475 is_boot wanted_mod Nothing excl_mods
1477 Nothing -> loop ss done
1478 Just s -> loop (msDeps s ++ ss)
1479 (addToFM done key [s]) }
1481 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1483 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1484 mkRootMap summaries = addListToFM_C (++) emptyFM
1485 [ (msKey s, [s]) | s <- summaries ]
1487 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1488 -- (msDeps s) returns the dependencies of the ModSummary s.
1489 -- A wrinkle is that for a {-# SOURCE #-} import we return
1490 -- *both* the hs-boot file
1491 -- *and* the source file
1492 -- as "dependencies". That ensures that the list of all relevant
1493 -- modules always contains B.hs if it contains B.hs-boot.
1494 -- Remember, this pass isn't doing the topological sort. It's
1495 -- just gathering the list of all relevant ModSummaries
1497 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1498 ++ [ (m,False) | m <- ms_imps s ]
1500 -----------------------------------------------------------------------------
1501 -- Summarising modules
1503 -- We have two types of summarisation:
1505 -- * Summarise a file. This is used for the root module(s) passed to
1506 -- cmLoadModules. The file is read, and used to determine the root
1507 -- module name. The module name may differ from the filename.
1509 -- * Summarise a module. We are given a module name, and must provide
1510 -- a summary. The finder is used to locate the file in which the module
1515 -> [ModSummary] -- old summaries
1516 -> FilePath -- source file name
1517 -> Maybe Phase -- start phase
1518 -> Maybe (StringBuffer,ClockTime)
1521 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1522 -- we can use a cached summary if one is available and the
1523 -- source file hasn't changed, But we have to look up the summary
1524 -- by source file, rather than module name as we do in summarise.
1525 | Just old_summary <- findSummaryBySourceFile old_summaries file
1527 let location = ms_location old_summary
1529 -- return the cached summary if the source didn't change
1530 src_timestamp <- case maybe_buf of
1531 Just (_,t) -> return t
1532 Nothing -> getModificationTime file
1533 -- The file exists; we checked in getRootSummary above.
1534 -- If it gets removed subsequently, then this
1535 -- getModificationTime may fail, but that's the right
1538 if ms_hs_date old_summary == src_timestamp
1539 then do -- update the object-file timestamp
1540 obj_timestamp <- getObjTimestamp location False
1541 return old_summary{ ms_obj_date = obj_timestamp }
1549 let dflags = hsc_dflags hsc_env
1551 (dflags', hspp_fn, buf)
1552 <- preprocessFile dflags file mb_phase maybe_buf
1554 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1556 -- Make a ModLocation for this file
1557 location <- mkHomeModLocation dflags mod_name file
1559 -- Tell the Finder cache where it is, so that subsequent calls
1560 -- to findModule will find it, even if it's not on any search path
1561 mod <- addHomeModuleToFinder hsc_env mod_name location
1563 src_timestamp <- case maybe_buf of
1564 Just (_,t) -> return t
1565 Nothing -> getModificationTime file
1566 -- getMofificationTime may fail
1568 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1570 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1571 ms_location = location,
1572 ms_hspp_file = hspp_fn,
1573 ms_hspp_opts = dflags',
1574 ms_hspp_buf = Just buf,
1575 ms_srcimps = srcimps, ms_imps = the_imps,
1576 ms_hs_date = src_timestamp,
1577 ms_obj_date = obj_timestamp })
1579 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1580 findSummaryBySourceFile summaries file
1581 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1582 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1586 -- Summarise a module, and pick up source and timestamp.
1589 -> NodeMap ModSummary -- Map of old summaries
1590 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1591 -> Located ModuleName -- Imported module to be summarised
1592 -> Maybe (StringBuffer, ClockTime)
1593 -> [ModuleName] -- Modules to exclude
1594 -> IO (Maybe ModSummary) -- Its new summary
1596 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1597 | wanted_mod `elem` excl_mods
1600 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1601 = do -- Find its new timestamp; all the
1602 -- ModSummaries in the old map have valid ml_hs_files
1603 let location = ms_location old_summary
1604 src_fn = expectJust "summariseModule" (ml_hs_file location)
1606 -- check the modification time on the source file, and
1607 -- return the cached summary if it hasn't changed. If the
1608 -- file has disappeared, we need to call the Finder again.
1610 Just (_,t) -> check_timestamp old_summary location src_fn t
1612 m <- System.IO.Error.try (getModificationTime src_fn)
1614 Right t -> check_timestamp old_summary location src_fn t
1615 Left e | isDoesNotExistError e -> find_it
1616 | otherwise -> ioError e
1618 | otherwise = find_it
1620 dflags = hsc_dflags hsc_env
1622 hsc_src = if is_boot then HsBootFile else HsSrcFile
1624 check_timestamp old_summary location src_fn src_timestamp
1625 | ms_hs_date old_summary == src_timestamp = do
1626 -- update the object-file timestamp
1627 obj_timestamp <- getObjTimestamp location is_boot
1628 return (Just old_summary{ ms_obj_date = obj_timestamp })
1630 -- source changed: re-summarise.
1631 new_summary location (ms_mod old_summary) src_fn src_timestamp
1634 -- Don't use the Finder's cache this time. If the module was
1635 -- previously a package module, it may have now appeared on the
1636 -- search path, so we want to consider it to be a home module. If
1637 -- the module was previously a home module, it may have moved.
1638 uncacheModule hsc_env wanted_mod
1639 found <- findImportedModule hsc_env wanted_mod Nothing
1642 | isJust (ml_hs_file location) ->
1644 just_found location mod
1646 -- Drop external-pkg
1647 ASSERT(modulePackageId mod /= thisPackage dflags)
1651 err -> noModError dflags loc wanted_mod err
1654 just_found location mod = do
1655 -- Adjust location to point to the hs-boot source file,
1656 -- hi file, object file, when is_boot says so
1657 let location' | is_boot = addBootSuffixLocn location
1658 | otherwise = location
1659 src_fn = expectJust "summarise2" (ml_hs_file location')
1661 -- Check that it exists
1662 -- It might have been deleted since the Finder last found it
1663 maybe_t <- modificationTimeIfExists src_fn
1665 Nothing -> noHsFileErr loc src_fn
1666 Just t -> new_summary location' mod src_fn t
1669 new_summary location mod src_fn src_timestamp
1671 -- Preprocess the source file and get its imports
1672 -- The dflags' contains the OPTIONS pragmas
1673 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1674 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1676 when (mod_name /= wanted_mod) $
1677 throwDyn $ mkPlainErrMsg mod_loc $
1678 text "file name does not match module name"
1679 <+> quotes (ppr mod_name)
1681 -- Find the object timestamp, and return the summary
1682 obj_timestamp <- getObjTimestamp location is_boot
1684 return (Just ( ModSummary { ms_mod = mod,
1685 ms_hsc_src = hsc_src,
1686 ms_location = location,
1687 ms_hspp_file = hspp_fn,
1688 ms_hspp_opts = dflags',
1689 ms_hspp_buf = Just buf,
1690 ms_srcimps = srcimps,
1692 ms_hs_date = src_timestamp,
1693 ms_obj_date = obj_timestamp }))
1696 getObjTimestamp location is_boot
1697 = if is_boot then return Nothing
1698 else modificationTimeIfExists (ml_obj_file location)
1701 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1702 -> IO (DynFlags, FilePath, StringBuffer)
1703 preprocessFile dflags src_fn mb_phase Nothing
1705 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1706 buf <- hGetStringBuffer hspp_fn
1707 return (dflags', hspp_fn, buf)
1709 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1711 -- case we bypass the preprocessing stage?
1713 local_opts = getOptions buf src_fn
1715 (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1719 | Just (Unlit _) <- mb_phase = True
1720 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1721 -- note: local_opts is only required if there's no Unlit phase
1722 | dopt Opt_Cpp dflags' = True
1723 | dopt Opt_Pp dflags' = True
1726 when needs_preprocessing $
1727 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1729 return (dflags', src_fn, buf)
1732 -----------------------------------------------------------------------------
1734 -----------------------------------------------------------------------------
1736 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1737 -- ToDo: we don't have a proper line number for this error
1738 noModError dflags loc wanted_mod err
1739 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1741 noHsFileErr loc path
1742 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1745 = throwDyn $ mkPlainErrMsg noSrcSpan $
1746 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1748 multiRootsErr :: [ModSummary] -> IO ()
1749 multiRootsErr summs@(summ1:_)
1750 = throwDyn $ mkPlainErrMsg noSrcSpan $
1751 text "module" <+> quotes (ppr mod) <+>
1752 text "is defined in multiple files:" <+>
1753 sep (map text files)
1756 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1758 cyclicModuleErr :: [ModSummary] -> SDoc
1760 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1761 2 (vcat (map show_one ms))
1763 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1764 nest 2 $ ptext SLIT("imports:") <+>
1765 (pp_imps HsBootFile (ms_srcimps ms)
1766 $$ pp_imps HsSrcFile (ms_imps ms))]
1767 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1768 pp_imps src mods = fsep (map (show_mod src) mods)
1771 -- | Inform GHC that the working directory has changed. GHC will flush
1772 -- its cache of module locations, since it may no longer be valid.
1773 -- Note: if you change the working directory, you should also unload
1774 -- the current program (set targets to empty, followed by load).
1775 workingDirectoryChanged :: Session -> IO ()
1776 workingDirectoryChanged s = withSession s $ flushFinderCaches
1778 -- -----------------------------------------------------------------------------
1779 -- inspecting the session
1781 -- | Get the module dependency graph.
1782 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1783 getModuleGraph s = withSession s (return . hsc_mod_graph)
1785 isLoaded :: Session -> ModuleName -> IO Bool
1786 isLoaded s m = withSession s $ \hsc_env ->
1787 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1789 getBindings :: Session -> IO [TyThing]
1790 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1792 getPrintUnqual :: Session -> IO PrintUnqualified
1793 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1795 -- | Container for information about a 'Module'.
1796 data ModuleInfo = ModuleInfo {
1797 minf_type_env :: TypeEnv,
1798 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1799 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1800 minf_instances :: [Instance]
1802 ,minf_dbg_sites :: [(SiteNumber,Coord)]
1804 -- ToDo: this should really contain the ModIface too
1806 -- We don't want HomeModInfo here, because a ModuleInfo applies
1807 -- to package modules too.
1809 -- | Request information about a loaded 'Module'
1810 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1811 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1812 let mg = hsc_mod_graph hsc_env
1813 if mdl `elem` map ms_mod mg
1814 then getHomeModuleInfo hsc_env (moduleName mdl)
1816 {- if isHomeModule (hsc_dflags hsc_env) mdl
1818 else -} getPackageModuleInfo hsc_env mdl
1819 -- getPackageModuleInfo will attempt to find the interface, so
1820 -- we don't want to call it for a home module, just in case there
1821 -- was a problem loading the module and the interface doesn't
1822 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1824 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1825 getPackageModuleInfo hsc_env mdl = do
1827 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1829 Nothing -> return Nothing
1831 eps <- readIORef (hsc_EPS hsc_env)
1833 names = availsToNameSet avails
1835 tys = [ ty | name <- concatMap availNames avails,
1836 Just ty <- [lookupTypeEnv pte name] ]
1838 return (Just (ModuleInfo {
1839 minf_type_env = mkTypeEnv tys,
1840 minf_exports = names,
1841 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1842 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1843 minf_dbg_sites = noDbgSites
1846 -- bogusly different for non-GHCI (ToDo)
1850 getHomeModuleInfo hsc_env mdl =
1851 case lookupUFM (hsc_HPT hsc_env) mdl of
1852 Nothing -> return Nothing
1854 let details = hm_details hmi
1855 return (Just (ModuleInfo {
1856 minf_type_env = md_types details,
1857 minf_exports = availsToNameSet (md_exports details),
1858 minf_rdr_env = mi_globals $! hm_iface hmi,
1859 minf_instances = md_insts details
1861 ,minf_dbg_sites = md_dbg_sites details
1865 -- | The list of top-level entities defined in a module
1866 modInfoTyThings :: ModuleInfo -> [TyThing]
1867 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1869 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1870 modInfoTopLevelScope minf
1871 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1873 modInfoExports :: ModuleInfo -> [Name]
1874 modInfoExports minf = nameSetToList $! minf_exports minf
1876 -- | Returns the instances defined by the specified module.
1877 -- Warning: currently unimplemented for package modules.
1878 modInfoInstances :: ModuleInfo -> [Instance]
1879 modInfoInstances = minf_instances
1881 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1882 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1884 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1885 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1887 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1888 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1889 case lookupTypeEnv (minf_type_env minf) name of
1890 Just tyThing -> return (Just tyThing)
1892 eps <- readIORef (hsc_EPS hsc_env)
1893 return $! lookupType (hsc_dflags hsc_env)
1894 (hsc_HPT hsc_env) (eps_PTE eps) name
1897 modInfoBkptSites = minf_dbg_sites
1900 isDictonaryId :: Id -> Bool
1902 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1904 -- | Looks up a global name: that is, any top-level name in any
1905 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1906 -- the interactive context, and therefore does not require a preceding
1908 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1909 lookupGlobalName s name = withSession s $ \hsc_env -> do
1910 eps <- readIORef (hsc_EPS hsc_env)
1911 return $! lookupType (hsc_dflags hsc_env)
1912 (hsc_HPT hsc_env) (eps_PTE eps) name
1914 -- -----------------------------------------------------------------------------
1915 -- Misc exported utils
1917 dataConType :: DataCon -> Type
1918 dataConType dc = idType (dataConWrapId dc)
1920 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1921 pprParenSymName :: NamedThing a => a -> SDoc
1922 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1924 -- ----------------------------------------------------------------------------
1929 -- - Data and Typeable instances for HsSyn.
1931 -- ToDo: check for small transformations that happen to the syntax in
1932 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1934 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1935 -- to get from TyCons, Ids etc. to TH syntax (reify).
1937 -- :browse will use either lm_toplev or inspect lm_interface, depending
1938 -- on whether the module is interpreted or not.
1940 -- This is for reconstructing refactored source code
1941 -- Calls the lexer repeatedly.
1942 -- ToDo: add comment tokens to token stream
1943 getTokenStream :: Session -> Module -> IO [Located Token]
1946 -- -----------------------------------------------------------------------------
1947 -- Interactive evaluation
1949 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1950 -- filesystem and package database to find the corresponding 'Module',
1951 -- using the algorithm that is used for an @import@ declaration.
1952 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1953 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1954 findModule' hsc_env mod_name maybe_pkg
1956 findModule' hsc_env mod_name maybe_pkg =
1958 dflags = hsc_dflags hsc_env
1959 hpt = hsc_HPT hsc_env
1960 this_pkg = thisPackage dflags
1962 case lookupUFM hpt mod_name of
1963 Just mod_info -> return (mi_module (hm_iface mod_info))
1964 _not_a_home_module -> do
1965 res <- findImportedModule hsc_env mod_name maybe_pkg
1967 Found _ m | modulePackageId m /= this_pkg -> return m
1968 | otherwise -> throwDyn (CmdLineError (showSDoc $
1969 text "module" <+> pprModule m <+>
1970 text "is not loaded"))
1971 err -> let msg = cannotFindModule dflags mod_name err in
1972 throwDyn (CmdLineError (showSDoc msg))
1976 -- | Set the interactive evaluation context.
1978 -- Setting the context doesn't throw away any bindings; the bindings
1979 -- we've built up in the InteractiveContext simply move to the new
1980 -- module. They always shadow anything in scope in the current context.
1981 setContext :: Session
1982 -> [Module] -- entire top level scope of these modules
1983 -> [Module] -- exports only of these modules
1985 setContext sess@(Session ref) toplev_mods export_mods = do
1986 hsc_env <- readIORef ref
1987 let old_ic = hsc_IC hsc_env
1988 hpt = hsc_HPT hsc_env
1990 export_env <- mkExportEnv hsc_env export_mods
1991 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
1992 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1993 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
1994 ic_exports = export_mods,
1995 ic_rn_gbl_env = all_env }}
1996 reinstallBreakpointHandlers sess
1998 -- Make a GlobalRdrEnv based on the exports of the modules only.
1999 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
2000 mkExportEnv hsc_env mods = do
2001 stuff <- mapM (getModuleExports hsc_env) mods
2003 (_msgs, mb_name_sets) = unzip stuff
2004 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
2005 | (Just avails, mod) <- zip mb_name_sets mods ]
2007 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
2009 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
2010 nameSetToGlobalRdrEnv names mod =
2011 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
2012 | name <- nameSetToList names ]
2014 vanillaProv :: ModuleName -> Provenance
2015 -- We're building a GlobalRdrEnv as if the user imported
2016 -- all the specified modules into the global interactive module
2017 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
2019 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
2021 is_dloc = srcLocSpan interactiveSrcLoc }
2023 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
2024 mkTopLevEnv hpt modl
2025 = case lookupUFM hpt (moduleName modl) of
2026 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
2027 showSDoc (ppr modl)))
2029 case mi_globals (hm_iface details) of
2031 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
2032 ++ showSDoc (ppr modl)))
2033 Just env -> return env
2035 -- | Get the interactive evaluation context, consisting of a pair of the
2036 -- set of modules from which we take the full top-level scope, and the set
2037 -- of modules from which we take just the exports respectively.
2038 getContext :: Session -> IO ([Module],[Module])
2039 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
2040 return (ic_toplev_scope ic, ic_exports ic))
2042 -- | Returns 'True' if the specified module is interpreted, and hence has
2043 -- its full top-level scope available.
2044 moduleIsInterpreted :: Session -> Module -> IO Bool
2045 moduleIsInterpreted s modl = withSession s $ \h ->
2046 if modulePackageId modl /= thisPackage (hsc_dflags h)
2048 else case lookupUFM (hsc_HPT h) (moduleName modl) of
2049 Just details -> return (isJust (mi_globals (hm_iface details)))
2050 _not_a_home_module -> return False
2052 -- | Looks up an identifier in the current interactive context (for :info)
2053 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
2054 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
2056 -- | Returns all names in scope in the current interactive context
2057 getNamesInScope :: Session -> IO [Name]
2058 getNamesInScope s = withSession s $ \hsc_env -> do
2059 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
2061 getRdrNamesInScope :: Session -> IO [RdrName]
2062 getRdrNamesInScope s = withSession s $ \hsc_env -> do
2063 let env = ic_rn_gbl_env (hsc_IC hsc_env)
2064 return (concat (map greToRdrNames (globalRdrEnvElts env)))
2066 -- ToDo: move to RdrName
2067 greToRdrNames :: GlobalRdrElt -> [RdrName]
2068 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
2070 LocalDef -> [unqual]
2071 Imported specs -> concat (map do_spec (map is_decl specs))
2073 occ = nameOccName name
2076 | is_qual decl_spec = [qual]
2077 | otherwise = [unqual,qual]
2078 where qual = Qual (is_as decl_spec) occ
2080 -- | Parses a string as an identifier, and returns the list of 'Name's that
2081 -- the identifier can refer to in the current interactive context.
2082 parseName :: Session -> String -> IO [Name]
2083 parseName s str = withSession s $ \hsc_env -> do
2084 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
2085 case maybe_rdr_name of
2086 Nothing -> return []
2087 Just (L _ rdr_name) -> do
2088 mb_names <- tcRnLookupRdrName hsc_env rdr_name
2090 Nothing -> return []
2091 Just ns -> return ns
2092 -- ToDo: should return error messages
2094 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
2095 -- entity known to GHC, including 'Name's defined using 'runStmt'.
2096 lookupName :: Session -> Name -> IO (Maybe TyThing)
2097 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
2099 -- -----------------------------------------------------------------------------
2100 -- Getting the type of an expression
2102 -- | Get the type of an expression
2103 exprType :: Session -> String -> IO (Maybe Type)
2104 exprType s expr = withSession s $ \hsc_env -> do
2105 maybe_stuff <- hscTcExpr hsc_env expr
2107 Nothing -> return Nothing
2108 Just ty -> return (Just tidy_ty)
2110 tidy_ty = tidyType emptyTidyEnv ty
2112 -- -----------------------------------------------------------------------------
2113 -- Getting the kind of a type
2115 -- | Get the kind of a type
2116 typeKind :: Session -> String -> IO (Maybe Kind)
2117 typeKind s str = withSession s $ \hsc_env -> do
2118 maybe_stuff <- hscKcType hsc_env str
2120 Nothing -> return Nothing
2121 Just kind -> return (Just kind)
2123 -----------------------------------------------------------------------------
2124 -- cmCompileExpr: compile an expression and deliver an HValue
2126 compileExpr :: Session -> String -> IO (Maybe HValue)
2127 compileExpr s expr = withSession s $ \hsc_env -> do
2128 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
2130 Nothing -> return Nothing
2131 Just (new_ic, names, hval) -> do
2133 hvals <- (unsafeCoerce# hval) :: IO [HValue]
2135 case (names,hvals) of
2136 ([n],[hv]) -> return (Just hv)
2137 _ -> panic "compileExpr"
2139 -- -----------------------------------------------------------------------------
2140 -- Compile an expression into a dynamic
2142 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
2143 dynCompileExpr ses expr = do
2144 (full,exports) <- getContext ses
2145 setContext ses full $
2147 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
2149 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
2150 res <- withSession ses (flip hscStmt stmt)
2151 setContext ses full exports
2153 Nothing -> return Nothing
2154 Just (_, names, hvals) -> do
2155 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
2156 case (names,vals) of
2157 (_:[], v:[]) -> return (Just v)
2158 _ -> panic "dynCompileExpr"
2160 -- -----------------------------------------------------------------------------
2161 -- running a statement interactively
2164 = RunOk [Name] -- ^ names bound by this evaluation
2165 | RunFailed -- ^ statement failed compilation
2166 | RunException Exception -- ^ statement raised an exception
2168 -- | Run a statement in the current interactive context. Statemenet
2169 -- may bind multple values.
2170 runStmt :: Session -> String -> IO RunResult
2171 runStmt (Session ref) expr
2173 hsc_env <- readIORef ref
2175 -- Turn off -fwarn-unused-bindings when running a statement, to hide
2176 -- warnings about the implicit bindings we introduce.
2177 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
2178 hsc_env' = hsc_env{ hsc_dflags = dflags' }
2180 maybe_stuff <- hscStmt hsc_env' expr
2183 Nothing -> return RunFailed
2184 Just (new_hsc_env, names, hval) -> do
2186 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2187 either_hvals <- sandboxIO thing_to_run
2189 case either_hvals of
2191 -- on error, keep the *old* interactive context,
2192 -- so that 'it' is not bound to something
2193 -- that doesn't exist.
2194 return (RunException e)
2197 -- Get the newly bound things, and bind them.
2198 -- Don't need to delete any shadowed bindings;
2199 -- the new ones override the old ones.
2200 extendLinkEnv (zip names hvals)
2202 writeIORef ref new_hsc_env
2203 return (RunOk names)
2205 -- When running a computation, we redirect ^C exceptions to the running
2206 -- thread. ToDo: we might want a way to continue even if the target
2207 -- thread doesn't die when it receives the exception... "this thread
2208 -- is not responding".
2209 sandboxIO :: IO a -> IO (Either Exception a)
2210 sandboxIO thing = do
2212 ts <- takeMVar interruptTargetThread
2213 child <- forkIO (do res <- Exception.try thing; putMVar m res)
2214 putMVar interruptTargetThread (child:ts)
2215 takeMVar m `finally` modifyMVar_ interruptTargetThread (return.tail)
2218 -- This version of sandboxIO runs the expression in a completely new
2219 -- RTS main thread. It is disabled for now because ^C exceptions
2220 -- won't be delivered to the new thread, instead they'll be delivered
2221 -- to the (blocked) GHCi main thread.
2223 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2225 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2226 sandboxIO thing = do
2227 st_thing <- newStablePtr (Exception.try thing)
2228 alloca $ \ p_st_result -> do
2229 stat <- rts_evalStableIO st_thing p_st_result
2230 freeStablePtr st_thing
2232 then do st_result <- peek p_st_result
2233 result <- deRefStablePtr st_result
2234 freeStablePtr st_result
2235 return (Right result)
2237 return (Left (fromIntegral stat))
2239 foreign import "rts_evalStableIO" {- safe -}
2240 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2241 -- more informative than the C type!
2243 XXX the type of rts_evalStableIO no longer matches the above
2248 -----------------------------------------------------------------------------
2249 -- show a module and it's source/object filenames
2251 showModule :: Session -> ModSummary -> IO String
2252 showModule s mod_summary = withSession s $ \hsc_env ->
2253 isModuleInterpreted s mod_summary >>= \interpreted ->
2254 return (showModMsg (hscTarget(hsc_dflags hsc_env)) interpreted mod_summary)
2256 isModuleInterpreted :: Session -> ModSummary -> IO Bool
2257 isModuleInterpreted s mod_summary = withSession s $ \hsc_env ->
2258 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
2259 Nothing -> panic "missing linkable"
2260 Just mod_info -> return (not obj_linkable)
2262 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
2264 -----------------------------------------------------------------------------
2265 -- Breakpoint handlers
2267 getBreakpointHandler :: Session -> IO (Maybe (BkptHandler Module))
2268 getBreakpointHandler session = getSessionDynFlags session >>= return . bkptHandler
2270 setBreakpointHandler :: Session -> BkptHandler Module -> IO ()
2271 setBreakpointHandler session handler = do
2272 dflags <- getSessionDynFlags session
2273 setSessionDynFlags session dflags{ bkptHandler = Just handler }
2274 let linkEnv = [ ( breakpointJumpName
2275 , unsafeCoerce# (jumpFunction session handler))
2276 , ( breakpointCondJumpName
2277 , unsafeCoerce# (jumpCondFunction session handler))
2278 , ( breakpointAutoJumpName
2279 , unsafeCoerce# (jumpAutoFunction session handler))
2281 writeIORef v_bkptLinkEnv linkEnv
2282 dflags <- getSessionDynFlags session
2283 reinstallBreakpointHandlers session
2285 reinstallBreakpointHandlers :: Session -> IO ()
2286 reinstallBreakpointHandlers session = do
2287 dflags <- getSessionDynFlags session
2288 let mode = ghcMode dflags
2289 when (ghcLink dflags == LinkInMemory) $ do
2290 linkEnv <- readIORef v_bkptLinkEnv
2291 initDynLinker dflags
2292 extendLinkEnv linkEnv
2294 -----------------------------------------------------------------------
2297 type SiteInfo = (String, SiteNumber)
2298 jumpFunction, jumpAutoFunction :: Session -> BkptHandler Module -> SiteInfo -> (Int, [Opaque], String) -> b -> b
2299 jumpCondFunction :: Session -> BkptHandler Module -> SiteInfo -> (Int, [Opaque], String) -> Bool -> b -> b
2300 jumpFunctionM :: Session -> BkptHandler a -> BkptLocation a -> (Int, [Opaque], String) -> b -> IO b
2302 jumpCondFunction _ _ _ _ False b = b
2303 jumpCondFunction session handler site args True b
2304 = jumpFunction session handler site args b
2306 jumpFunction session handler siteInfo args b
2307 | site <- mkSite siteInfo
2308 = unsafePerformIO $ jumpFunctionM session handler site args b
2310 jumpFunctionM session handler site (I# idsPtr, wrapped_hValues, locmsg) b =
2312 ids <- deRefStablePtr (castPtrToStablePtr (Ptr (int2Addr# idsPtr)))
2313 let hValues = unsafeCoerce# b : [unsafeCoerce# hv | O hv <- wrapped_hValues]
2314 handleBreakpoint handler session (zip ids hValues) site locmsg b
2316 jumpAutoFunction session handler siteInfo args b
2317 | site <- mkSite siteInfo
2318 = unsafePerformIO $ do
2319 break <- isAutoBkptEnabled handler session site
2321 then jumpFunctionM session handler site args b
2324 jumpStepByStepFunction session handler siteInfo args b
2325 | site <- mkSite siteInfo
2326 = unsafePerformIO $ do
2327 jumpFunctionM session handler site args b
2329 mkSite :: SiteInfo -> BkptLocation Module
2330 mkSite ( modName, sitenum) =
2331 (mkModule mainPackageId (mkModuleName modName), sitenum)
2333 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2334 obtainTerm1 sess force mb_ty x = withSession sess $ \hsc_env -> cvObtainTerm hsc_env force mb_ty (unsafeCoerce# x)
2336 obtainTerm :: Session -> Bool -> Id -> IO (Maybe Term)
2337 obtainTerm sess force id = withSession sess $ \hsc_env -> do
2338 mb_v <- getHValue (varName id)
2340 Just v -> fmap Just$ cvObtainTerm hsc_env force (Just$ idType id) v
2341 Nothing -> return Nothing