1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), GhcMode(..), HscTarget(..), dopt,
25 Target(..), TargetId(..),
32 -- * Loading\/compiling the program
34 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
35 workingDirectoryChanged,
36 checkModule, CheckedModule(..),
38 -- * Inspecting the module structure of the program
39 ModuleGraph, ModSummary(..),
44 -- * Interactive evaluation
45 getBindings, getPrintUnqual,
47 setContext, getContext,
49 getInfo, GetInfoResult,
60 -- * Abstract syntax elements
61 Module, mkModule, pprModule,
64 Name, Id, TyCon, Class, DataCon,
68 -- used by DriverMkDepend:
76 * return error messages rather than printing them.
77 * inline bits of HscMain here to simplify layering: hscGetInfo,
79 * implement second argument to load.
80 * we need to expose DynFlags, so should parseDynamicFlags really be
81 part of this interface?
82 * what StaticFlags should we expose, if any?
85 #include "HsVersions.h"
88 import qualified Linker
89 import Linker ( HValue, extendLinkEnv )
90 import NameEnv ( lookupNameEnv )
91 import TcRnDriver ( mkExportEnv, getModuleContents )
92 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
93 import HscMain ( hscGetInfo, GetInfoResult,
94 hscStmt, hscTcExpr, hscKcType )
95 import Type ( tidyType )
96 import VarEnv ( emptyTidyEnv )
97 import GHC.Exts ( unsafeCoerce# )
98 import IfaceSyn ( IfaceDecl )
101 import HsSyn ( HsModule, LHsBinds )
102 import Type ( Kind, Type, dropForAlls )
103 import Id ( Id, idType )
104 import TyCon ( TyCon )
105 import Class ( Class )
106 import DataCon ( DataCon )
108 import RdrName ( RdrName )
109 import NameEnv ( nameEnvElts )
110 import SrcLoc ( Located )
111 import DriverPipeline
112 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
113 import GetImports ( getImports )
114 import Packages ( isHomePackage )
116 import HscMain ( newHscEnv, hscFileCheck, HscResult(..) )
120 import SysTools ( initSysTools, cleanTempFiles )
125 import ErrUtils ( showPass, Messages )
126 import qualified ErrUtils
128 import StringBuffer ( StringBuffer(..), hGetStringBuffer, lexemeToString )
130 import SysTools ( cleanTempFilesExcept )
131 import BasicTypes ( SuccessFlag(..), succeeded, failed )
132 import Maybes ( orElse, expectJust, mapCatMaybes )
134 import Directory ( getModificationTime, doesFileExist )
135 import Maybe ( isJust, isNothing, fromJust )
136 import Maybes ( expectJust )
137 import List ( partition, nub )
138 import qualified List
139 import Monad ( unless, when, foldM )
140 import System ( exitWith, ExitCode(..) )
141 import Time ( ClockTime )
142 import EXCEPTION as Exception hiding (handle)
143 import GLAEXTS ( Int(..) )
146 import Prelude hiding (init)
148 -- -----------------------------------------------------------------------------
149 -- Exception handlers
151 -- | Install some default exception handlers and run the inner computation.
152 -- Unless you want to handle exceptions yourself, you should wrap this around
153 -- the top level of your program. The default handlers output the error
154 -- message(s) to stderr and exit cleanly.
155 defaultErrorHandler :: IO a -> IO a
156 defaultErrorHandler inner =
157 -- top-level exception handler: any unrecognised exception is a compiler bug.
158 handle (\exception -> do
161 -- an IO exception probably isn't our fault, so don't panic
162 IOException _ -> hPutStrLn stderr (show exception)
163 AsyncException StackOverflow ->
164 hPutStrLn stderr "stack overflow: use +RTS -K<size> to increase it"
165 _other -> hPutStr stderr (show (Panic (show exception)))
166 exitWith (ExitFailure 1)
169 -- all error messages are propagated as exceptions
170 handleDyn (\dyn -> do
173 PhaseFailed _ code -> exitWith code
174 Interrupted -> exitWith (ExitFailure 1)
175 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
176 exitWith (ExitFailure 1)
180 -- | Install a default cleanup handler to remove temporary files
181 -- deposited by a GHC run. This is seperate from
182 -- 'defaultErrorHandler', because you might want to override the error
183 -- handling, but still get the ordinary cleanup behaviour.
184 defaultCleanupHandler :: DynFlags -> IO a -> IO a
185 defaultCleanupHandler dflags inner =
186 -- make sure we clean up after ourselves
187 later (unless (dopt Opt_KeepTmpFiles dflags) $
188 cleanTempFiles dflags)
189 -- exceptions will be blocked while we clean the temporary files,
190 -- so there shouldn't be any difficulty if we receive further
195 -- | Initialises GHC. This must be done /once/ only. Takes the
196 -- command-line arguments. All command-line arguments which aren't
197 -- understood by GHC will be returned.
199 init :: [String] -> IO [String]
202 installSignalHandlers
204 -- Grab the -B option if there is one
205 let (minusB_args, argv1) = partition (prefixMatch "-B") args
206 dflags0 <- initSysTools minusB_args defaultDynFlags
207 writeIORef v_initDynFlags dflags0
209 -- Parse the static flags
210 argv2 <- parseStaticFlags argv1
213 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
214 -- stores the DynFlags between the call to init and subsequent
215 -- calls to newSession.
217 -- | Starts a new session. A session consists of a set of loaded
218 -- modules, a set of options (DynFlags), and an interactive context.
219 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
221 newSession :: GhcMode -> IO Session
223 dflags0 <- readIORef v_initDynFlags
224 dflags <- initDynFlags dflags0
225 env <- newHscEnv dflags{ ghcMode=mode }
229 -- tmp: this breaks the abstraction, but required because DriverMkDepend
230 -- needs to call the Finder. ToDo: untangle this.
231 sessionHscEnv :: Session -> IO HscEnv
232 sessionHscEnv (Session ref) = readIORef ref
234 withSession :: Session -> (HscEnv -> IO a) -> IO a
235 withSession (Session ref) f = do h <- readIORef ref; f h
237 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
238 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
240 -- -----------------------------------------------------------------------------
243 -- | Grabs the DynFlags from the Session
244 getSessionDynFlags :: Session -> IO DynFlags
245 getSessionDynFlags s = withSession s (return . hsc_dflags)
247 -- | Updates the DynFlags in a Session
248 setSessionDynFlags :: Session -> DynFlags -> IO ()
249 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
251 -- | Messages during compilation (eg. warnings and progress messages)
252 -- are reported using this callback. By default, these messages are
253 -- printed to stderr.
254 setMsgHandler :: (String -> IO ()) -> IO ()
255 setMsgHandler = ErrUtils.setMsgHandler
257 -- -----------------------------------------------------------------------------
260 -- ToDo: think about relative vs. absolute file paths. And what
261 -- happens when the current directory changes.
263 -- | Sets the targets for this session. Each target may be a module name
264 -- or a filename. The targets correspond to the set of root modules for
265 -- the program\/library. Unloading the current program is achieved by
266 -- setting the current set of targets to be empty, followed by load.
267 setTargets :: Session -> [Target] -> IO ()
268 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
270 -- | returns the current set of targets
271 getTargets :: Session -> IO [Target]
272 getTargets s = withSession s (return . hsc_targets)
274 -- | Add another target
275 addTarget :: Session -> Target -> IO ()
277 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
280 removeTarget :: Session -> TargetId -> IO ()
281 removeTarget s target_id
282 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
284 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
286 -- Attempts to guess what Target a string refers to. This function implements
287 -- the --make/GHCi command-line syntax for filenames:
289 -- - if the string looks like a Haskell source filename, then interpret
291 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
293 -- - otherwise interpret the string as a module name
295 guessTarget :: String -> IO Target
297 | isHaskellSrcFilename file
298 = return (Target (TargetFile file) Nothing)
300 = do exists <- doesFileExist hs_file
301 if exists then return (Target (TargetFile hs_file) Nothing) else do
302 exists <- doesFileExist lhs_file
303 if exists then return (Target (TargetFile lhs_file) Nothing) else do
304 return (Target (TargetModule (mkModule file)) Nothing)
306 hs_file = file ++ ".hs"
307 lhs_file = file ++ ".lhs"
309 -- -----------------------------------------------------------------------------
310 -- Loading the program
312 -- Perform a dependency analysis starting from the current targets
313 -- and update the session with the new module graph.
314 depanal :: Session -> [Module] -> IO ()
315 depanal (Session ref) excluded_mods = do
316 hsc_env <- readIORef ref
318 dflags = hsc_dflags hsc_env
319 gmode = ghcMode (hsc_dflags hsc_env)
320 targets = hsc_targets hsc_env
321 old_graph = hsc_mod_graph hsc_env
323 showPass dflags "Chasing dependencies"
324 when (verbosity dflags >= 1 && gmode == BatchCompile) $
325 hPutStrLn stderr (showSDoc (hcat [
326 text "Chasing modules from: ",
327 hcat (punctuate comma (map pprTarget targets))]))
329 graph <- downsweep hsc_env old_graph excluded_mods
330 writeIORef ref hsc_env{ hsc_mod_graph=graph }
333 -- | The result of load.
335 = LoadOk Errors -- ^ all specified targets were loaded successfully.
336 | LoadFailed Errors -- ^ not all modules were loaded.
338 type Errors = [String]
340 data ErrMsg = ErrMsg {
341 errMsgSeverity :: Severity, -- warning, error, etc.
342 errMsgSpans :: [SrcSpan],
343 errMsgShortDoc :: Doc,
344 errMsgExtraInfo :: Doc
351 | LoadDependenciesOf Module
353 -- | Try to load the program. If a Module is supplied, then just
354 -- attempt to load up to this target. If no Module is supplied,
355 -- then try to load all targets.
356 load :: Session -> LoadHowMuch -> IO SuccessFlag
357 load s@(Session ref) how_much
359 -- Dependency analysis first. Note that this fixes the module graph:
360 -- even if we don't get a fully successful upsweep, the full module
361 -- graph is still retained in the Session. We can tell which modules
362 -- were successfully loaded by inspecting the Session's HPT.
365 hsc_env <- readIORef ref
367 let hpt1 = hsc_HPT hsc_env
368 let dflags = hsc_dflags hsc_env
369 let mod_graph = hsc_mod_graph hsc_env
371 let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
372 let verb = verbosity dflags
374 -- The "bad" boot modules are the ones for which we have
375 -- B.hs-boot in the module graph, but no B.hs
376 -- The downsweep should have ensured this does not happen
378 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
379 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
380 not (ms_mod s `elem` all_home_mods)]
381 ASSERT( null bad_boot_mods ) return ()
383 -- mg2_with_srcimps drops the hi-boot nodes, returning a
384 -- graph with cycles. Among other things, it is used for
385 -- backing out partially complete cycles following a failed
386 -- upsweep, and for removing from hpt all the modules
387 -- not in strict downwards closure, during calls to compile.
388 let mg2_with_srcimps :: [SCC ModSummary]
389 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
391 -- check the stability property for each module.
392 stable_mods@(stable_obj,stable_bco)
393 | BatchCompile <- ghci_mode = ([],[])
394 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
396 -- prune bits of the HPT which are definitely redundant now,
398 pruned_hpt = pruneHomePackageTable hpt1
399 (flattenSCCs mg2_with_srcimps)
405 putStrLn (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
406 text "Stable BCO:" <+> ppr stable_bco))
408 -- Unload any modules which are going to be re-linked this time around.
409 let stable_linkables = [ linkable
410 | m <- stable_obj++stable_bco,
411 Just hmi <- [lookupModuleEnv pruned_hpt m],
412 Just linkable <- [hm_linkable hmi] ]
413 unload hsc_env stable_linkables
415 -- We could at this point detect cycles which aren't broken by
416 -- a source-import, and complain immediately, but it seems better
417 -- to let upsweep_mods do this, so at least some useful work gets
418 -- done before the upsweep is abandoned.
419 --hPutStrLn stderr "after tsort:\n"
420 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
422 -- Now do the upsweep, calling compile for each module in
423 -- turn. Final result is version 3 of everything.
425 -- Topologically sort the module graph, this time including hi-boot
426 -- nodes, and possibly just including the portion of the graph
427 -- reachable from the module specified in the 2nd argument to load.
428 -- This graph should be cycle-free.
429 -- If we're restricting the upsweep to a portion of the graph, we
430 -- also want to retain everything that is still stable.
431 let full_mg :: [SCC ModSummary]
432 full_mg = topSortModuleGraph False mod_graph Nothing
434 maybe_top_mod = case how_much of
436 LoadDependenciesOf m -> Just m
439 partial_mg0 :: [SCC ModSummary]
440 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
442 -- LoadDependenciesOf m: we want the upsweep to stop just
443 -- short of the specified module (unless the specified module
446 | LoadDependenciesOf mod <- how_much
447 = ASSERT( case last partial_mg0 of
448 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
449 List.init partial_mg0
455 | AcyclicSCC ms <- full_mg,
456 ms_mod ms `elem` stable_obj++stable_bco,
457 ms_mod ms `notElem` [ ms_mod ms' |
458 AcyclicSCC ms' <- partial_mg ] ]
460 mg = stable_mg ++ partial_mg
462 -- clean up between compilations
463 let cleanup = cleanTempFilesExcept dflags
464 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
466 (upsweep_ok, hsc_env1, modsUpswept)
467 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
468 pruned_hpt stable_mods cleanup mg
470 -- Make modsDone be the summaries for each home module now
471 -- available; this should equal the domain of hpt3.
472 -- Get in in a roughly top .. bottom order (hence reverse).
474 let modsDone = reverse modsUpswept
476 -- Try and do linking in some form, depending on whether the
477 -- upsweep was completely or only partially successful.
479 if succeeded upsweep_ok
482 -- Easy; just relink it all.
483 do when (verb >= 2) $
484 hPutStrLn stderr "Upsweep completely successful."
486 -- Clean up after ourselves
487 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
489 -- Issue a warning for the confusing case where the user
490 -- said '-o foo' but we're not going to do any linking.
491 -- We attempt linking if either (a) one of the modules is
492 -- called Main, or (b) the user said -no-hs-main, indicating
493 -- that main() is going to come from somewhere else.
495 let ofile = outputFile dflags
496 let no_hs_main = dopt Opt_NoHsMain dflags
497 let mb_main_mod = mainModIs dflags
499 main_mod = mb_main_mod `orElse` "Main"
501 = any ((==main_mod).moduleUserString.ms_mod)
503 do_linking = a_root_is_Main || no_hs_main
505 when (ghci_mode == BatchCompile && isJust ofile && not do_linking
507 hPutStrLn stderr ("Warning: output was redirected with -o, " ++
508 "but no output will be generated\n" ++
509 "because there is no " ++ main_mod ++ " module.")
511 -- link everything together
512 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
514 loadFinish Succeeded linkresult ref hsc_env1
517 -- Tricky. We need to back out the effects of compiling any
518 -- half-done cycles, both so as to clean up the top level envs
519 -- and to avoid telling the interactive linker to link them.
520 do when (verb >= 2) $
521 hPutStrLn stderr "Upsweep partially successful."
524 = map ms_mod modsDone
525 let mods_to_zap_names
526 = findPartiallyCompletedCycles modsDone_names
529 = filter ((`notElem` mods_to_zap_names).ms_mod)
532 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
535 -- Clean up after ourselves
536 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
538 -- there should be no Nothings where linkables should be, now
539 ASSERT(all (isJust.hm_linkable)
540 (moduleEnvElts (hsc_HPT hsc_env))) do
542 -- Link everything together
543 linkresult <- link ghci_mode dflags False hpt4
545 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
546 loadFinish Failed linkresult ref hsc_env4
548 -- Finish up after a load.
550 -- If the link failed, unload everything and return.
551 loadFinish all_ok Failed ref hsc_env
552 = do unload hsc_env []
553 writeIORef ref $! discardProg hsc_env
556 -- Empty the interactive context and set the module context to the topmost
557 -- newly loaded module, or the Prelude if none were loaded.
558 loadFinish all_ok Succeeded ref hsc_env
559 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
563 -- Forget the current program, but retain the persistent info in HscEnv
564 discardProg :: HscEnv -> HscEnv
566 = hsc_env { hsc_mod_graph = emptyMG,
567 hsc_IC = emptyInteractiveContext,
568 hsc_HPT = emptyHomePackageTable }
570 -- used to fish out the preprocess output files for the purposes of
571 -- cleaning up. The preprocessed file *might* be the same as the
572 -- source file, but that doesn't do any harm.
573 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
575 -- -----------------------------------------------------------------------------
579 CheckedModule { parsedSource :: ParsedSource,
580 typecheckedSource :: Maybe TypecheckedSource
583 type ParsedSource = Located (HsModule RdrName)
584 type TypecheckedSource = (LHsBinds Id, GlobalRdrEnv)
586 -- | This is the way to get access to parsed and typechecked source code
587 -- for a module. 'checkModule' loads all the dependencies of the specified
588 -- module in the Session, and then attempts to typecheck the module. If
589 -- successful, it returns the abstract syntax for the module.
590 checkModule :: Session -> Module -> (Messages -> IO ())
591 -> IO (Maybe CheckedModule)
592 checkModule session@(Session ref) mod msg_act = do
593 -- load up the dependencies first
594 r <- load session (LoadDependenciesOf mod)
595 if (failed r) then return Nothing else do
597 -- now parse & typecheck the module
598 hsc_env <- readIORef ref
599 let mg = hsc_mod_graph hsc_env
600 case [ ms | ms <- mg, ms_mod ms == mod ] of
603 r <- hscFileCheck hsc_env msg_act ms
607 HscChecked parsed tcd ->
608 return (Just (CheckedModule parsed tcd) )
610 -----------------------------------------------------------------------------
613 unload :: HscEnv -> [Linkable] -> IO ()
614 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
615 = case ghcMode (hsc_dflags hsc_env) of
616 BatchCompile -> return ()
618 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
620 Interactive -> panic "unload: no interpreter"
622 other -> panic "unload: strange mode"
624 -- -----------------------------------------------------------------------------
628 Stability tells us which modules definitely do not need to be recompiled.
629 There are two main reasons for having stability:
631 - avoid doing a complete upsweep of the module graph in GHCi when
632 modules near the bottom of the tree have not changed.
634 - to tell GHCi when it can load object code: we can only load object code
635 for a module when we also load object code fo all of the imports of the
636 module. So we need to know that we will definitely not be recompiling
637 any of these modules, and we can use the object code.
639 NB. stability is of no importance to BatchCompile at all, only Interactive.
640 (ToDo: what about JustTypecheck?)
642 The stability check is as follows. Both stableObject and
643 stableBCO are used during the upsweep phase later.
646 stable m = stableObject m || stableBCO m
649 all stableObject (imports m)
650 && old linkable does not exist, or is == on-disk .o
651 && date(on-disk .o) > date(.hs)
654 all stable (imports m)
655 && date(BCO) > date(.hs)
658 These properties embody the following ideas:
660 - if a module is stable:
661 - if it has been compiled in a previous pass (present in HPT)
662 then it does not need to be compiled or re-linked.
663 - if it has not been compiled in a previous pass,
664 then we only need to read its .hi file from disk and
665 link it to produce a ModDetails.
667 - if a modules is not stable, we will definitely be at least
668 re-linking, and possibly re-compiling it during the upsweep.
669 All non-stable modules can (and should) therefore be unlinked
672 - Note that objects are only considered stable if they only depend
673 on other objects. We can't link object code against byte code.
677 :: HomePackageTable -- HPT from last compilation
678 -> [SCC ModSummary] -- current module graph (cyclic)
679 -> [Module] -- all home modules
680 -> ([Module], -- stableObject
681 [Module]) -- stableBCO
683 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
685 checkSCC (stable_obj, stable_bco) scc0
686 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
687 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
688 | otherwise = (stable_obj, stable_bco)
690 scc = flattenSCC scc0
691 scc_mods = map ms_mod scc
692 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
694 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
695 -- all imports outside the current SCC, but in the home pkg
697 stable_obj_imps = map (`elem` stable_obj) scc_allimps
698 stable_bco_imps = map (`elem` stable_bco) scc_allimps
705 and (zipWith (||) stable_obj_imps stable_bco_imps)
709 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
713 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
715 Just hmi | Just l <- hm_linkable hmi
716 -> isObjectLinkable l && t == linkableTime l
717 -- why '>=' rather than '>' above? If the filesystem stores
718 -- times to the nearset second, we may occasionally find that
719 -- the object & source have the same modification time,
720 -- especially if the source was automatically generated
721 -- and compiled. Using >= is slightly unsafe, but it matches
725 = case lookupModuleEnv hpt (ms_mod ms) of
727 Just hmi | Just l <- hm_linkable hmi ->
728 not (isObjectLinkable l) &&
729 linkableTime l >= ms_hs_date ms
731 ms_allimps :: ModSummary -> [Module]
732 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
734 -- -----------------------------------------------------------------------------
735 -- Prune the HomePackageTable
737 -- Before doing an upsweep, we can throw away:
739 -- - For non-stable modules:
740 -- - all ModDetails, all linked code
741 -- - all unlinked code that is out of date with respect to
744 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
745 -- space at the end of the upsweep, because the topmost ModDetails of the
746 -- old HPT holds on to the entire type environment from the previous
749 pruneHomePackageTable
752 -> ([Module],[Module])
755 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
756 = mapModuleEnv prune hpt
758 | is_stable modl = hmi'
759 | otherwise = hmi'{ hm_details = emptyModDetails }
761 modl = mi_module (hm_iface hmi)
762 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
763 = hmi{ hm_linkable = Nothing }
766 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
768 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
770 is_stable m = m `elem` stable_obj || m `elem` stable_bco
772 -- -----------------------------------------------------------------------------
774 -- Return (names of) all those in modsDone who are part of a cycle
775 -- as defined by theGraph.
776 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
777 findPartiallyCompletedCycles modsDone theGraph
781 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
782 chew ((CyclicSCC vs):rest)
783 = let names_in_this_cycle = nub (map ms_mod vs)
785 = nub ([done | done <- modsDone,
786 done `elem` names_in_this_cycle])
787 chewed_rest = chew rest
789 if notNull mods_in_this_cycle
790 && length mods_in_this_cycle < length names_in_this_cycle
791 then mods_in_this_cycle ++ chewed_rest
794 -- -----------------------------------------------------------------------------
797 -- This is where we compile each module in the module graph, in a pass
798 -- from the bottom to the top of the graph.
800 -- There better had not be any cyclic groups here -- we check for them.
803 :: HscEnv -- Includes initially-empty HPT
804 -> HomePackageTable -- HPT from last time round (pruned)
805 -> ([Module],[Module]) -- stable modules (see checkStability)
806 -> IO () -- How to clean up unwanted tmp files
807 -> [SCC ModSummary] -- Mods to do (the worklist)
809 HscEnv, -- With an updated HPT
810 [ModSummary]) -- Mods which succeeded
812 upsweep hsc_env old_hpt stable_mods cleanup
814 = return (Succeeded, hsc_env, [])
816 upsweep hsc_env old_hpt stable_mods cleanup
818 = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
819 return (Failed, hsc_env, [])
821 upsweep hsc_env old_hpt stable_mods cleanup
822 (AcyclicSCC mod:mods)
823 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
824 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
825 -- (moduleEnvElts (hsc_HPT hsc_env)))
827 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
829 cleanup -- Remove unwanted tmp files between compilations
832 Nothing -> return (Failed, hsc_env, [])
834 { let this_mod = ms_mod mod
836 -- Add new info to hsc_env
837 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
839 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
841 -- Space-saving: delete the old HPT entry
842 -- for mod BUT if mod is a hs-boot
843 -- node, don't delete it. For the
844 -- interface, the HPT entry is probaby for the
845 -- main Haskell source file. Deleting it
846 -- would force .. (what?? --SDM)
847 old_hpt1 | isBootSummary mod = old_hpt
848 | otherwise = delModuleEnv old_hpt this_mod
850 ; (restOK, hsc_env2, modOKs)
851 <- upsweep hsc_env1 old_hpt1 stable_mods cleanup mods
852 ; return (restOK, hsc_env2, mod:modOKs)
856 -- Compile a single module. Always produce a Linkable for it if
857 -- successful. If no compilation happened, return the old Linkable.
858 upsweep_mod :: HscEnv
860 -> ([Module],[Module])
862 -> IO (Maybe HomeModInfo) -- Nothing => Failed
864 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary
867 this_mod = ms_mod summary
868 mb_obj_date = ms_obj_date summary
869 obj_fn = ml_obj_file (ms_location summary)
870 hs_date = ms_hs_date summary
872 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
873 compile_it = upsweep_compile hsc_env old_hpt this_mod summary
875 case ghcMode (hsc_dflags hsc_env) of
878 -- Batch-compilating is easy: just check whether we have
879 -- an up-to-date object file. If we do, then the compiler
880 -- needs to do a recompilation check.
881 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
883 findObjectLinkable this_mod obj_fn obj_date
884 compile_it (Just linkable)
891 _ | is_stable_obj, isJust old_hmi ->
893 -- object is stable, and we have an entry in the
894 -- old HPT: nothing to do
896 | is_stable_obj, isNothing old_hmi -> do
898 findObjectLinkable this_mod obj_fn
899 (expectJust "upseep1" mb_obj_date)
900 compile_it (Just linkable)
901 -- object is stable, but we need to load the interface
902 -- off disk to make a HMI.
905 ASSERT(isJust old_hmi) -- must be in the old_hpt
907 -- BCO is stable: nothing to do
909 | Just hmi <- old_hmi,
910 Just l <- hm_linkable hmi, not (isObjectLinkable l),
911 linkableTime l >= ms_hs_date summary ->
913 -- we have an old BCO that is up to date with respect
914 -- to the source: do a recompilation check as normal.
918 -- no existing code at all: we must recompile.
920 is_stable_obj = this_mod `elem` stable_obj
921 is_stable_bco = this_mod `elem` stable_bco
923 old_hmi = lookupModuleEnv old_hpt this_mod
925 -- Run hsc to compile a module
926 upsweep_compile hsc_env old_hpt this_mod summary mb_old_linkable = do
928 -- The old interface is ok if it's in the old HPT
929 -- a) we're compiling a source file, and the old HPT
930 -- entry is for a source file
931 -- b) we're compiling a hs-boot file
932 -- Case (b) allows an hs-boot file to get the interface of its
933 -- real source file on the second iteration of the compilation
934 -- manager, but that does no harm. Otherwise the hs-boot file
935 -- will always be recompiled
938 = case lookupModuleEnv old_hpt this_mod of
940 Just hm_info | isBootSummary summary -> Just iface
941 | not (mi_boot iface) -> Just iface
942 | otherwise -> Nothing
944 iface = hm_iface hm_info
946 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
949 -- Compilation failed. Compile may still have updated the PCS, tho.
950 CompErrs -> return Nothing
952 -- Compilation "succeeded", and may or may not have returned a new
953 -- linkable (depending on whether compilation was actually performed
955 CompOK new_details new_iface new_linkable
956 -> do let new_info = HomeModInfo { hm_iface = new_iface,
957 hm_details = new_details,
958 hm_linkable = new_linkable }
959 return (Just new_info)
962 -- Filter modules in the HPT
963 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
964 retainInTopLevelEnvs keep_these hpt
965 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
967 , let mb_mod_info = lookupModuleEnv hpt mod
968 , isJust mb_mod_info ]
970 -- ---------------------------------------------------------------------------
971 -- Topological sort of the module graph
974 :: Bool -- Drop hi-boot nodes? (see below)
978 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
980 -- Drop hi-boot nodes (first boolean arg)?
982 -- False: treat the hi-boot summaries as nodes of the graph,
983 -- so the graph must be acyclic
985 -- True: eliminate the hi-boot nodes, and instead pretend
986 -- the a source-import of Foo is an import of Foo
987 -- The resulting graph has no hi-boot nodes, but can by cyclic
989 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
990 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
991 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
992 = stronglyConnComp (map vertex_fn (reachable graph root))
994 -- restrict the graph to just those modules reachable from
995 -- the specified module. We do this by building a graph with
996 -- the full set of nodes, and determining the reachable set from
997 -- the specified node.
998 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
999 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1001 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1002 | otherwise = throwDyn (ProgramError "module does not exist")
1004 moduleGraphNodes :: Bool -> [ModSummary]
1005 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1006 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1008 -- Drop hs-boot nodes by using HsSrcFile as the key
1009 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1010 | otherwise = HsBootFile
1012 -- We use integers as the keys for the SCC algorithm
1013 nodes :: [(ModSummary, Int, [Int])]
1014 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1015 out_edge_keys hs_boot_key (ms_srcimps s) ++
1016 out_edge_keys HsSrcFile (ms_imps s) )
1018 , not (isBootSummary s && drop_hs_boot_nodes) ]
1019 -- Drop the hi-boot ones if told to do so
1021 key_map :: NodeMap Int
1022 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1025 lookup_key :: HscSource -> Module -> Maybe Int
1026 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1028 out_edge_keys :: HscSource -> [Module] -> [Int]
1029 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1030 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1031 -- the IsBootInterface parameter True; else False
1034 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1035 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1037 msKey :: ModSummary -> NodeKey
1038 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1040 emptyNodeMap :: NodeMap a
1041 emptyNodeMap = emptyFM
1043 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1044 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1046 nodeMapElts :: NodeMap a -> [a]
1047 nodeMapElts = eltsFM
1049 -- -----------------------------------------------------------------
1050 -- The unlinked image
1052 -- The compilation manager keeps a list of compiled, but as-yet unlinked
1053 -- binaries (byte code or object code). Even when it links bytecode
1054 -- it keeps the unlinked version so it can re-link it later without
1057 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
1059 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
1060 findModuleLinkable_maybe lis mod
1061 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
1064 many -> pprPanic "findModuleLinkable" (ppr mod)
1066 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1067 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1069 -----------------------------------------------------------------------------
1070 -- Downsweep (dependency analysis)
1072 -- Chase downwards from the specified root set, returning summaries
1073 -- for all home modules encountered. Only follow source-import
1076 -- We pass in the previous collection of summaries, which is used as a
1077 -- cache to avoid recalculating a module summary if the source is
1080 -- The returned list of [ModSummary] nodes has one node for each home-package
1081 -- module, plus one for any hs-boot files. The imports of these nodes
1082 -- are all there, including the imports of non-home-package modules.
1085 -> [ModSummary] -- Old summaries
1086 -> [Module] -- Ignore dependencies on these; treat them as
1087 -- if they were package modules
1089 downsweep hsc_env old_summaries excl_mods
1090 = do rootSummaries <- mapM getRootSummary roots
1091 checkDuplicates rootSummaries
1092 loop (concatMap msDeps rootSummaries)
1093 (mkNodeMap rootSummaries)
1095 roots = hsc_targets hsc_env
1097 old_summary_map :: NodeMap ModSummary
1098 old_summary_map = mkNodeMap old_summaries
1100 getRootSummary :: Target -> IO ModSummary
1101 getRootSummary (Target (TargetFile file) maybe_buf)
1102 = do exists <- doesFileExist file
1103 if exists then summariseFile hsc_env file maybe_buf else do
1104 throwDyn (CmdLineError ("can't find file: " ++ file))
1105 getRootSummary (Target (TargetModule modl) maybe_buf)
1106 = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False
1107 modl maybe_buf excl_mods
1108 case maybe_summary of
1109 Nothing -> packageModErr modl
1112 -- In a root module, the filename is allowed to diverge from the module
1113 -- name, so we have to check that there aren't multiple root files
1114 -- defining the same module (otherwise the duplicates will be silently
1115 -- ignored, leading to confusing behaviour).
1116 checkDuplicates :: [ModSummary] -> IO ()
1117 checkDuplicates summaries = mapM_ check summaries
1122 many -> multiRootsErr modl many
1123 where modl = ms_mod summ
1125 [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1126 | summ' <- summaries, ms_mod summ' == modl ]
1128 loop :: [(FilePath,Module,IsBootInterface)]
1129 -- Work list: process these modules
1130 -> NodeMap ModSummary
1133 -- The result includes the worklist, except
1134 -- for those mentioned in the visited set
1135 loop [] done = return (nodeMapElts done)
1136 loop ((cur_path, wanted_mod, is_boot) : ss) done
1137 | key `elemFM` done = loop ss done
1138 | otherwise = do { mb_s <- summarise hsc_env old_summary_map
1139 (Just cur_path) is_boot
1140 wanted_mod Nothing excl_mods
1142 Nothing -> loop ss done
1143 Just s -> loop (msDeps s ++ ss)
1144 (addToFM done key s) }
1146 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1148 msDeps :: ModSummary -> [(FilePath, -- Importing module
1149 Module, -- Imported module
1150 IsBootInterface)] -- {-# SOURCE #-} import or not
1151 -- (msDeps s) returns the dependencies of the ModSummary s.
1152 -- A wrinkle is that for a {-# SOURCE #-} import we return
1153 -- *both* the hs-boot file
1154 -- *and* the source file
1155 -- as "dependencies". That ensures that the list of all relevant
1156 -- modules always contains B.hs if it contains B.hs-boot.
1157 -- Remember, this pass isn't doing the topological sort. It's
1158 -- just gathering the list of all relevant ModSummaries
1159 msDeps s = concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s]
1160 ++ [(f,m,False) | m <- ms_imps s]
1162 f = msHsFilePath s -- Keep the importing module for error reporting
1165 -----------------------------------------------------------------------------
1166 -- Summarising modules
1168 -- We have two types of summarisation:
1170 -- * Summarise a file. This is used for the root module(s) passed to
1171 -- cmLoadModules. The file is read, and used to determine the root
1172 -- module name. The module name may differ from the filename.
1174 -- * Summarise a module. We are given a module name, and must provide
1175 -- a summary. The finder is used to locate the file in which the module
1178 summariseFile :: HscEnv -> FilePath
1179 -> Maybe (StringBuffer,ClockTime)
1181 -- Used for Haskell source only, I think
1182 -- We know the file name, and we know it exists,
1183 -- but we don't necessarily know the module name (might differ)
1184 summariseFile hsc_env file maybe_buf
1185 = do let dflags = hsc_dflags hsc_env
1187 (dflags', hspp_fn, buf)
1188 <- preprocessFile dflags file maybe_buf
1190 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1192 -- Make a ModLocation for this file
1193 location <- mkHomeModLocation dflags mod file
1195 -- Tell the Finder cache where it is, so that subsequent calls
1196 -- to findModule will find it, even if it's not on any search path
1197 addHomeModuleToFinder hsc_env mod location
1199 src_timestamp <- case maybe_buf of
1200 Just (_,t) -> return t
1201 Nothing -> getModificationTime file
1203 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1205 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1206 ms_location = location,
1207 ms_hspp_file = Just hspp_fn,
1208 ms_hspp_buf = Just buf,
1209 ms_srcimps = srcimps, ms_imps = the_imps,
1210 ms_hs_date = src_timestamp,
1211 ms_obj_date = obj_timestamp })
1213 -- Summarise a module, and pick up source and timestamp.
1215 -> NodeMap ModSummary -- Map of old summaries
1216 -> Maybe FilePath -- Importing module (for error messages)
1217 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1218 -> Module -- Imported module to be summarised
1219 -> Maybe (StringBuffer, ClockTime)
1220 -> [Module] -- Modules to exclude
1221 -> IO (Maybe ModSummary) -- Its new summary
1223 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1224 | wanted_mod `elem` excl_mods
1227 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1228 = do -- Find its new timestamp; all the
1229 -- ModSummaries in the old map have valid ml_hs_files
1230 let location = ms_location old_summary
1231 src_fn = expectJust "summarise" (ml_hs_file location)
1233 -- return the cached summary if the source didn't change
1234 src_timestamp <- case maybe_buf of
1235 Just (_,t) -> return t
1236 Nothing -> getModificationTime src_fn
1238 if ms_hs_date old_summary == src_timestamp
1239 then do -- update the object-file timestamp
1240 obj_timestamp <- getObjTimestamp location is_boot
1241 return (Just old_summary{ ms_obj_date = obj_timestamp })
1243 -- source changed: re-summarise
1244 new_summary location src_fn maybe_buf src_timestamp
1247 = do found <- findModule hsc_env wanted_mod True {-explicit-}
1250 | not (isHomePackage pkg) -> return Nothing
1251 -- Drop external-pkg
1252 | isJust (ml_hs_file location) -> just_found location
1254 err -> noModError dflags cur_mod wanted_mod err
1257 dflags = hsc_dflags hsc_env
1259 hsc_src = if is_boot then HsBootFile else HsSrcFile
1261 just_found location = do
1262 -- Adjust location to point to the hs-boot source file,
1263 -- hi file, object file, when is_boot says so
1264 let location' | is_boot = addBootSuffixLocn location
1265 | otherwise = location
1266 src_fn = expectJust "summarise2" (ml_hs_file location')
1268 -- Check that it exists
1269 -- It might have been deleted since the Finder last found it
1270 maybe_t <- modificationTimeIfExists src_fn
1272 Nothing -> noHsFileErr cur_mod src_fn
1273 Just t -> new_summary location' src_fn Nothing t
1276 new_summary location src_fn maybe_bug src_timestamp
1278 -- Preprocess the source file and get its imports
1279 -- The dflags' contains the OPTIONS pragmas
1280 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1281 (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1283 when (mod_name /= wanted_mod) $
1284 throwDyn (ProgramError
1285 (showSDoc (text src_fn
1286 <> text ": file name does not match module name"
1287 <+> quotes (ppr mod_name))))
1289 -- Find the object timestamp, and return the summary
1290 obj_timestamp <- getObjTimestamp location is_boot
1292 return (Just ( ModSummary { ms_mod = wanted_mod,
1293 ms_hsc_src = hsc_src,
1294 ms_location = location,
1295 ms_hspp_file = Just hspp_fn,
1296 ms_hspp_buf = Just buf,
1297 ms_srcimps = srcimps,
1299 ms_hs_date = src_timestamp,
1300 ms_obj_date = obj_timestamp }))
1303 getObjTimestamp location is_boot
1304 = if is_boot then return Nothing
1305 else modificationTimeIfExists (ml_obj_file location)
1308 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1309 -> IO (DynFlags, FilePath, StringBuffer)
1310 preprocessFile dflags src_fn Nothing
1312 (dflags', hspp_fn) <- preprocess dflags src_fn
1313 buf <- hGetStringBuffer hspp_fn
1314 return (dflags', hspp_fn, buf)
1316 preprocessFile dflags src_fn (Just (buf, time))
1318 -- case we bypass the preprocessing stage?
1320 local_opts = getOptionsFromStringBuffer buf
1322 (dflags', errs) <- parseDynamicFlags dflags local_opts
1326 | Unlit _ <- startPhase src_fn = True
1327 -- note: local_opts is only required if there's no Unlit phase
1328 | dopt Opt_Cpp dflags' = True
1329 | dopt Opt_Pp dflags' = True
1332 when needs_preprocessing $
1333 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1335 return (dflags', "<buffer>", buf)
1338 -- code adapted from the file-based version in DriverUtil
1339 getOptionsFromStringBuffer :: StringBuffer -> [String]
1340 getOptionsFromStringBuffer buffer@(StringBuffer _ len# _) =
1342 ls = lines (lexemeToString buffer (I# len#)) -- lazy, so it's ok
1348 let l = removeSpaces l'
1350 () | null l -> look ls
1351 | prefixMatch "#" l -> look ls
1352 | prefixMatch "{-# LINE" l -> look ls -- -}
1353 | Just opts <- matchOptions l
1357 -----------------------------------------------------------------------------
1359 -----------------------------------------------------------------------------
1361 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1362 -- ToDo: we don't have a proper line number for this error
1363 noModError dflags cur_mod wanted_mod err
1364 = throwDyn $ ProgramError $ showSDoc $
1365 vcat [cantFindError dflags wanted_mod err,
1366 nest 2 (parens (pp_where cur_mod))]
1368 noHsFileErr cur_mod path
1369 = throwDyn $ CmdLineError $ showSDoc $
1370 vcat [text "Can't find" <+> text path,
1371 nest 2 (parens (pp_where cur_mod))]
1373 pp_where Nothing = text "one of the roots of the dependency analysis"
1374 pp_where (Just p) = text "imported from" <+> text p
1377 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1378 quotes (ppr mod) <+>
1379 text "is a package module")))
1381 multiRootsErr mod files
1382 = throwDyn (ProgramError (showSDoc (
1383 text "module" <+> quotes (ppr mod) <+>
1384 text "is defined in multiple files:" <+>
1385 sep (map text files))))
1387 cyclicModuleErr :: [ModSummary] -> SDoc
1389 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1390 2 (vcat (map show_one ms))
1392 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1393 nest 2 $ ptext SLIT("imports:") <+>
1394 (pp_imps HsBootFile (ms_srcimps ms)
1395 $$ pp_imps HsSrcFile (ms_imps ms))]
1396 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1397 pp_imps src mods = fsep (map (show_mod src) mods)
1400 -- | Inform GHC that the working directory has changed. GHC will flush
1401 -- its cache of module locations, since it may no longer be valid.
1402 -- Note: if you change the working directory, you should also unload
1403 -- the current program (set targets to empty, followed by load).
1404 workingDirectoryChanged :: Session -> IO ()
1405 workingDirectoryChanged s = withSession s $ \hsc_env ->
1406 flushFinderCache (hsc_FC hsc_env)
1408 -- -----------------------------------------------------------------------------
1409 -- inspecting the session
1411 -- | Get the module dependency graph.
1412 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1413 getModuleGraph s = withSession s (return . hsc_mod_graph)
1415 isLoaded :: Session -> Module -> IO Bool
1416 isLoaded s m = withSession s $ \hsc_env ->
1417 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1419 getBindings :: Session -> IO [TyThing]
1420 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1422 getPrintUnqual :: Session -> IO PrintUnqualified
1423 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1426 getModuleInfo :: Session -> Module -> IO ModuleInfo
1430 | BinaryCode FilePath
1432 data ModuleInfo = ModuleInfo {
1433 lm_modulename :: Module,
1434 lm_summary :: ModSummary,
1435 lm_interface :: ModIface,
1436 lm_tc_code :: Maybe TypecheckedCode,
1437 lm_rn_code :: Maybe RenamedCode,
1438 lm_obj :: Maybe ObjectCode
1441 type TypecheckedCode = HsTypecheckedGroup
1442 type RenamedCode = [HsGroup Name]
1444 -- ToDo: typechecks abstract syntax or renamed abstract syntax. Issues:
1445 -- - typechecked syntax includes extra dictionary translation and
1446 -- AbsBinds which need to be translated back into something closer to
1447 -- the original source.
1448 -- - renamed syntax currently doesn't exist in a single blob, since
1449 -- renaming and typechecking are interleaved at splice points. We'd
1450 -- need a restriction that there are no splices in the source module.
1453 -- - Data and Typeable instances for HsSyn.
1456 -- - things that aren't in the output of the renamer:
1457 -- - the export list
1461 -- - things that aren't in the output of the typechecker right now:
1462 -- - the export list
1464 -- - type signatures
1465 -- - type/data/newtype declarations
1466 -- - class declarations
1468 -- - extra things in the typechecker's output:
1469 -- - default methods are turned into top-level decls.
1470 -- - dictionary bindings
1472 -- ToDo: check for small transformations that happen to the syntax in
1473 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1475 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1476 -- to get from TyCons, Ids etc. to TH syntax (reify).
1478 -- :browse will use either lm_toplev or inspect lm_interface, depending
1479 -- on whether the module is interpreted or not.
1481 -- various abstract syntax types (perhaps IfaceBlah)
1485 -- This is for reconstructing refactored source code
1486 -- Calls the lexer repeatedly.
1487 -- ToDo: add comment tokens to token stream
1488 getTokenStream :: Session -> Module -> IO [Located Token]
1491 -- -----------------------------------------------------------------------------
1492 -- Interactive evaluation
1496 -- | Set the interactive evaluation context.
1498 -- Setting the context doesn't throw away any bindings; the bindings
1499 -- we've built up in the InteractiveContext simply move to the new
1500 -- module. They always shadow anything in scope in the current context.
1501 setContext :: Session
1502 -> [Module] -- entire top level scope of these modules
1503 -> [Module] -- exports only of these modules
1505 setContext (Session ref) toplevs exports = do
1506 hsc_env <- readIORef ref
1507 let old_ic = hsc_IC hsc_env
1508 hpt = hsc_HPT hsc_env
1510 mapM_ (checkModuleExists hsc_env hpt) exports
1511 export_env <- mkExportEnv hsc_env exports
1512 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1513 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1514 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1515 ic_exports = exports,
1516 ic_rn_gbl_env = all_env } }
1518 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1519 checkModuleExists hsc_env hpt mod =
1520 case lookupModuleEnv hpt mod of
1521 Just mod_info -> return ()
1522 _not_a_home_module -> do
1523 res <- findPackageModule hsc_env mod True
1525 Found _ _ -> return ()
1526 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1527 throwDyn (CmdLineError (showSDoc msg))
1529 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1530 mkTopLevEnv hpt modl
1531 = case lookupModuleEnv hpt modl of
1533 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1534 ++ showSDoc (pprModule modl)))
1536 case mi_globals (hm_iface details) of
1538 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1539 ++ showSDoc (pprModule modl)))
1540 Just env -> return env
1542 -- | Get the interactive evaluation context, consisting of a pair of the
1543 -- set of modules from which we take the full top-level scope, and the set
1544 -- of modules from which we take just the exports respectively.
1545 getContext :: Session -> IO ([Module],[Module])
1546 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1547 return (ic_toplev_scope ic, ic_exports ic))
1549 -- | Returns 'True' if the specified module is interpreted, and hence has
1550 -- its full top-level scope available.
1551 moduleIsInterpreted :: Session -> Module -> IO Bool
1552 moduleIsInterpreted s modl = withSession s $ \h ->
1553 case lookupModuleEnv (hsc_HPT h) modl of
1554 Just details -> return (isJust (mi_globals (hm_iface details)))
1555 _not_a_home_module -> return False
1557 -- | Looks up an identifier in the current interactive context (for :info)
1558 getInfo :: Session -> String -> IO [GetInfoResult]
1559 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1561 -- -----------------------------------------------------------------------------
1562 -- Getting the type of an expression
1564 -- | Get the type of an expression
1565 exprType :: Session -> String -> IO (Maybe Type)
1566 exprType s expr = withSession s $ \hsc_env -> do
1567 maybe_stuff <- hscTcExpr hsc_env expr
1569 Nothing -> return Nothing
1570 Just ty -> return (Just tidy_ty)
1572 tidy_ty = tidyType emptyTidyEnv ty
1573 dflags = hsc_dflags hsc_env
1575 -- -----------------------------------------------------------------------------
1576 -- Getting the kind of a type
1578 -- | Get the kind of a type
1579 typeKind :: Session -> String -> IO (Maybe Kind)
1580 typeKind s str = withSession s $ \hsc_env -> do
1581 maybe_stuff <- hscKcType hsc_env str
1583 Nothing -> return Nothing
1584 Just kind -> return (Just kind)
1586 -----------------------------------------------------------------------------
1587 -- lookupName: returns the TyThing for a Name in the interactive context.
1588 -- ToDo: should look it up in the full environment
1590 lookupName :: Session -> Name -> IO (Maybe TyThing)
1591 lookupName s name = withSession s $ \hsc_env -> do
1592 return $! lookupNameEnv (ic_type_env (hsc_IC hsc_env)) name
1594 -----------------------------------------------------------------------------
1595 -- cmCompileExpr: compile an expression and deliver an HValue
1597 compileExpr :: Session -> String -> IO (Maybe HValue)
1598 compileExpr s expr = withSession s $ \hsc_env -> do
1599 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1601 Nothing -> return Nothing
1602 Just (new_ic, names, hval) -> do
1604 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1606 case (names,hvals) of
1607 ([n],[hv]) -> return (Just hv)
1608 _ -> panic "compileExpr"
1610 -- -----------------------------------------------------------------------------
1611 -- running a statement interactively
1614 = RunOk [Name] -- ^ names bound by this evaluation
1615 | RunFailed -- ^ statement failed compilation
1616 | RunException Exception -- ^ statement raised an exception
1618 -- | Run a statement in the current interactive context. Statemenet
1619 -- may bind multple values.
1620 runStmt :: Session -> String -> IO RunResult
1621 runStmt (Session ref) expr
1623 hsc_env <- readIORef ref
1625 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1626 -- warnings about the implicit bindings we introduce.
1627 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1628 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1630 maybe_stuff <- hscStmt hsc_env' expr
1633 Nothing -> return RunFailed
1634 Just (new_hsc_env, names, hval) -> do
1636 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1637 either_hvals <- sandboxIO thing_to_run
1639 case either_hvals of
1641 -- on error, keep the *old* interactive context,
1642 -- so that 'it' is not bound to something
1643 -- that doesn't exist.
1644 return (RunException e)
1647 -- Get the newly bound things, and bind them.
1648 -- Don't need to delete any shadowed bindings;
1649 -- the new ones override the old ones.
1650 extendLinkEnv (zip names hvals)
1652 writeIORef ref new_hsc_env
1653 return (RunOk names)
1656 -- We run the statement in a "sandbox" to protect the rest of the
1657 -- system from anything the expression might do. For now, this
1658 -- consists of just wrapping it in an exception handler, but see below
1659 -- for another version.
1661 sandboxIO :: IO a -> IO (Either Exception a)
1662 sandboxIO thing = Exception.try thing
1665 -- This version of sandboxIO runs the expression in a completely new
1666 -- RTS main thread. It is disabled for now because ^C exceptions
1667 -- won't be delivered to the new thread, instead they'll be delivered
1668 -- to the (blocked) GHCi main thread.
1670 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1672 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1673 sandboxIO thing = do
1674 st_thing <- newStablePtr (Exception.try thing)
1675 alloca $ \ p_st_result -> do
1676 stat <- rts_evalStableIO st_thing p_st_result
1677 freeStablePtr st_thing
1679 then do st_result <- peek p_st_result
1680 result <- deRefStablePtr st_result
1681 freeStablePtr st_result
1682 return (Right result)
1684 return (Left (fromIntegral stat))
1686 foreign import "rts_evalStableIO" {- safe -}
1687 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1688 -- more informative than the C type!
1691 -- ---------------------------------------------------------------------------
1692 -- cmBrowseModule: get all the TyThings defined in a module
1694 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1695 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1696 mb_decls <- getModuleContents hsc_env modl exports_only
1698 Nothing -> return [] -- An error of some kind
1699 Just ds -> return ds
1702 -----------------------------------------------------------------------------
1703 -- show a module and it's source/object filenames
1705 showModule :: Session -> ModSummary -> IO String
1706 showModule s mod_summary = withSession s $ \hsc_env -> do
1707 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1708 Nothing -> panic "missing linkable"
1709 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1711 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))