1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), GhcMode(..), HscTarget(..), dopt,
31 -- * Loading/compiling the program
33 load, SuccessFlag(..), -- also does depanal
34 workingDirectoryChanged,
36 -- * Inspecting the module structure of the program
37 ModuleGraph, ModSummary(..),
41 -- * Interactive evaluation
42 getBindings, getPrintUnqual,
44 setContext, getContext,
46 getInfo, GetInfoResult,
57 -- * Abstract syntax elements
58 Module, mkModule, pprModule,
61 Name, Id, TyCon, Class, DataCon,
65 -- used by DriverMkDepend:
73 * return error messages rather than printing them.
74 * inline bits of HscMain here to simplify layering: hscGetInfo,
76 * implement second argument to load.
77 * we need to expose DynFlags, so should parseDynamicFlags really be
78 part of this interface?
79 * what StaticFlags should we expose, if any?
82 #include "HsVersions.h"
85 import qualified Linker
86 import Linker ( HValue, extendLinkEnv )
87 import NameEnv ( lookupNameEnv )
88 import TcRnDriver ( mkExportEnv, getModuleContents )
89 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
90 import HscMain ( hscGetInfo, GetInfoResult,
91 hscStmt, hscTcExpr, hscKcType )
92 import Type ( tidyType )
93 import VarEnv ( emptyTidyEnv )
94 import GHC.Exts ( unsafeCoerce# )
95 import IfaceSyn ( IfaceDecl )
98 import Type ( Kind, Type, dropForAlls )
99 import Id ( Id, idType )
100 import TyCon ( TyCon )
101 import Class ( Class )
102 import DataCon ( DataCon )
104 import NameEnv ( nameEnvElts )
105 import DriverPipeline ( preprocess, compile, CompResult(..), link )
106 import DriverPhases ( isHaskellSrcFilename )
107 import GetImports ( getImports )
108 import Packages ( isHomePackage )
110 import HscMain ( newHscEnv )
114 import SysTools ( initSysTools, cleanTempFiles )
118 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
119 import ErrUtils ( showPass )
120 import qualified ErrUtils
122 import StringBuffer ( hGetStringBuffer )
124 import SysTools ( cleanTempFilesExcept )
125 import BasicTypes ( SuccessFlag(..), succeeded )
126 import Maybes ( orElse, expectJust, mapCatMaybes )
128 import Directory ( getModificationTime, doesFileExist )
129 import Maybe ( isJust, fromJust )
130 import List ( partition, nub )
131 import Monad ( unless, when, foldM )
132 import System ( exitWith, ExitCode(..) )
133 import EXCEPTION as Exception hiding (handle)
136 import Prelude hiding (init)
138 -- -----------------------------------------------------------------------------
139 -- Exception handlers
141 -- | Install some default exception handlers and run the inner computation.
142 -- Unless you want to handle exceptions yourself, you should wrap this around
143 -- the top level of your program. The default handlers output the error
144 -- message(s) to stderr and exit cleanly.
145 defaultErrorHandler :: IO a -> IO a
146 defaultErrorHandler inner =
147 -- top-level exception handler: any unrecognised exception is a compiler bug.
148 handle (\exception -> do
151 -- an IO exception probably isn't our fault, so don't panic
152 IOException _ -> hPutStrLn stderr (show exception)
153 AsyncException StackOverflow ->
154 hPutStrLn stderr "stack overflow: use +RTS -K<size> to increase it"
155 _other -> hPutStr stderr (show (Panic (show exception)))
156 exitWith (ExitFailure 1)
159 -- all error messages are propagated as exceptions
160 handleDyn (\dyn -> do
163 PhaseFailed _ code -> exitWith code
164 Interrupted -> exitWith (ExitFailure 1)
165 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
166 exitWith (ExitFailure 1)
170 -- | Install a default cleanup handler to remove temporary files
171 -- deposited by a GHC run. This is seperate from
172 -- 'defaultErrorHandler', because you might want to override the error
173 -- handling, but still get the ordinary cleanup behaviour.
174 defaultCleanupHandler :: DynFlags -> IO a -> IO a
175 defaultCleanupHandler dflags inner =
176 -- make sure we clean up after ourselves
177 later (unless (dopt Opt_KeepTmpFiles dflags) $
178 cleanTempFiles dflags)
179 -- exceptions will be blocked while we clean the temporary files,
180 -- so there shouldn't be any difficulty if we receive further
185 -- | Initialises GHC. This must be done /once/ only. Takes the
186 -- command-line arguments. All command-line arguments which aren't
187 -- understood by GHC will be returned.
189 init :: [String] -> IO [String]
192 installSignalHandlers
194 -- Grab the -B option if there is one
195 let (minusB_args, argv1) = partition (prefixMatch "-B") args
196 dflags0 <- initSysTools minusB_args defaultDynFlags
197 writeIORef v_initDynFlags dflags0
199 -- Parse the static flags
200 argv2 <- parseStaticFlags argv1
203 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
204 -- stores the DynFlags between the call to init and subsequent
205 -- calls to newSession.
207 -- | Starts a new session. A session consists of a set of loaded
208 -- modules, a set of options (DynFlags), and an interactive context.
209 -- ToDo: GhcMode should say "keep typechecked code" and/or "keep renamed
211 newSession :: GhcMode -> IO Session
213 dflags0 <- readIORef v_initDynFlags
214 dflags <- initDynFlags dflags0
215 env <- newHscEnv dflags{ ghcMode=mode }
219 -- tmp: this breaks the abstraction, but required because DriverMkDepend
220 -- needs to call the Finder. ToDo: untangle this.
221 sessionHscEnv :: Session -> IO HscEnv
222 sessionHscEnv (Session ref) = readIORef ref
224 withSession :: Session -> (HscEnv -> IO a) -> IO a
225 withSession (Session ref) f = do h <- readIORef ref; f h
227 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
228 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
230 -- -----------------------------------------------------------------------------
233 -- | Grabs the DynFlags from the Session
234 getSessionDynFlags :: Session -> IO DynFlags
235 getSessionDynFlags s = withSession s (return . hsc_dflags)
237 -- | Updates the DynFlags in a Session
238 setSessionDynFlags :: Session -> DynFlags -> IO ()
239 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
241 -- | Messages during compilation (eg. warnings and progress messages)
242 -- are reported using this callback. By default, these messages are
243 -- printed to stderr.
244 setMsgHandler :: (String -> IO ()) -> IO ()
245 setMsgHandler = ErrUtils.setMsgHandler
247 -- -----------------------------------------------------------------------------
250 -- ToDo: think about relative vs. absolute file paths. And what
251 -- happens when the current directory changes.
253 -- | Sets the targets for this session. Each target may be a module name
254 -- or a filename. The targets correspond to the set of root modules for
255 -- the program/library. Unloading the current program is achieved by
256 -- setting the current set of targets to be empty, followed by load.
257 setTargets :: Session -> [Target] -> IO ()
258 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
260 -- | returns the current set of targets
261 getTargets :: Session -> IO [Target]
262 getTargets s = withSession s (return . hsc_targets)
264 -- Add another target, or update an existing target with new content.
265 addTarget :: Session -> Target -> IO ()
267 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
270 -- removeTarget :: Session -> Module -> IO ()
272 -- Attempts to guess what Target a string refers to. This function implements
273 -- the --make/GHCi command-line syntax for filenames:
275 -- - if the string looks like a Haskell source filename, then interpret
277 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
279 -- - otherwise interpret the string as a module name
281 guessTarget :: String -> IO Target
283 | isHaskellSrcFilename file
284 = return (Target (TargetFile file) Nothing)
286 = do exists <- doesFileExist hs_file
287 if exists then return (Target (TargetFile hs_file) Nothing) else do
288 exists <- doesFileExist lhs_file
289 if exists then return (Target (TargetFile lhs_file) Nothing) else do
290 return (Target (TargetModule (mkModule file)) Nothing)
292 hs_file = file ++ ".hs"
293 lhs_file = file ++ ".lhs"
295 -- -----------------------------------------------------------------------------
296 -- Loading the program
298 -- | The result of load.
300 = LoadOk Errors -- ^ all specified targets were loaded successfully.
301 | LoadFailed Errors -- ^ not all modules were loaded.
303 type Errors = [String]
306 data ErrMsg = ErrMsg {
307 errMsgSeverity :: Severity, -- warning, error, etc.
308 errMsgSpans :: [SrcSpan],
309 errMsgShortDoc :: Doc,
310 errMsgExtraInfo :: Doc
314 -- Perform a dependency analysis starting from the current targets
315 -- and update the session with the new module graph.
316 depanal :: Session -> [Module] -> IO ()
317 depanal (Session ref) excluded_mods = do
318 hsc_env <- readIORef ref
320 dflags = hsc_dflags hsc_env
321 gmode = ghcMode (hsc_dflags hsc_env)
322 targets = hsc_targets hsc_env
323 old_graph = hsc_mod_graph hsc_env
325 showPass dflags "Chasing dependencies"
326 when (verbosity dflags >= 1 && gmode == BatchCompile) $
327 hPutStrLn stderr (showSDoc (hcat [
328 text "Chasing modules from: ",
329 hcat (punctuate comma (map pprTarget targets))]))
331 graph <- downsweep hsc_env old_graph excluded_mods
332 writeIORef ref hsc_env{ hsc_mod_graph=graph }
335 -- | Try to load the program. If a Module is supplied, then just
336 -- attempt to load up to this target. If no Module is supplied,
337 -- then try to load all targets.
338 load :: Session -> Maybe Module -> IO SuccessFlag
339 load s@(Session ref) maybe_mod{-ToDo-}
341 -- dependency analysis first
344 hsc_env <- readIORef ref
346 let hpt1 = hsc_HPT hsc_env
347 let dflags = hsc_dflags hsc_env
348 let mod_graph = hsc_mod_graph hsc_env
350 let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
351 let verb = verbosity dflags
353 -- The "bad" boot modules are the ones for which we have
354 -- B.hs-boot in the module graph, but no B.hs
355 -- The downsweep should have ensured this does not happen
357 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
358 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
359 not (ms_mod s `elem` all_home_mods)]
360 ASSERT( null bad_boot_mods ) return ()
362 -- Topologically sort the module graph
363 -- mg2 should be cycle free; but it includes hi-boot ModSummary nodes
364 let mg2 :: [SCC ModSummary]
365 mg2 = topSortModuleGraph False mod_graph
367 -- mg2_with_srcimps drops the hi-boot nodes, returning a
368 -- graph with cycles. Among other things, it is used for
369 -- backing out partially complete cycles following a failed
370 -- upsweep, and for removing from hpt all the modules
371 -- not in strict downwards closure, during calls to compile.
372 let mg2_with_srcimps :: [SCC ModSummary]
373 mg2_with_srcimps = topSortModuleGraph True mod_graph
375 -- Sort out which linkables we wish to keep in the unlinked image.
376 -- See getValidLinkables below for details.
377 (valid_old_linkables, new_linkables)
378 <- getValidLinkables ghci_mode (hptLinkables hpt1)
379 all_home_mods mg2_with_srcimps
381 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
383 -- The new_linkables are .o files we found on the disk, presumably
384 -- as a result of a GHC run "on the side". So we'd better forget
385 -- everything we know abouut those modules!
386 let old_hpt = delModuleEnvList hpt1 (map linkableModule new_linkables)
388 -- When (verb >= 2) $
389 -- putStrLn (showSDoc (text "Valid linkables:"
390 -- <+> ppr valid_linkables))
392 -- Figure out a stable set of modules which can be retained
393 -- the top level envs, to avoid upsweeping them. Goes to a
394 -- bit of trouble to avoid upsweeping module cycles.
396 -- Construct a set S of stable modules like this:
397 -- Travel upwards, over the sccified graph. For each scc
398 -- of modules ms, add ms to S only if:
399 -- 1. All home imports of ms are either in ms or S
400 -- 2. A valid old linkable exists for each module in ms
402 -- mg2_with_srcimps has no hi-boot nodes,
403 -- and hence neither does stable_mods
404 stable_summaries <- preUpsweep valid_old_linkables
405 all_home_mods [] mg2_with_srcimps
406 let stable_mods = map ms_mod stable_summaries
407 stable_linkables = filter (\m -> linkableModule m `elem` stable_mods)
410 stable_hpt = filterModuleEnv is_stable_hm hpt1
411 is_stable_hm hm_info = mi_module (hm_iface hm_info) `elem` stable_mods
414 = filter (\scc -> any (`notElem` stable_mods)
415 (map ms_mod (flattenSCC scc)))
419 hPutStrLn stderr (showSDoc (text "Stable modules:"
420 <+> sep (map (text.moduleUserString) stable_mods)))
422 -- Unload any modules which are going to be re-linked this time around.
423 unload hsc_env stable_linkables
425 -- We can now glom together our linkable sets
426 let valid_linkables = valid_old_linkables ++ new_linkables
428 -- We could at this point detect cycles which aren't broken by
429 -- a source-import, and complain immediately, but it seems better
430 -- to let upsweep_mods do this, so at least some useful work gets
431 -- done before the upsweep is abandoned.
432 --hPutStrLn stderr "after tsort:\n"
433 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
435 -- Now do the upsweep, calling compile for each module in
436 -- turn. Final result is version 3 of everything.
438 -- clean up between compilations
439 let cleanup = cleanTempFilesExcept dflags
440 (ppFilesFromSummaries (flattenSCCs mg2))
442 (upsweep_ok, hsc_env3, modsUpswept)
443 <- upsweep_mods (hsc_env { hsc_HPT = stable_hpt })
444 (old_hpt, valid_linkables)
445 cleanup upsweep_these
447 -- At this point, modsUpswept and newLis should have the same
448 -- length, so there is one new (or old) linkable for each
449 -- mod which was processed (passed to compile).
451 -- Make modsDone be the summaries for each home module now
452 -- available; this should equal the domain of hpt3.
453 -- (NOT STRICTLY TRUE if an interactive session was started
454 -- with some object on disk ???)
455 -- Get in in a roughly top .. bottom order (hence reverse).
457 let modsDone = reverse modsUpswept ++ stable_summaries
459 -- Try and do linking in some form, depending on whether the
460 -- upsweep was completely or only partially successful.
462 if succeeded upsweep_ok
465 -- Easy; just relink it all.
466 do when (verb >= 2) $
467 hPutStrLn stderr "Upsweep completely successful."
469 -- Clean up after ourselves
470 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
472 -- Issue a warning for the confusing case where the user
473 -- said '-o foo' but we're not going to do any linking.
474 -- We attempt linking if either (a) one of the modules is
475 -- called Main, or (b) the user said -no-hs-main, indicating
476 -- that main() is going to come from somewhere else.
478 let ofile = outputFile dflags
479 let no_hs_main = dopt Opt_NoHsMain dflags
480 let mb_main_mod = mainModIs dflags
482 main_mod = mb_main_mod `orElse` "Main"
484 = any ((==main_mod).moduleUserString.ms_mod)
486 do_linking = a_root_is_Main || no_hs_main
488 when (ghci_mode == BatchCompile && isJust ofile && not do_linking
490 hPutStrLn stderr ("Warning: output was redirected with -o, " ++
491 "but no output will be generated\n" ++
492 "because there is no " ++ main_mod ++ " module.")
494 -- link everything together
495 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
497 let hsc_env4 = hsc_env3{ hsc_mod_graph = modsDone }
498 loadFinish Succeeded linkresult ref hsc_env4
501 -- Tricky. We need to back out the effects of compiling any
502 -- half-done cycles, both so as to clean up the top level envs
503 -- and to avoid telling the interactive linker to link them.
504 do when (verb >= 2) $
505 hPutStrLn stderr "Upsweep partially successful."
508 = map ms_mod modsDone
509 let mods_to_zap_names
510 = findPartiallyCompletedCycles modsDone_names
513 = filter ((`notElem` mods_to_zap_names).ms_mod)
516 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
519 -- Clean up after ourselves
520 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
522 -- Link everything together
523 linkresult <- link ghci_mode dflags False hpt4
525 let hsc_env4 = hsc_env3{ hsc_mod_graph = mods_to_keep,
527 loadFinish Failed linkresult ref hsc_env4
529 -- Finish up after a load.
531 -- If the link failed, unload everything and return.
532 loadFinish all_ok Failed ref hsc_env
533 = do unload hsc_env []
534 writeIORef ref $! discardProg hsc_env
537 -- Empty the interactive context and set the module context to the topmost
538 -- newly loaded module, or the Prelude if none were loaded.
539 loadFinish all_ok Succeeded ref hsc_env
540 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
543 -- Forget the current program, but retain the persistent info in HscEnv
544 discardProg :: HscEnv -> HscEnv
546 = hsc_env { hsc_mod_graph = emptyMG,
547 hsc_IC = emptyInteractiveContext,
548 hsc_HPT = emptyHomePackageTable }
550 -- used to fish out the preprocess output files for the purposes of
551 -- cleaning up. The preprocessed file *might* be the same as the
552 -- source file, but that doesn't do any harm.
553 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
555 -----------------------------------------------------------------------------
558 unload :: HscEnv -> [Linkable] -> IO ()
559 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
560 = case ghcMode (hsc_dflags hsc_env) of
561 BatchCompile -> return ()
563 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
565 Interactive -> panic "unload: no interpreter"
567 other -> panic "unload: strange mode"
569 -----------------------------------------------------------------------------
572 -- For each module (or SCC of modules), we take:
574 -- - an on-disk linkable, if this is the first time around and one
577 -- - the old linkable, otherwise (and if one is available).
579 -- and we throw away the linkable if it is older than the source file.
580 -- In interactive mode, we also ignore the on-disk linkables unless
581 -- all of the dependents of this SCC also have on-disk linkables (we
582 -- can't have dynamically loaded objects that depend on interpreted
585 -- If a module has a valid linkable, then it may be STABLE (see below),
586 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
589 -- ToDo: this pass could be merged with the preUpsweep.
592 -- CAREFUL! This pass operates on the cyclic version of
593 -- the module graph (topSortModuleGraph True), whereas the upsweep operates on
594 -- the non-cyclic (topSortModuleGraph False) version of the graph.
599 -> [Linkable] -- old linkables
600 -> [Module] -- all home modules
601 -> [SCC ModSummary] -- all modules in the program, dependency order
602 -> IO ( [Linkable], -- still-valid linkables
603 [Linkable] -- new linkables we just found on the disk
604 -- presumably generated by separate run of ghc
607 getValidLinkables mode old_linkables all_home_mods module_graph
608 = do { -- Process the SCCs in bottom-to-top order
609 -- (foldM works left-to-right)
610 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
612 ; return (partition_it ls [] []) }
614 partition_it [] valid new = (valid,new)
615 partition_it ((l,b):ls) valid new
616 | b = partition_it ls valid (l:new)
617 | otherwise = partition_it ls (l:valid) new
622 -> [Linkable] -- old linkables
623 -> [Module] -- all home modules
626 -> IO [(Linkable,Bool)]
628 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
630 scc = flattenSCC scc0
631 scc_names = map ms_mod scc
632 home_module m = m `elem` all_home_mods && m `notElem` scc_names
633 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
634 -- NB. ms_imps, not ms_allimps above. We don't want to
635 -- force a module's SOURCE imports to be already compiled for
636 -- its object linkable to be valid.
638 -- The new_linkables is only the *valid* linkables below here
639 has_object m = case findModuleLinkable_maybe (map fst new_linkables) m of
641 Just l -> isObjectLinkable l
643 objects_allowed = mode == BatchCompile || all has_object scc_allhomeimps
647 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
649 -- since an scc can contain only all objects or no objects at all,
650 -- we have to check whether we got all objects or not, and re-do
651 -- the linkable check if not.
654 && not (all isObjectLinkable (map fst new_linkables'))
655 then foldM (getValidLinkable old_linkables False) [] scc
656 else return new_linkables'
658 return (new_linkables ++ new_linkables')
661 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
662 -> IO [(Linkable,Bool)]
663 -- True <=> linkable is new; i.e. freshly discovered on the disk
664 -- presumably generated 'on the side'
665 -- by a separate GHC run
666 getValidLinkable old_linkables objects_allowed new_linkables summary
667 -- 'objects_allowed' says whether we permit this module to
668 -- have a .o-file linkable. We only permit it if all the
669 -- modules it depends on also have .o files; a .o file can't
670 -- link to a bytecode module
671 = do let mod_name = ms_mod summary
674 <- if (not objects_allowed)
677 else findLinkable mod_name (ms_location summary)
679 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
682 case (old_linkable, maybe_disk_linkable) of
683 (Nothing, Nothing) -> []
685 -- new object linkable just appeared
686 (Nothing, Just l) -> up_to_date l True
689 | isObjectLinkable l -> []
690 -- object linkable disappeared! In case we need to
691 -- relink the module, disregard the old linkable and
692 -- just interpret the module from now on.
693 | otherwise -> up_to_date l False
694 -- old byte code linkable
697 | not (isObjectLinkable l) -> up_to_date l False
698 -- if the previous linkable was interpreted, then we
699 -- ignore a newly compiled version, because the version
700 -- numbers in the interface file will be out-of-sync with
701 -- our internal ones.
702 | linkableTime l' > linkableTime l -> up_to_date l' True
703 | linkableTime l' == linkableTime l -> up_to_date l False
705 -- on-disk linkable has been replaced by an older one!
706 -- again, disregard the previous one.
709 | linkableTime l < ms_hs_date summary = []
710 | otherwise = [(l,b)]
711 -- why '<' rather than '<=' above? If the filesystem stores
712 -- times to the nearset second, we may occasionally find that
713 -- the object & source have the same modification time,
714 -- especially if the source was automatically generated
715 -- and compiled. Using >= is slightly unsafe, but it matches
718 return (new_linkables' ++ new_linkables)
721 hptLinkables :: HomePackageTable -> [Linkable]
722 -- Get all the linkables from the home package table, one for each module
723 -- Once the HPT is up to date, these are the ones we should link
724 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
727 -----------------------------------------------------------------------------
728 -- Do a pre-upsweep without use of "compile", to establish a
729 -- (downward-closed) set of stable modules for which we won't call compile.
732 -- * has a valid linkable (see getValidLinkables above)
733 -- * depends only on stable modules
734 -- * has an interface in the HPT (interactive mode only)
736 preUpsweep :: [Linkable] -- new valid linkables
737 -> [Module] -- names of all mods encountered in downsweep
738 -> [ModSummary] -- accumulating stable modules
739 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
740 -> IO [ModSummary] -- stable modules
742 preUpsweep valid_lis all_home_mods stable [] = return stable
743 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
744 = do let scc = flattenSCC scc0
745 scc_allhomeimps :: [Module]
747 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
748 all_imports_in_scc_or_stable
749 = all in_stable_or_scc scc_allhomeimps
750 scc_mods = map ms_mod scc
751 stable_names = scc_mods ++ map ms_mod stable
752 in_stable_or_scc m = m `elem` stable_names
754 -- now we check for valid linkables: each module in the SCC must
755 -- have a valid linkable (see getValidLinkables above).
756 has_valid_linkable scc_mod
757 = isJust (findModuleLinkable_maybe valid_lis scc_mod)
759 scc_is_stable = all_imports_in_scc_or_stable
760 && all has_valid_linkable scc_mods
763 then preUpsweep valid_lis all_home_mods (scc ++ stable) sccs
764 else preUpsweep valid_lis all_home_mods stable sccs
766 ms_allimps :: ModSummary -> [Module]
767 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
769 -- Return (names of) all those in modsDone who are part of a cycle
770 -- as defined by theGraph.
771 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
772 findPartiallyCompletedCycles modsDone theGraph
776 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
777 chew ((CyclicSCC vs):rest)
778 = let names_in_this_cycle = nub (map ms_mod vs)
780 = nub ([done | done <- modsDone,
781 done `elem` names_in_this_cycle])
782 chewed_rest = chew rest
784 if notNull mods_in_this_cycle
785 && length mods_in_this_cycle < length names_in_this_cycle
786 then mods_in_this_cycle ++ chewed_rest
790 -- Compile multiple modules, stopping as soon as an error appears.
791 -- There better had not be any cyclic groups here -- we check for them.
792 upsweep_mods :: HscEnv -- Includes initially-empty HPT
793 -> (HomePackageTable, [Linkable]) -- HPT and valid linkables from last time round
794 -> IO () -- How to clean up unwanted tmp files
795 -> [SCC ModSummary] -- Mods to do (the worklist)
797 HscEnv, -- With an updated HPT
798 [ModSummary]) -- Mods which succeeded
800 upsweep_mods hsc_env oldUI cleanup
802 = return (Succeeded, hsc_env, [])
804 upsweep_mods hsc_env oldUI cleanup
806 = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
807 return (Failed, hsc_env, [])
809 upsweep_mods hsc_env oldUI@(old_hpt, old_linkables) cleanup
810 (AcyclicSCC mod:mods)
811 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
812 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
813 -- (moduleEnvElts (hsc_HPT hsc_env)))
815 mb_mod_info <- upsweep_mod hsc_env oldUI mod
817 cleanup -- Remove unwanted tmp files between compilations
820 Nothing -> return (Failed, hsc_env, [])
822 { let this_mod = ms_mod mod
824 -- Add new info to hsc_env
825 hpt1 = extendModuleEnv (hsc_HPT hsc_env) this_mod mod_info
826 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
827 -- Space-saving: delete the old HPT entry and
828 -- linkable for mod BUT if mod is a hs-boot
829 -- node, don't delete it For the linkable this
830 -- is dead right: the linkable relates only to
831 -- the main Haskell source file. For the
832 -- interface, the HPT entry is probaby for the
833 -- main Haskell source file. Deleting it
834 -- would force .. (what?? --SDM)
835 oldUI1 | isBootSummary mod = oldUI
837 = (delModuleEnv old_hpt this_mod,
838 delModuleLinkable old_linkables this_mod)
840 ; (restOK, hsc_env2, modOKs) <- upsweep_mods hsc_env1 oldUI1 cleanup mods
841 ; return (restOK, hsc_env2, mod:modOKs) }
844 -- Compile a single module. Always produce a Linkable for it if
845 -- successful. If no compilation happened, return the old Linkable.
846 upsweep_mod :: HscEnv
847 -> (HomePackageTable, UnlinkedImage)
849 -> IO (Maybe HomeModInfo) -- Nothing => Failed
851 upsweep_mod hsc_env (old_hpt, old_linkables) summary
853 let this_mod = ms_mod summary
855 -- The old interface is ok if it's in the old HPT
856 -- a) we're compiling a source file, and the old HPT
857 -- entry is for a source file
858 -- b) we're compiling a hs-boot file
859 -- Case (b) allows an hs-boot file to get the interface of its
860 -- real source file on the second iteration of the compilation
861 -- manager, but that does no harm. Otherwise the hs-boot file
862 -- will always be recompiled
865 = case lookupModuleEnv old_hpt this_mod of
867 Just hm_info | isBootSummary summary -> Just iface
868 | not (mi_boot iface) -> Just iface
869 | otherwise -> Nothing
871 iface = hm_iface hm_info
873 maybe_old_linkable = findModuleLinkable_maybe old_linkables this_mod
874 source_unchanged = isJust maybe_old_linkable
876 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
879 | Just l <- maybe_old_linkable, isObjectLinkable l = True
882 compresult <- compile hsc_env summary source_unchanged have_object mb_old_iface
886 -- Compilation "succeeded", and may or may not have returned a new
887 -- linkable (depending on whether compilation was actually performed
889 CompOK new_details new_iface maybe_new_linkable
891 new_linkable = maybe_new_linkable `orElse` old_linkable
892 new_info = HomeModInfo { hm_iface = new_iface,
893 hm_details = new_details,
894 hm_linkable = new_linkable }
895 return (Just new_info)
897 -- Compilation failed. Compile may still have updated the PCS, tho.
898 CompErrs -> return Nothing
900 -- Filter modules in the HPT
901 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
902 retainInTopLevelEnvs keep_these hpt
903 = mkModuleEnv [ (mod, fromJust mb_mod_info)
905 , let mb_mod_info = lookupModuleEnv hpt mod
906 , isJust mb_mod_info ]
908 -- ---------------------------------------------------------------------------
909 -- Topological sort of the module graph
912 :: Bool -- Drop hi-boot nodes? (see below)
915 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
917 -- Drop hi-boot nodes (first boolean arg)?
919 -- False: treat the hi-boot summaries as nodes of the graph,
920 -- so the graph must be acyclic
922 -- True: eliminate the hi-boot nodes, and instead pretend
923 -- the a source-import of Foo is an import of Foo
924 -- The resulting graph has no hi-boot nodes, but can by cyclic
926 topSortModuleGraph drop_hs_boot_nodes summaries
927 = stronglyConnComp nodes
929 -- Drop hs-boot nodes by using HsSrcFile as the key
930 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
931 | otherwise = HsBootFile
933 -- We use integers as the keys for the SCC algorithm
934 nodes :: [(ModSummary, Int, [Int])]
935 nodes = [(s, fromJust (lookup_key (ms_hsc_src s) (ms_mod s)),
936 out_edge_keys hs_boot_key (ms_srcimps s) ++
937 out_edge_keys HsSrcFile (ms_imps s) )
939 , not (isBootSummary s && drop_hs_boot_nodes) ]
940 -- Drop the hi-boot ones if told to do so
942 key_map :: NodeMap Int
943 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
946 lookup_key :: HscSource -> Module -> Maybe Int
947 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
949 out_edge_keys :: HscSource -> [Module] -> [Int]
950 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
951 -- If we want keep_hi_boot_nodes, then we do lookup_key with
952 -- the IsBootInterface parameter True; else False
955 type NodeKey = (Module, HscSource) -- The nodes of the graph are
956 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
958 msKey :: ModSummary -> NodeKey
959 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
961 emptyNodeMap :: NodeMap a
962 emptyNodeMap = emptyFM
964 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
965 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
967 nodeMapElts :: NodeMap a -> [a]
970 -- -----------------------------------------------------------------
971 -- The unlinked image
973 -- The compilation manager keeps a list of compiled, but as-yet unlinked
974 -- binaries (byte code or object code). Even when it links bytecode
975 -- it keeps the unlinked version so it can re-link it later without
978 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
980 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
981 findModuleLinkable_maybe lis mod
982 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
985 many -> pprPanic "findModuleLinkable" (ppr mod)
987 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
988 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
990 -----------------------------------------------------------------------------
991 -- Downsweep (dependency analysis)
993 -- Chase downwards from the specified root set, returning summaries
994 -- for all home modules encountered. Only follow source-import
997 -- We pass in the previous collection of summaries, which is used as a
998 -- cache to avoid recalculating a module summary if the source is
1001 -- The returned list of [ModSummary] nodes has one node for each home-package
1002 -- module, plus one for any hs-boot files. The imports of these nodes
1003 -- are all there, including the imports of non-home-package modules.
1006 -> [ModSummary] -- Old summaries
1007 -> [Module] -- Ignore dependencies on these; treat them as
1008 -- if they were package modules
1010 downsweep hsc_env old_summaries excl_mods
1011 = do rootSummaries <- mapM getRootSummary roots
1012 checkDuplicates rootSummaries
1013 loop (concatMap msDeps rootSummaries)
1014 (mkNodeMap rootSummaries)
1016 dflags = hsc_dflags hsc_env
1017 roots = hsc_targets hsc_env
1019 old_summary_map :: NodeMap ModSummary
1020 old_summary_map = mkNodeMap old_summaries
1022 getRootSummary :: Target -> IO ModSummary
1023 getRootSummary (Target (TargetFile file) maybe_buf)
1024 = do exists <- doesFileExist file
1025 if exists then summariseFile hsc_env file else do
1026 throwDyn (CmdLineError ("can't find file: " ++ file))
1027 getRootSummary (Target (TargetModule modl) maybe_buf)
1028 = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False
1030 case maybe_summary of
1031 Nothing -> packageModErr modl
1034 -- In a root module, the filename is allowed to diverge from the module
1035 -- name, so we have to check that there aren't multiple root files
1036 -- defining the same module (otherwise the duplicates will be silently
1037 -- ignored, leading to confusing behaviour).
1038 checkDuplicates :: [ModSummary] -> IO ()
1039 checkDuplicates summaries = mapM_ check summaries
1044 many -> multiRootsErr modl many
1045 where modl = ms_mod summ
1047 [ fromJust (ml_hs_file (ms_location summ'))
1048 | summ' <- summaries, ms_mod summ' == modl ]
1050 loop :: [(FilePath,Module,IsBootInterface)]
1051 -- Work list: process these modules
1052 -> NodeMap ModSummary
1055 -- The result includes the worklist, except
1056 -- for those mentioned in the visited set
1057 loop [] done = return (nodeMapElts done)
1058 loop ((cur_path, wanted_mod, is_boot) : ss) done
1059 | key `elemFM` done = loop ss done
1060 | otherwise = do { mb_s <- summarise hsc_env old_summary_map
1061 (Just cur_path) is_boot
1062 wanted_mod excl_mods
1064 Nothing -> loop ss done
1065 Just s -> loop (msDeps s ++ ss)
1066 (addToFM done key s) }
1068 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1070 msDeps :: ModSummary -> [(FilePath, -- Importing module
1071 Module, -- Imported module
1072 IsBootInterface)] -- {-# SOURCE #-} import or not
1073 -- (msDeps s) returns the dependencies of the ModSummary s.
1074 -- A wrinkle is that for a {-# SOURCE #-} import we return
1075 -- *both* the hs-boot file
1076 -- *and* the source file
1077 -- as "dependencies". That ensures that the list of all relevant
1078 -- modules always contains B.hs if it contains B.hs-boot.
1079 -- Remember, this pass isn't doing the topological sort. It's
1080 -- just gathering the list of all relevant ModSummaries
1081 msDeps s = concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s]
1082 ++ [(f,m,False) | m <- ms_imps s]
1084 f = msHsFilePath s -- Keep the importing module for error reporting
1087 -----------------------------------------------------------------------------
1088 -- Summarising modules
1090 -- We have two types of summarisation:
1092 -- * Summarise a file. This is used for the root module(s) passed to
1093 -- cmLoadModules. The file is read, and used to determine the root
1094 -- module name. The module name may differ from the filename.
1096 -- * Summarise a module. We are given a module name, and must provide
1097 -- a summary. The finder is used to locate the file in which the module
1100 summariseFile :: HscEnv -> FilePath -> IO ModSummary
1101 -- Used for Haskell source only, I think
1102 -- We know the file name, and we know it exists,
1103 -- but we don't necessarily know the module name (might differ)
1104 summariseFile hsc_env file
1105 = do let dflags = hsc_dflags hsc_env
1107 (dflags', hspp_fn) <- preprocess dflags file
1108 -- The dflags' contains the OPTIONS pragmas
1110 -- Read the file into a buffer. We're going to cache
1111 -- this buffer in the ModLocation (ml_hspp_buf) so that it
1112 -- doesn't have to be slurped again when hscMain parses the
1114 buf <- hGetStringBuffer hspp_fn
1115 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1117 -- Make a ModLocation for this file
1118 location <- mkHomeModLocation dflags mod file
1120 -- Tell the Finder cache where it is, so that subsequent calls
1121 -- to findModule will find it, even if it's not on any search path
1122 addHomeModuleToFinder hsc_env mod location
1124 src_timestamp <- getModificationTime file
1125 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1126 ms_location = location,
1127 ms_hspp_file = Just hspp_fn,
1128 ms_hspp_buf = Just buf,
1129 ms_srcimps = srcimps, ms_imps = the_imps,
1130 ms_hs_date = src_timestamp })
1132 -- Summarise a module, and pick up source and timestamp.
1134 -> NodeMap ModSummary -- Map of old summaries
1135 -> Maybe FilePath -- Importing module (for error messages)
1136 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1137 -> Module -- Imported module to be summarised
1138 -> [Module] -- Modules to exclude
1139 -> IO (Maybe ModSummary) -- Its new summary
1141 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod excl_mods
1142 | wanted_mod `elem` excl_mods
1145 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1146 = do { -- Find its new timestamp; all the
1147 -- ModSummaries in the old map have valid ml_hs_files
1148 let location = ms_location old_summary
1149 src_fn = fromJust (ml_hs_file location)
1151 ; src_timestamp <- getModificationTime src_fn
1153 -- return the cached summary if the source didn't change
1154 ; if ms_hs_date old_summary == src_timestamp
1155 then return (Just old_summary)
1156 else new_summary location
1160 = do { found <- findModule hsc_env wanted_mod True {-explicit-}
1163 | not (isHomePackage pkg) -> return Nothing
1164 -- Drop external-pkg
1165 | isJust (ml_hs_file location) -> new_summary location
1167 err -> noModError dflags cur_mod wanted_mod err
1171 dflags = hsc_dflags hsc_env
1173 hsc_src = if is_boot then HsBootFile else HsSrcFile
1175 new_summary location
1176 = do { -- Adjust location to point to the hs-boot source file,
1177 -- hi file, object file, when is_boot says so
1178 let location' | is_boot = addBootSuffixLocn location
1179 | otherwise = location
1180 src_fn = fromJust (ml_hs_file location')
1182 -- Check that it exists
1183 -- It might have been deleted since the Finder last found it
1184 ; exists <- doesFileExist src_fn
1185 ; if exists then return () else noHsFileErr cur_mod src_fn
1187 -- Preprocess the source file and get its imports
1188 -- The dflags' contains the OPTIONS pragmas
1189 ; (dflags', hspp_fn) <- preprocess dflags src_fn
1190 ; buf <- hGetStringBuffer hspp_fn
1191 ; (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1193 ; when (mod_name /= wanted_mod) $
1194 throwDyn (ProgramError
1195 (showSDoc (text src_fn
1196 <> text ": file name does not match module name"
1197 <+> quotes (ppr mod_name))))
1199 -- Find its timestamp, and return the summary
1200 ; src_timestamp <- getModificationTime src_fn
1201 ; return (Just ( ModSummary { ms_mod = wanted_mod,
1202 ms_hsc_src = hsc_src,
1203 ms_location = location',
1204 ms_hspp_file = Just hspp_fn,
1205 ms_hspp_buf = Just buf,
1206 ms_srcimps = srcimps,
1208 ms_hs_date = src_timestamp }))
1212 -----------------------------------------------------------------------------
1214 -----------------------------------------------------------------------------
1216 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1217 -- ToDo: we don't have a proper line number for this error
1218 noModError dflags cur_mod wanted_mod err
1219 = throwDyn $ ProgramError $ showSDoc $
1220 vcat [cantFindError dflags wanted_mod err,
1221 nest 2 (parens (pp_where cur_mod))]
1223 noHsFileErr cur_mod path
1224 = throwDyn $ CmdLineError $ showSDoc $
1225 vcat [text "Can't find" <+> text path,
1226 nest 2 (parens (pp_where cur_mod))]
1228 pp_where Nothing = text "one of the roots of the dependency analysis"
1229 pp_where (Just p) = text "imported from" <+> text p
1232 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1233 quotes (ppr mod) <+>
1234 text "is a package module")))
1236 multiRootsErr mod files
1237 = throwDyn (ProgramError (showSDoc (
1238 text "module" <+> quotes (ppr mod) <+>
1239 text "is defined in multiple files:" <+>
1240 sep (map text files))))
1242 cyclicModuleErr :: [ModSummary] -> SDoc
1244 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1245 2 (vcat (map show_one ms))
1247 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1248 nest 2 $ ptext SLIT("imports:") <+>
1249 (pp_imps HsBootFile (ms_srcimps ms)
1250 $$ pp_imps HsSrcFile (ms_imps ms))]
1251 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1252 pp_imps src mods = fsep (map (show_mod src) mods)
1255 -- | Inform GHC that the working directory has changed. GHC will flush
1256 -- its cache of module locations, since it may no longer be valid.
1257 -- Note: if you change the working directory, you should also unload
1258 -- the current program (set targets to empty, followed by load).
1259 workingDirectoryChanged :: Session -> IO ()
1260 workingDirectoryChanged s = withSession s $ \hsc_env ->
1261 flushFinderCache (hsc_FC hsc_env)
1263 -- -----------------------------------------------------------------------------
1264 -- inspecting the session
1266 -- | Get the module dependency graph. After a 'load', this will contain
1267 -- only the modules that were successfully loaded.
1268 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1269 getModuleGraph s = withSession s (return . hsc_mod_graph)
1271 getBindings :: Session -> IO [TyThing]
1272 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1274 getPrintUnqual :: Session -> IO PrintUnqualified
1275 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1278 getModuleInfo :: Session -> Module -> IO ModuleInfo
1282 | BinaryCode FilePath
1284 data ModuleInfo = ModuleInfo {
1285 lm_modulename :: Module,
1286 lm_summary :: ModSummary,
1287 lm_interface :: ModIface,
1288 lm_tc_code :: Maybe TypecheckedCode,
1289 lm_rn_code :: Maybe RenamedCode,
1290 lm_obj :: Maybe ObjectCode
1293 type TypecheckedCode = HsTypecheckedGroup
1294 type RenamedCode = [HsGroup Name]
1296 -- ToDo: typechecks abstract syntax or renamed abstract syntax. Issues:
1297 -- - typechecked syntax includes extra dictionary translation and
1298 -- AbsBinds which need to be translated back into something closer to
1299 -- the original source.
1300 -- - renamed syntax currently doesn't exist in a single blob, since
1301 -- renaming and typechecking are interleaved at splice points. We'd
1302 -- need a restriction that there are no splices in the source module.
1305 -- - Data and Typeable instances for HsSyn.
1308 -- - things that aren't in the output of the renamer:
1309 -- - the export list
1313 -- - things that aren't in the output of the typechecker right now:
1314 -- - the export list
1316 -- - type signatures
1317 -- - type/data/newtype declarations
1318 -- - class declarations
1320 -- - extra things in the typechecker's output:
1321 -- - default methods are turned into top-level decls.
1322 -- - dictionary bindings
1324 -- ToDo: check for small transformations that happen to the syntax in
1325 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1327 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1328 -- to get from TyCons, Ids etc. to TH syntax (reify).
1330 -- :browse will use either lm_toplev or inspect lm_interface, depending
1331 -- on whether the module is interpreted or not.
1333 -- various abstract syntax types (perhaps IfaceBlah)
1337 -- This is for reconstructing refactored source code
1338 -- Calls the lexer repeatedly.
1339 -- ToDo: add comment tokens to token stream
1340 getTokenStream :: Session -> Module -> IO [Located Token]
1343 -- -----------------------------------------------------------------------------
1344 -- Interactive evaluation
1348 -- | Set the interactive evaluation context.
1350 -- Setting the context doesn't throw away any bindings; the bindings
1351 -- we've built up in the InteractiveContext simply move to the new
1352 -- module. They always shadow anything in scope in the current context.
1353 setContext :: Session
1354 -> [Module] -- entire top level scope of these modules
1355 -> [Module] -- exports only of these modules
1357 setContext (Session ref) toplevs exports = do
1358 hsc_env <- readIORef ref
1359 let old_ic = hsc_IC hsc_env
1360 hpt = hsc_HPT hsc_env
1361 dflags = hsc_dflags hsc_env
1363 mapM_ (checkModuleExists hsc_env hpt) exports
1364 export_env <- mkExportEnv hsc_env exports
1365 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1366 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1367 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1368 ic_exports = exports,
1369 ic_rn_gbl_env = all_env } }
1371 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1372 checkModuleExists hsc_env hpt mod =
1373 case lookupModuleEnv hpt mod of
1374 Just mod_info -> return ()
1375 _not_a_home_module -> do
1376 res <- findPackageModule hsc_env mod True
1378 Found _ _ -> return ()
1379 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1380 throwDyn (CmdLineError (showSDoc msg))
1382 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1383 mkTopLevEnv hpt modl
1384 = case lookupModuleEnv hpt modl of
1386 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1387 ++ showSDoc (pprModule modl)))
1389 case mi_globals (hm_iface details) of
1391 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1392 ++ showSDoc (pprModule modl)))
1393 Just env -> return env
1395 -- | Get the interactive evaluation context, consisting of a pair of the
1396 -- set of modules from which we take the full top-level scope, and the set
1397 -- of modules from which we take just the exports respectively.
1398 getContext :: Session -> IO ([Module],[Module])
1399 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1400 return (ic_toplev_scope ic, ic_exports ic))
1402 -- | Returns 'True' if the specified module is interpreted, and hence has
1403 -- its full top-level scope available.
1404 moduleIsInterpreted :: Session -> Module -> IO Bool
1405 moduleIsInterpreted s modl = withSession s $ \h ->
1406 case lookupModuleEnv (hsc_HPT h) modl of
1407 Just details -> return (isJust (mi_globals (hm_iface details)))
1408 _not_a_home_module -> return False
1410 -- | Looks up an identifier in the current interactive context (for :info)
1411 getInfo :: Session -> String -> IO [GetInfoResult]
1412 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1414 -- -----------------------------------------------------------------------------
1415 -- Getting the type of an expression
1417 -- | Get the type of an expression
1418 exprType :: Session -> String -> IO (Maybe Type)
1419 exprType s expr = withSession s $ \hsc_env -> do
1420 maybe_stuff <- hscTcExpr hsc_env expr
1422 Nothing -> return Nothing
1423 Just ty -> return (Just tidy_ty)
1425 tidy_ty = tidyType emptyTidyEnv ty
1426 dflags = hsc_dflags hsc_env
1428 -- -----------------------------------------------------------------------------
1429 -- Getting the kind of a type
1431 -- | Get the kind of a type
1432 typeKind :: Session -> String -> IO (Maybe Kind)
1433 typeKind s str = withSession s $ \hsc_env -> do
1434 maybe_stuff <- hscKcType hsc_env str
1436 Nothing -> return Nothing
1437 Just kind -> return (Just kind)
1439 -----------------------------------------------------------------------------
1440 -- lookupName: returns the TyThing for a Name in the interactive context.
1441 -- ToDo: should look it up in the full environment
1443 lookupName :: Session -> Name -> IO (Maybe TyThing)
1444 lookupName s name = withSession s $ \hsc_env -> do
1445 return $! lookupNameEnv (ic_type_env (hsc_IC hsc_env)) name
1447 -----------------------------------------------------------------------------
1448 -- cmCompileExpr: compile an expression and deliver an HValue
1450 compileExpr :: Session -> String -> IO (Maybe HValue)
1451 compileExpr s expr = withSession s $ \hsc_env -> do
1452 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1454 Nothing -> return Nothing
1455 Just (new_ic, names, hval) -> do
1457 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1459 case (names,hvals) of
1460 ([n],[hv]) -> return (Just hv)
1461 _ -> panic "compileExpr"
1463 -- -----------------------------------------------------------------------------
1464 -- running a statement interactively
1467 = RunOk [Name] -- ^ names bound by this evaluation
1468 | RunFailed -- ^ statement failed compilation
1469 | RunException Exception -- ^ statement raised an exception
1471 -- | Run a statement in the current interactive context. Statemenet
1472 -- may bind multple values.
1473 runStmt :: Session -> String -> IO RunResult
1474 runStmt (Session ref) expr
1476 hsc_env <- readIORef ref
1478 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1479 -- warnings about the implicit bindings we introduce.
1480 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1481 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1483 maybe_stuff <- hscStmt hsc_env' expr
1486 Nothing -> return RunFailed
1487 Just (new_hsc_env, names, hval) -> do
1489 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1490 either_hvals <- sandboxIO thing_to_run
1492 case either_hvals of
1494 -- on error, keep the *old* interactive context,
1495 -- so that 'it' is not bound to something
1496 -- that doesn't exist.
1497 return (RunException e)
1500 -- Get the newly bound things, and bind them.
1501 -- Don't need to delete any shadowed bindings;
1502 -- the new ones override the old ones.
1503 extendLinkEnv (zip names hvals)
1505 writeIORef ref new_hsc_env
1506 return (RunOk names)
1509 -- We run the statement in a "sandbox" to protect the rest of the
1510 -- system from anything the expression might do. For now, this
1511 -- consists of just wrapping it in an exception handler, but see below
1512 -- for another version.
1514 sandboxIO :: IO a -> IO (Either Exception a)
1515 sandboxIO thing = Exception.try thing
1518 -- This version of sandboxIO runs the expression in a completely new
1519 -- RTS main thread. It is disabled for now because ^C exceptions
1520 -- won't be delivered to the new thread, instead they'll be delivered
1521 -- to the (blocked) GHCi main thread.
1523 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1525 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1526 sandboxIO thing = do
1527 st_thing <- newStablePtr (Exception.try thing)
1528 alloca $ \ p_st_result -> do
1529 stat <- rts_evalStableIO st_thing p_st_result
1530 freeStablePtr st_thing
1532 then do st_result <- peek p_st_result
1533 result <- deRefStablePtr st_result
1534 freeStablePtr st_result
1535 return (Right result)
1537 return (Left (fromIntegral stat))
1539 foreign import "rts_evalStableIO" {- safe -}
1540 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1541 -- more informative than the C type!
1544 -- ---------------------------------------------------------------------------
1545 -- cmBrowseModule: get all the TyThings defined in a module
1547 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1548 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1549 mb_decls <- getModuleContents hsc_env modl exports_only
1551 Nothing -> return [] -- An error of some kind
1552 Just ds -> return ds
1555 -----------------------------------------------------------------------------
1556 -- show a module and it's source/object filenames
1558 showModule :: Session -> ModSummary -> IO String
1559 showModule s mod_summary = withSession s $ \hsc_env -> do
1560 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1561 Nothing -> panic "missing linkable"
1562 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1564 obj_linkable = isObjectLinkable (hm_linkable mod_info)