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(..),
42 -- * Interactive evaluation
43 getBindings, getPrintUnqual,
45 setContext, getContext,
47 getInfo, GetInfoResult,
58 -- * Abstract syntax elements
59 Module, mkModule, pprModule,
62 Name, Id, TyCon, Class, DataCon,
66 -- used by DriverMkDepend:
74 * return error messages rather than printing them.
75 * inline bits of HscMain here to simplify layering: hscGetInfo,
77 * implement second argument to load.
78 * we need to expose DynFlags, so should parseDynamicFlags really be
79 part of this interface?
80 * what StaticFlags should we expose, if any?
83 #include "HsVersions.h"
86 import qualified Linker
87 import Linker ( HValue, extendLinkEnv )
88 import NameEnv ( lookupNameEnv )
89 import TcRnDriver ( mkExportEnv, getModuleContents )
90 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
91 import HscMain ( hscGetInfo, GetInfoResult,
92 hscStmt, hscTcExpr, hscKcType )
93 import Type ( tidyType )
94 import VarEnv ( emptyTidyEnv )
95 import GHC.Exts ( unsafeCoerce# )
96 import IfaceSyn ( IfaceDecl )
99 import Type ( Kind, Type, dropForAlls )
100 import Id ( Id, idType )
101 import TyCon ( TyCon )
102 import Class ( Class )
103 import DataCon ( DataCon )
105 import NameEnv ( nameEnvElts )
106 import DriverPipeline
107 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
108 import GetImports ( getImports )
109 import Packages ( isHomePackage )
111 import HscMain ( newHscEnv )
115 import SysTools ( initSysTools, cleanTempFiles )
120 import ErrUtils ( showPass )
121 import qualified ErrUtils
123 import StringBuffer ( StringBuffer(..), hGetStringBuffer, lexemeToString )
125 import SysTools ( cleanTempFilesExcept )
126 import BasicTypes ( SuccessFlag(..), succeeded )
127 import Maybes ( orElse, expectJust, mapCatMaybes )
129 import Directory ( getModificationTime, doesFileExist )
130 import Maybe ( isJust, isNothing, fromJust )
131 import Maybes ( expectJust )
132 import List ( partition, nub )
133 import Monad ( unless, when, foldM )
134 import System ( exitWith, ExitCode(..) )
135 import Time ( ClockTime )
136 import EXCEPTION as Exception hiding (handle)
137 import GLAEXTS ( Int(..) )
140 import Prelude hiding (init)
142 -- -----------------------------------------------------------------------------
143 -- Exception handlers
145 -- | Install some default exception handlers and run the inner computation.
146 -- Unless you want to handle exceptions yourself, you should wrap this around
147 -- the top level of your program. The default handlers output the error
148 -- message(s) to stderr and exit cleanly.
149 defaultErrorHandler :: IO a -> IO a
150 defaultErrorHandler inner =
151 -- top-level exception handler: any unrecognised exception is a compiler bug.
152 handle (\exception -> do
155 -- an IO exception probably isn't our fault, so don't panic
156 IOException _ -> hPutStrLn stderr (show exception)
157 AsyncException StackOverflow ->
158 hPutStrLn stderr "stack overflow: use +RTS -K<size> to increase it"
159 _other -> hPutStr stderr (show (Panic (show exception)))
160 exitWith (ExitFailure 1)
163 -- all error messages are propagated as exceptions
164 handleDyn (\dyn -> do
167 PhaseFailed _ code -> exitWith code
168 Interrupted -> exitWith (ExitFailure 1)
169 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
170 exitWith (ExitFailure 1)
174 -- | Install a default cleanup handler to remove temporary files
175 -- deposited by a GHC run. This is seperate from
176 -- 'defaultErrorHandler', because you might want to override the error
177 -- handling, but still get the ordinary cleanup behaviour.
178 defaultCleanupHandler :: DynFlags -> IO a -> IO a
179 defaultCleanupHandler dflags inner =
180 -- make sure we clean up after ourselves
181 later (unless (dopt Opt_KeepTmpFiles dflags) $
182 cleanTempFiles dflags)
183 -- exceptions will be blocked while we clean the temporary files,
184 -- so there shouldn't be any difficulty if we receive further
189 -- | Initialises GHC. This must be done /once/ only. Takes the
190 -- command-line arguments. All command-line arguments which aren't
191 -- understood by GHC will be returned.
193 init :: [String] -> IO [String]
196 installSignalHandlers
198 -- Grab the -B option if there is one
199 let (minusB_args, argv1) = partition (prefixMatch "-B") args
200 dflags0 <- initSysTools minusB_args defaultDynFlags
201 writeIORef v_initDynFlags dflags0
203 -- Parse the static flags
204 argv2 <- parseStaticFlags argv1
207 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
208 -- stores the DynFlags between the call to init and subsequent
209 -- calls to newSession.
211 -- | Starts a new session. A session consists of a set of loaded
212 -- modules, a set of options (DynFlags), and an interactive context.
213 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
215 newSession :: GhcMode -> IO Session
217 dflags0 <- readIORef v_initDynFlags
218 dflags <- initDynFlags dflags0
219 env <- newHscEnv dflags{ ghcMode=mode }
223 -- tmp: this breaks the abstraction, but required because DriverMkDepend
224 -- needs to call the Finder. ToDo: untangle this.
225 sessionHscEnv :: Session -> IO HscEnv
226 sessionHscEnv (Session ref) = readIORef ref
228 withSession :: Session -> (HscEnv -> IO a) -> IO a
229 withSession (Session ref) f = do h <- readIORef ref; f h
231 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
232 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
234 -- -----------------------------------------------------------------------------
237 -- | Grabs the DynFlags from the Session
238 getSessionDynFlags :: Session -> IO DynFlags
239 getSessionDynFlags s = withSession s (return . hsc_dflags)
241 -- | Updates the DynFlags in a Session
242 setSessionDynFlags :: Session -> DynFlags -> IO ()
243 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
245 -- | Messages during compilation (eg. warnings and progress messages)
246 -- are reported using this callback. By default, these messages are
247 -- printed to stderr.
248 setMsgHandler :: (String -> IO ()) -> IO ()
249 setMsgHandler = ErrUtils.setMsgHandler
251 -- -----------------------------------------------------------------------------
254 -- ToDo: think about relative vs. absolute file paths. And what
255 -- happens when the current directory changes.
257 -- | Sets the targets for this session. Each target may be a module name
258 -- or a filename. The targets correspond to the set of root modules for
259 -- the program\/library. Unloading the current program is achieved by
260 -- setting the current set of targets to be empty, followed by load.
261 setTargets :: Session -> [Target] -> IO ()
262 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
264 -- | returns the current set of targets
265 getTargets :: Session -> IO [Target]
266 getTargets s = withSession s (return . hsc_targets)
268 -- Add another target, or update an existing target with new content.
269 addTarget :: Session -> Target -> IO ()
271 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
274 -- removeTarget :: Session -> Module -> IO ()
276 -- Attempts to guess what Target a string refers to. This function implements
277 -- the --make/GHCi command-line syntax for filenames:
279 -- - if the string looks like a Haskell source filename, then interpret
281 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
283 -- - otherwise interpret the string as a module name
285 guessTarget :: String -> IO Target
287 | isHaskellSrcFilename file
288 = return (Target (TargetFile file) Nothing)
290 = do exists <- doesFileExist hs_file
291 if exists then return (Target (TargetFile hs_file) Nothing) else do
292 exists <- doesFileExist lhs_file
293 if exists then return (Target (TargetFile lhs_file) Nothing) else do
294 return (Target (TargetModule (mkModule file)) Nothing)
296 hs_file = file ++ ".hs"
297 lhs_file = file ++ ".lhs"
299 -- -----------------------------------------------------------------------------
300 -- Loading the program
302 -- | The result of load.
304 = LoadOk Errors -- ^ all specified targets were loaded successfully.
305 | LoadFailed Errors -- ^ not all modules were loaded.
307 type Errors = [String]
310 data ErrMsg = ErrMsg {
311 errMsgSeverity :: Severity, -- warning, error, etc.
312 errMsgSpans :: [SrcSpan],
313 errMsgShortDoc :: Doc,
314 errMsgExtraInfo :: Doc
318 -- Perform a dependency analysis starting from the current targets
319 -- and update the session with the new module graph.
320 depanal :: Session -> [Module] -> IO ()
321 depanal (Session ref) excluded_mods = do
322 hsc_env <- readIORef ref
324 dflags = hsc_dflags hsc_env
325 gmode = ghcMode (hsc_dflags hsc_env)
326 targets = hsc_targets hsc_env
327 old_graph = hsc_mod_graph hsc_env
329 showPass dflags "Chasing dependencies"
330 when (verbosity dflags >= 1 && gmode == BatchCompile) $
331 hPutStrLn stderr (showSDoc (hcat [
332 text "Chasing modules from: ",
333 hcat (punctuate comma (map pprTarget targets))]))
335 graph <- downsweep hsc_env old_graph excluded_mods
336 writeIORef ref hsc_env{ hsc_mod_graph=graph }
339 -- | Try to load the program. If a Module is supplied, then just
340 -- attempt to load up to this target. If no Module is supplied,
341 -- then try to load all targets.
342 load :: Session -> Maybe Module -> IO SuccessFlag
343 load s@(Session ref) maybe_mod
345 -- Dependency analysis first. Note that this fixes the module graph:
346 -- even if we don't get a fully successful upsweep, the full module
347 -- graph is still retained in the Session. We can tell which modules
348 -- were successfully loaded by inspecting the Session's HPT.
351 hsc_env <- readIORef ref
353 let hpt1 = hsc_HPT hsc_env
354 let dflags = hsc_dflags hsc_env
355 let mod_graph = hsc_mod_graph hsc_env
357 let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
358 let verb = verbosity dflags
360 -- The "bad" boot modules are the ones for which we have
361 -- B.hs-boot in the module graph, but no B.hs
362 -- The downsweep should have ensured this does not happen
364 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
365 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
366 not (ms_mod s `elem` all_home_mods)]
367 ASSERT( null bad_boot_mods ) return ()
369 -- mg2_with_srcimps drops the hi-boot nodes, returning a
370 -- graph with cycles. Among other things, it is used for
371 -- backing out partially complete cycles following a failed
372 -- upsweep, and for removing from hpt all the modules
373 -- not in strict downwards closure, during calls to compile.
374 let mg2_with_srcimps :: [SCC ModSummary]
375 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
377 -- check the stability property for each module.
378 stable_mods@(stable_obj,stable_bco)
379 | BatchCompile <- ghci_mode = ([],[])
380 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
382 -- prune bits of the HPT which are definitely redundant now,
384 pruned_hpt = pruneHomePackageTable hpt1
385 (flattenSCCs mg2_with_srcimps)
391 putStrLn (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
392 text "Stable BCO:" <+> ppr stable_bco))
394 -- Unload any modules which are going to be re-linked this time around.
395 let stable_linkables = [ linkable
396 | m <- stable_obj++stable_bco,
397 Just hmi <- [lookupModuleEnv pruned_hpt m],
398 Just linkable <- [hm_linkable hmi] ]
399 unload hsc_env stable_linkables
401 -- We could at this point detect cycles which aren't broken by
402 -- a source-import, and complain immediately, but it seems better
403 -- to let upsweep_mods do this, so at least some useful work gets
404 -- done before the upsweep is abandoned.
405 --hPutStrLn stderr "after tsort:\n"
406 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
408 -- Now do the upsweep, calling compile for each module in
409 -- turn. Final result is version 3 of everything.
411 -- Topologically sort the module graph, this time including hi-boot
412 -- nodes, and possibly just including the portion of the graph
413 -- reachable from the module specified in the 2nd argument to load.
414 -- This graph should be cycle-free.
415 -- If we're restricting the upsweep to a portion of the graph, we
416 -- also want to retain everything that is still stable.
417 let full_mg, partial_mg :: [SCC ModSummary]
418 full_mg = topSortModuleGraph False mod_graph Nothing
419 partial_mg = topSortModuleGraph False mod_graph maybe_mod
423 | AcyclicSCC ms <- full_mg,
424 ms_mod ms `elem` stable_obj++stable_bco,
425 ms_mod ms `notElem` [ ms_mod ms' |
426 AcyclicSCC ms' <- partial_mg ] ]
428 mg = stable_mg ++ partial_mg
430 -- clean up between compilations
431 let cleanup = cleanTempFilesExcept dflags
432 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
434 (upsweep_ok, hsc_env1, modsUpswept)
435 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
436 pruned_hpt stable_mods cleanup mg
438 -- Make modsDone be the summaries for each home module now
439 -- available; this should equal the domain of hpt3.
440 -- Get in in a roughly top .. bottom order (hence reverse).
442 let modsDone = reverse modsUpswept
444 -- Try and do linking in some form, depending on whether the
445 -- upsweep was completely or only partially successful.
447 if succeeded upsweep_ok
450 -- Easy; just relink it all.
451 do when (verb >= 2) $
452 hPutStrLn stderr "Upsweep completely successful."
454 -- Clean up after ourselves
455 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
457 -- Issue a warning for the confusing case where the user
458 -- said '-o foo' but we're not going to do any linking.
459 -- We attempt linking if either (a) one of the modules is
460 -- called Main, or (b) the user said -no-hs-main, indicating
461 -- that main() is going to come from somewhere else.
463 let ofile = outputFile dflags
464 let no_hs_main = dopt Opt_NoHsMain dflags
465 let mb_main_mod = mainModIs dflags
467 main_mod = mb_main_mod `orElse` "Main"
469 = any ((==main_mod).moduleUserString.ms_mod)
471 do_linking = a_root_is_Main || no_hs_main
473 when (ghci_mode == BatchCompile && isJust ofile && not do_linking
475 hPutStrLn stderr ("Warning: output was redirected with -o, " ++
476 "but no output will be generated\n" ++
477 "because there is no " ++ main_mod ++ " module.")
479 -- link everything together
480 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
482 loadFinish Succeeded linkresult ref hsc_env1
485 -- Tricky. We need to back out the effects of compiling any
486 -- half-done cycles, both so as to clean up the top level envs
487 -- and to avoid telling the interactive linker to link them.
488 do when (verb >= 2) $
489 hPutStrLn stderr "Upsweep partially successful."
492 = map ms_mod modsDone
493 let mods_to_zap_names
494 = findPartiallyCompletedCycles modsDone_names
497 = filter ((`notElem` mods_to_zap_names).ms_mod)
500 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
503 -- Clean up after ourselves
504 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
506 -- there should be no Nothings where linkables should be, now
507 ASSERT(all (isJust.hm_linkable)
508 (moduleEnvElts (hsc_HPT hsc_env))) do
510 -- Link everything together
511 linkresult <- link ghci_mode dflags False hpt4
513 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
514 loadFinish Failed linkresult ref hsc_env4
516 -- Finish up after a load.
518 -- If the link failed, unload everything and return.
519 loadFinish all_ok Failed ref hsc_env
520 = do unload hsc_env []
521 writeIORef ref $! discardProg hsc_env
524 -- Empty the interactive context and set the module context to the topmost
525 -- newly loaded module, or the Prelude if none were loaded.
526 loadFinish all_ok Succeeded ref hsc_env
527 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
531 -- Forget the current program, but retain the persistent info in HscEnv
532 discardProg :: HscEnv -> HscEnv
534 = hsc_env { hsc_mod_graph = emptyMG,
535 hsc_IC = emptyInteractiveContext,
536 hsc_HPT = emptyHomePackageTable }
538 -- used to fish out the preprocess output files for the purposes of
539 -- cleaning up. The preprocessed file *might* be the same as the
540 -- source file, but that doesn't do any harm.
541 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
543 -----------------------------------------------------------------------------
546 unload :: HscEnv -> [Linkable] -> IO ()
547 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
548 = case ghcMode (hsc_dflags hsc_env) of
549 BatchCompile -> return ()
551 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
553 Interactive -> panic "unload: no interpreter"
555 other -> panic "unload: strange mode"
557 -- -----------------------------------------------------------------------------
561 Stability tells us which modules definitely do not need to be recompiled.
562 There are two main reasons for having stability:
564 - avoid doing a complete upsweep of the module graph in GHCi when
565 modules near the bottom of the tree have not changed.
567 - to tell GHCi when it can load object code: we can only load object code
568 for a module when we also load object code fo all of the imports of the
569 module. So we need to know that we will definitely not be recompiling
570 any of these modules, and we can use the object code.
572 NB. stability is of no importance to BatchCompile at all, only Interactive.
573 (ToDo: what about JustTypecheck?)
575 The stability check is as follows. Both stableObject and
576 stableBCO are used during the upsweep phase later.
579 stable m = stableObject m || stableBCO m
582 all stableObject (imports m)
583 && old linkable does not exist, or is == on-disk .o
584 && date(on-disk .o) > date(.hs)
587 all stable (imports m)
588 && date(BCO) > date(.hs)
591 These properties embody the following ideas:
593 - if a module is stable:
594 - if it has been compiled in a previous pass (present in HPT)
595 then it does not need to be compiled or re-linked.
596 - if it has not been compiled in a previous pass,
597 then we only need to read its .hi file from disk and
598 link it to produce a ModDetails.
600 - if a modules is not stable, we will definitely be at least
601 re-linking, and possibly re-compiling it during the upsweep.
602 All non-stable modules can (and should) therefore be unlinked
605 - Note that objects are only considered stable if they only depend
606 on other objects. We can't link object code against byte code.
610 :: HomePackageTable -- HPT from last compilation
611 -> [SCC ModSummary] -- current module graph (cyclic)
612 -> [Module] -- all home modules
613 -> ([Module], -- stableObject
614 [Module]) -- stableBCO
616 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
618 checkSCC (stable_obj, stable_bco) scc0
619 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
620 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
621 | otherwise = (stable_obj, stable_bco)
623 scc = flattenSCC scc0
624 scc_mods = map ms_mod scc
625 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
627 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
628 -- all imports outside the current SCC, but in the home pkg
630 stable_obj_imps = map (`elem` stable_obj) scc_allimps
631 stable_bco_imps = map (`elem` stable_bco) scc_allimps
638 and (zipWith (||) stable_obj_imps stable_bco_imps)
642 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
646 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
648 Just hmi | Just l <- hm_linkable hmi
649 -> isObjectLinkable l && t == linkableTime l
650 -- why '>=' rather than '>' above? If the filesystem stores
651 -- times to the nearset second, we may occasionally find that
652 -- the object & source have the same modification time,
653 -- especially if the source was automatically generated
654 -- and compiled. Using >= is slightly unsafe, but it matches
658 = case lookupModuleEnv hpt (ms_mod ms) of
660 Just hmi | Just l <- hm_linkable hmi ->
661 not (isObjectLinkable l) &&
662 linkableTime l >= ms_hs_date ms
664 ms_allimps :: ModSummary -> [Module]
665 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
667 -- -----------------------------------------------------------------------------
668 -- Prune the HomePackageTable
670 -- Before doing an upsweep, we can throw away:
672 -- - For non-stable modules:
673 -- - all ModDetails, all linked code
674 -- - all unlinked code that is out of date with respect to
677 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
678 -- space at the end of the upsweep, because the topmost ModDetails of the
679 -- old HPT holds on to the entire type environment from the previous
682 pruneHomePackageTable
685 -> ([Module],[Module])
688 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
689 = mapModuleEnv prune hpt
691 | is_stable modl = hmi'
692 | otherwise = hmi'{ hm_details = emptyModDetails }
694 modl = mi_module (hm_iface hmi)
695 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
696 = hmi{ hm_linkable = Nothing }
699 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
701 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
703 is_stable m = m `elem` stable_obj || m `elem` stable_bco
705 -- -----------------------------------------------------------------------------
707 -- Return (names of) all those in modsDone who are part of a cycle
708 -- as defined by theGraph.
709 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
710 findPartiallyCompletedCycles modsDone theGraph
714 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
715 chew ((CyclicSCC vs):rest)
716 = let names_in_this_cycle = nub (map ms_mod vs)
718 = nub ([done | done <- modsDone,
719 done `elem` names_in_this_cycle])
720 chewed_rest = chew rest
722 if notNull mods_in_this_cycle
723 && length mods_in_this_cycle < length names_in_this_cycle
724 then mods_in_this_cycle ++ chewed_rest
727 -- -----------------------------------------------------------------------------
730 -- This is where we compile each module in the module graph, in a pass
731 -- from the bottom to the top of the graph.
733 -- There better had not be any cyclic groups here -- we check for them.
736 :: HscEnv -- Includes initially-empty HPT
737 -> HomePackageTable -- HPT from last time round (pruned)
738 -> ([Module],[Module]) -- stable modules (see checkStability)
739 -> IO () -- How to clean up unwanted tmp files
740 -> [SCC ModSummary] -- Mods to do (the worklist)
742 HscEnv, -- With an updated HPT
743 [ModSummary]) -- Mods which succeeded
745 upsweep hsc_env old_hpt stable_mods cleanup
747 = return (Succeeded, hsc_env, [])
749 upsweep hsc_env old_hpt stable_mods cleanup
751 = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
752 return (Failed, hsc_env, [])
754 upsweep hsc_env old_hpt stable_mods cleanup
755 (AcyclicSCC mod:mods)
756 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
757 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
758 -- (moduleEnvElts (hsc_HPT hsc_env)))
760 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
762 cleanup -- Remove unwanted tmp files between compilations
765 Nothing -> return (Failed, hsc_env, [])
767 { let this_mod = ms_mod mod
769 -- Add new info to hsc_env
770 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
772 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
774 -- Space-saving: delete the old HPT entry
775 -- for mod BUT if mod is a hs-boot
776 -- node, don't delete it. For the
777 -- interface, the HPT entry is probaby for the
778 -- main Haskell source file. Deleting it
779 -- would force .. (what?? --SDM)
780 old_hpt1 | isBootSummary mod = old_hpt
781 | otherwise = delModuleEnv old_hpt this_mod
783 ; (restOK, hsc_env2, modOKs)
784 <- upsweep hsc_env1 old_hpt1 stable_mods cleanup mods
785 ; return (restOK, hsc_env2, mod:modOKs)
789 -- Compile a single module. Always produce a Linkable for it if
790 -- successful. If no compilation happened, return the old Linkable.
791 upsweep_mod :: HscEnv
793 -> ([Module],[Module])
795 -> IO (Maybe HomeModInfo) -- Nothing => Failed
797 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary
800 this_mod = ms_mod summary
801 mb_obj_date = ms_obj_date summary
802 obj_fn = ml_obj_file (ms_location summary)
803 hs_date = ms_hs_date summary
805 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
806 compile_it = upsweep_compile hsc_env old_hpt this_mod summary
808 case ghcMode (hsc_dflags hsc_env) of
811 -- Batch-compilating is easy: just check whether we have
812 -- an up-to-date object file. If we do, then the compiler
813 -- needs to do a recompilation check.
814 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
816 findObjectLinkable this_mod obj_fn obj_date
817 compile_it (Just linkable)
824 _ | is_stable_obj, isJust old_hmi ->
826 -- object is stable, and we have an entry in the
827 -- old HPT: nothing to do
829 | is_stable_obj, isNothing old_hmi -> do
831 findObjectLinkable this_mod obj_fn
832 (expectJust "upseep1" mb_obj_date)
833 compile_it (Just linkable)
834 -- object is stable, but we need to load the interface
835 -- off disk to make a HMI.
838 ASSERT(isJust old_hmi) -- must be in the old_hpt
840 -- BCO is stable: nothing to do
842 | Just hmi <- old_hmi,
843 Just l <- hm_linkable hmi, not (isObjectLinkable l),
844 linkableTime l >= ms_hs_date summary ->
846 -- we have an old BCO that is up to date with respect
847 -- to the source: do a recompilation check as normal.
851 -- no existing code at all: we must recompile.
853 is_stable_obj = this_mod `elem` stable_obj
854 is_stable_bco = this_mod `elem` stable_bco
856 old_hmi = lookupModuleEnv old_hpt this_mod
858 -- Run hsc to compile a module
859 upsweep_compile hsc_env old_hpt this_mod summary mb_old_linkable = do
861 -- The old interface is ok if it's in the old HPT
862 -- a) we're compiling a source file, and the old HPT
863 -- entry is for a source file
864 -- b) we're compiling a hs-boot file
865 -- Case (b) allows an hs-boot file to get the interface of its
866 -- real source file on the second iteration of the compilation
867 -- manager, but that does no harm. Otherwise the hs-boot file
868 -- will always be recompiled
871 = case lookupModuleEnv old_hpt this_mod of
873 Just hm_info | isBootSummary summary -> Just iface
874 | not (mi_boot iface) -> Just iface
875 | otherwise -> Nothing
877 iface = hm_iface hm_info
879 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
882 -- Compilation failed. Compile may still have updated the PCS, tho.
883 CompErrs -> return Nothing
885 -- Compilation "succeeded", and may or may not have returned a new
886 -- linkable (depending on whether compilation was actually performed
888 CompOK new_details new_iface new_linkable
889 -> do let new_info = HomeModInfo { hm_iface = new_iface,
890 hm_details = new_details,
891 hm_linkable = new_linkable }
892 return (Just new_info)
895 -- Filter modules in the HPT
896 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
897 retainInTopLevelEnvs keep_these hpt
898 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
900 , let mb_mod_info = lookupModuleEnv hpt mod
901 , isJust mb_mod_info ]
903 -- ---------------------------------------------------------------------------
904 -- Topological sort of the module graph
907 :: Bool -- Drop hi-boot nodes? (see below)
911 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
913 -- Drop hi-boot nodes (first boolean arg)?
915 -- False: treat the hi-boot summaries as nodes of the graph,
916 -- so the graph must be acyclic
918 -- True: eliminate the hi-boot nodes, and instead pretend
919 -- the a source-import of Foo is an import of Foo
920 -- The resulting graph has no hi-boot nodes, but can by cyclic
922 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
923 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
924 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
925 = stronglyConnComp (map vertex_fn (reachable graph root))
927 -- restrict the graph to just those modules reachable from
928 -- the specified module. We do this by building a graph with
929 -- the full set of nodes, and determining the reachable set from
930 -- the specified node.
931 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
932 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
934 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
935 | otherwise = throwDyn (ProgramError "module does not exist")
937 moduleGraphNodes :: Bool -> [ModSummary]
938 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
939 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
941 -- Drop hs-boot nodes by using HsSrcFile as the key
942 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
943 | otherwise = HsBootFile
945 -- We use integers as the keys for the SCC algorithm
946 nodes :: [(ModSummary, Int, [Int])]
947 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
948 out_edge_keys hs_boot_key (ms_srcimps s) ++
949 out_edge_keys HsSrcFile (ms_imps s) )
951 , not (isBootSummary s && drop_hs_boot_nodes) ]
952 -- Drop the hi-boot ones if told to do so
954 key_map :: NodeMap Int
955 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
958 lookup_key :: HscSource -> Module -> Maybe Int
959 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
961 out_edge_keys :: HscSource -> [Module] -> [Int]
962 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
963 -- If we want keep_hi_boot_nodes, then we do lookup_key with
964 -- the IsBootInterface parameter True; else False
967 type NodeKey = (Module, HscSource) -- The nodes of the graph are
968 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
970 msKey :: ModSummary -> NodeKey
971 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
973 emptyNodeMap :: NodeMap a
974 emptyNodeMap = emptyFM
976 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
977 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
979 nodeMapElts :: NodeMap a -> [a]
982 -- -----------------------------------------------------------------
983 -- The unlinked image
985 -- The compilation manager keeps a list of compiled, but as-yet unlinked
986 -- binaries (byte code or object code). Even when it links bytecode
987 -- it keeps the unlinked version so it can re-link it later without
990 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
992 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
993 findModuleLinkable_maybe lis mod
994 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
997 many -> pprPanic "findModuleLinkable" (ppr mod)
999 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1000 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1002 -----------------------------------------------------------------------------
1003 -- Downsweep (dependency analysis)
1005 -- Chase downwards from the specified root set, returning summaries
1006 -- for all home modules encountered. Only follow source-import
1009 -- We pass in the previous collection of summaries, which is used as a
1010 -- cache to avoid recalculating a module summary if the source is
1013 -- The returned list of [ModSummary] nodes has one node for each home-package
1014 -- module, plus one for any hs-boot files. The imports of these nodes
1015 -- are all there, including the imports of non-home-package modules.
1018 -> [ModSummary] -- Old summaries
1019 -> [Module] -- Ignore dependencies on these; treat them as
1020 -- if they were package modules
1022 downsweep hsc_env old_summaries excl_mods
1023 = do rootSummaries <- mapM getRootSummary roots
1024 checkDuplicates rootSummaries
1025 loop (concatMap msDeps rootSummaries)
1026 (mkNodeMap rootSummaries)
1028 roots = hsc_targets hsc_env
1030 old_summary_map :: NodeMap ModSummary
1031 old_summary_map = mkNodeMap old_summaries
1033 getRootSummary :: Target -> IO ModSummary
1034 getRootSummary (Target (TargetFile file) maybe_buf)
1035 = do exists <- doesFileExist file
1036 if exists then summariseFile hsc_env file maybe_buf else do
1037 throwDyn (CmdLineError ("can't find file: " ++ file))
1038 getRootSummary (Target (TargetModule modl) maybe_buf)
1039 = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False
1040 modl maybe_buf excl_mods
1041 case maybe_summary of
1042 Nothing -> packageModErr modl
1045 -- In a root module, the filename is allowed to diverge from the module
1046 -- name, so we have to check that there aren't multiple root files
1047 -- defining the same module (otherwise the duplicates will be silently
1048 -- ignored, leading to confusing behaviour).
1049 checkDuplicates :: [ModSummary] -> IO ()
1050 checkDuplicates summaries = mapM_ check summaries
1055 many -> multiRootsErr modl many
1056 where modl = ms_mod summ
1058 [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1059 | summ' <- summaries, ms_mod summ' == modl ]
1061 loop :: [(FilePath,Module,IsBootInterface)]
1062 -- Work list: process these modules
1063 -> NodeMap ModSummary
1066 -- The result includes the worklist, except
1067 -- for those mentioned in the visited set
1068 loop [] done = return (nodeMapElts done)
1069 loop ((cur_path, wanted_mod, is_boot) : ss) done
1070 | key `elemFM` done = loop ss done
1071 | otherwise = do { mb_s <- summarise hsc_env old_summary_map
1072 (Just cur_path) is_boot
1073 wanted_mod Nothing excl_mods
1075 Nothing -> loop ss done
1076 Just s -> loop (msDeps s ++ ss)
1077 (addToFM done key s) }
1079 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1081 msDeps :: ModSummary -> [(FilePath, -- Importing module
1082 Module, -- Imported module
1083 IsBootInterface)] -- {-# SOURCE #-} import or not
1084 -- (msDeps s) returns the dependencies of the ModSummary s.
1085 -- A wrinkle is that for a {-# SOURCE #-} import we return
1086 -- *both* the hs-boot file
1087 -- *and* the source file
1088 -- as "dependencies". That ensures that the list of all relevant
1089 -- modules always contains B.hs if it contains B.hs-boot.
1090 -- Remember, this pass isn't doing the topological sort. It's
1091 -- just gathering the list of all relevant ModSummaries
1092 msDeps s = concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s]
1093 ++ [(f,m,False) | m <- ms_imps s]
1095 f = msHsFilePath s -- Keep the importing module for error reporting
1098 -----------------------------------------------------------------------------
1099 -- Summarising modules
1101 -- We have two types of summarisation:
1103 -- * Summarise a file. This is used for the root module(s) passed to
1104 -- cmLoadModules. The file is read, and used to determine the root
1105 -- module name. The module name may differ from the filename.
1107 -- * Summarise a module. We are given a module name, and must provide
1108 -- a summary. The finder is used to locate the file in which the module
1111 summariseFile :: HscEnv -> FilePath
1112 -> Maybe (StringBuffer,ClockTime)
1114 -- Used for Haskell source only, I think
1115 -- We know the file name, and we know it exists,
1116 -- but we don't necessarily know the module name (might differ)
1117 summariseFile hsc_env file maybe_buf
1118 = do let dflags = hsc_dflags hsc_env
1120 (dflags', hspp_fn, buf)
1121 <- preprocessFile dflags file maybe_buf
1123 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1125 -- Make a ModLocation for this file
1126 location <- mkHomeModLocation dflags mod file
1128 -- Tell the Finder cache where it is, so that subsequent calls
1129 -- to findModule will find it, even if it's not on any search path
1130 addHomeModuleToFinder hsc_env mod location
1132 src_timestamp <- case maybe_buf of
1133 Just (_,t) -> return t
1134 Nothing -> getModificationTime file
1136 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1138 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1139 ms_location = location,
1140 ms_hspp_file = Just hspp_fn,
1141 ms_hspp_buf = Just buf,
1142 ms_srcimps = srcimps, ms_imps = the_imps,
1143 ms_hs_date = src_timestamp,
1144 ms_obj_date = obj_timestamp })
1146 -- Summarise a module, and pick up source and timestamp.
1148 -> NodeMap ModSummary -- Map of old summaries
1149 -> Maybe FilePath -- Importing module (for error messages)
1150 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1151 -> Module -- Imported module to be summarised
1152 -> Maybe (StringBuffer, ClockTime)
1153 -> [Module] -- Modules to exclude
1154 -> IO (Maybe ModSummary) -- Its new summary
1156 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1157 | wanted_mod `elem` excl_mods
1160 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1161 = do -- Find its new timestamp; all the
1162 -- ModSummaries in the old map have valid ml_hs_files
1163 let location = ms_location old_summary
1164 src_fn = expectJust "summarise" (ml_hs_file location)
1166 -- return the cached summary if the source didn't change
1167 src_timestamp <- case maybe_buf of
1168 Just (_,t) -> return t
1169 Nothing -> getModificationTime src_fn
1171 if ms_hs_date old_summary == src_timestamp
1172 then do -- update the object-file timestamp
1173 obj_timestamp <- getObjTimestamp location is_boot
1174 return (Just old_summary{ ms_obj_date = obj_timestamp })
1176 -- source changed: re-summarise
1177 new_summary location src_fn maybe_buf src_timestamp
1180 = do found <- findModule hsc_env wanted_mod True {-explicit-}
1183 | not (isHomePackage pkg) -> return Nothing
1184 -- Drop external-pkg
1185 | isJust (ml_hs_file location) -> just_found location
1187 err -> noModError dflags cur_mod wanted_mod err
1190 dflags = hsc_dflags hsc_env
1192 hsc_src = if is_boot then HsBootFile else HsSrcFile
1194 just_found location = do
1195 -- Adjust location to point to the hs-boot source file,
1196 -- hi file, object file, when is_boot says so
1197 let location' | is_boot = addBootSuffixLocn location
1198 | otherwise = location
1199 src_fn = expectJust "summarise2" (ml_hs_file location')
1201 -- Check that it exists
1202 -- It might have been deleted since the Finder last found it
1203 maybe_t <- modificationTimeIfExists src_fn
1205 Nothing -> noHsFileErr cur_mod src_fn
1206 Just t -> new_summary location' src_fn Nothing t
1209 new_summary location src_fn maybe_bug src_timestamp
1211 -- Preprocess the source file and get its imports
1212 -- The dflags' contains the OPTIONS pragmas
1213 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1214 (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1216 when (mod_name /= wanted_mod) $
1217 throwDyn (ProgramError
1218 (showSDoc (text src_fn
1219 <> text ": file name does not match module name"
1220 <+> quotes (ppr mod_name))))
1222 -- Find the object timestamp, and return the summary
1223 obj_timestamp <- getObjTimestamp location is_boot
1225 return (Just ( ModSummary { ms_mod = wanted_mod,
1226 ms_hsc_src = hsc_src,
1227 ms_location = location,
1228 ms_hspp_file = Just hspp_fn,
1229 ms_hspp_buf = Just buf,
1230 ms_srcimps = srcimps,
1232 ms_hs_date = src_timestamp,
1233 ms_obj_date = obj_timestamp }))
1236 getObjTimestamp location is_boot
1237 = if is_boot then return Nothing
1238 else modificationTimeIfExists (ml_obj_file location)
1241 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1242 -> IO (DynFlags, FilePath, StringBuffer)
1243 preprocessFile dflags src_fn Nothing
1245 (dflags', hspp_fn) <- preprocess dflags src_fn
1246 buf <- hGetStringBuffer hspp_fn
1247 return (dflags', hspp_fn, buf)
1249 preprocessFile dflags src_fn (Just (buf, time))
1251 -- case we bypass the preprocessing stage?
1253 local_opts = getOptionsFromStringBuffer buf
1255 (dflags', errs) <- parseDynamicFlags dflags local_opts
1259 | Unlit _ <- startPhase src_fn = True
1260 -- note: local_opts is only required if there's no Unlit phase
1261 | dopt Opt_Cpp dflags' = True
1262 | dopt Opt_Pp dflags' = True
1265 when needs_preprocessing $
1266 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1268 return (dflags', "<buffer>", buf)
1271 -- code adapted from the file-based version in DriverUtil
1272 getOptionsFromStringBuffer :: StringBuffer -> [String]
1273 getOptionsFromStringBuffer buffer@(StringBuffer _ len# _) =
1275 ls = lines (lexemeToString buffer (I# len#)) -- lazy, so it's ok
1281 let l = removeSpaces l'
1283 () | null l -> look ls
1284 | prefixMatch "#" l -> look ls
1285 | prefixMatch "{-# LINE" l -> look ls -- -}
1286 | Just opts <- matchOptions l
1290 -----------------------------------------------------------------------------
1292 -----------------------------------------------------------------------------
1294 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1295 -- ToDo: we don't have a proper line number for this error
1296 noModError dflags cur_mod wanted_mod err
1297 = throwDyn $ ProgramError $ showSDoc $
1298 vcat [cantFindError dflags wanted_mod err,
1299 nest 2 (parens (pp_where cur_mod))]
1301 noHsFileErr cur_mod path
1302 = throwDyn $ CmdLineError $ showSDoc $
1303 vcat [text "Can't find" <+> text path,
1304 nest 2 (parens (pp_where cur_mod))]
1306 pp_where Nothing = text "one of the roots of the dependency analysis"
1307 pp_where (Just p) = text "imported from" <+> text p
1310 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1311 quotes (ppr mod) <+>
1312 text "is a package module")))
1314 multiRootsErr mod files
1315 = throwDyn (ProgramError (showSDoc (
1316 text "module" <+> quotes (ppr mod) <+>
1317 text "is defined in multiple files:" <+>
1318 sep (map text files))))
1320 cyclicModuleErr :: [ModSummary] -> SDoc
1322 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1323 2 (vcat (map show_one ms))
1325 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1326 nest 2 $ ptext SLIT("imports:") <+>
1327 (pp_imps HsBootFile (ms_srcimps ms)
1328 $$ pp_imps HsSrcFile (ms_imps ms))]
1329 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1330 pp_imps src mods = fsep (map (show_mod src) mods)
1333 -- | Inform GHC that the working directory has changed. GHC will flush
1334 -- its cache of module locations, since it may no longer be valid.
1335 -- Note: if you change the working directory, you should also unload
1336 -- the current program (set targets to empty, followed by load).
1337 workingDirectoryChanged :: Session -> IO ()
1338 workingDirectoryChanged s = withSession s $ \hsc_env ->
1339 flushFinderCache (hsc_FC hsc_env)
1341 -- -----------------------------------------------------------------------------
1342 -- inspecting the session
1344 -- | Get the module dependency graph.
1345 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1346 getModuleGraph s = withSession s (return . hsc_mod_graph)
1348 isLoaded :: Session -> Module -> IO Bool
1349 isLoaded s m = withSession s $ \hsc_env ->
1350 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1352 getBindings :: Session -> IO [TyThing]
1353 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1355 getPrintUnqual :: Session -> IO PrintUnqualified
1356 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1359 getModuleInfo :: Session -> Module -> IO ModuleInfo
1363 | BinaryCode FilePath
1365 data ModuleInfo = ModuleInfo {
1366 lm_modulename :: Module,
1367 lm_summary :: ModSummary,
1368 lm_interface :: ModIface,
1369 lm_tc_code :: Maybe TypecheckedCode,
1370 lm_rn_code :: Maybe RenamedCode,
1371 lm_obj :: Maybe ObjectCode
1374 type TypecheckedCode = HsTypecheckedGroup
1375 type RenamedCode = [HsGroup Name]
1377 -- ToDo: typechecks abstract syntax or renamed abstract syntax. Issues:
1378 -- - typechecked syntax includes extra dictionary translation and
1379 -- AbsBinds which need to be translated back into something closer to
1380 -- the original source.
1381 -- - renamed syntax currently doesn't exist in a single blob, since
1382 -- renaming and typechecking are interleaved at splice points. We'd
1383 -- need a restriction that there are no splices in the source module.
1386 -- - Data and Typeable instances for HsSyn.
1389 -- - things that aren't in the output of the renamer:
1390 -- - the export list
1394 -- - things that aren't in the output of the typechecker right now:
1395 -- - the export list
1397 -- - type signatures
1398 -- - type/data/newtype declarations
1399 -- - class declarations
1401 -- - extra things in the typechecker's output:
1402 -- - default methods are turned into top-level decls.
1403 -- - dictionary bindings
1405 -- ToDo: check for small transformations that happen to the syntax in
1406 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1408 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1409 -- to get from TyCons, Ids etc. to TH syntax (reify).
1411 -- :browse will use either lm_toplev or inspect lm_interface, depending
1412 -- on whether the module is interpreted or not.
1414 -- various abstract syntax types (perhaps IfaceBlah)
1418 -- This is for reconstructing refactored source code
1419 -- Calls the lexer repeatedly.
1420 -- ToDo: add comment tokens to token stream
1421 getTokenStream :: Session -> Module -> IO [Located Token]
1424 -- -----------------------------------------------------------------------------
1425 -- Interactive evaluation
1429 -- | Set the interactive evaluation context.
1431 -- Setting the context doesn't throw away any bindings; the bindings
1432 -- we've built up in the InteractiveContext simply move to the new
1433 -- module. They always shadow anything in scope in the current context.
1434 setContext :: Session
1435 -> [Module] -- entire top level scope of these modules
1436 -> [Module] -- exports only of these modules
1438 setContext (Session ref) toplevs exports = do
1439 hsc_env <- readIORef ref
1440 let old_ic = hsc_IC hsc_env
1441 hpt = hsc_HPT hsc_env
1443 mapM_ (checkModuleExists hsc_env hpt) exports
1444 export_env <- mkExportEnv hsc_env exports
1445 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1446 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1447 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1448 ic_exports = exports,
1449 ic_rn_gbl_env = all_env } }
1451 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1452 checkModuleExists hsc_env hpt mod =
1453 case lookupModuleEnv hpt mod of
1454 Just mod_info -> return ()
1455 _not_a_home_module -> do
1456 res <- findPackageModule hsc_env mod True
1458 Found _ _ -> return ()
1459 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1460 throwDyn (CmdLineError (showSDoc msg))
1462 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1463 mkTopLevEnv hpt modl
1464 = case lookupModuleEnv hpt modl of
1466 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1467 ++ showSDoc (pprModule modl)))
1469 case mi_globals (hm_iface details) of
1471 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1472 ++ showSDoc (pprModule modl)))
1473 Just env -> return env
1475 -- | Get the interactive evaluation context, consisting of a pair of the
1476 -- set of modules from which we take the full top-level scope, and the set
1477 -- of modules from which we take just the exports respectively.
1478 getContext :: Session -> IO ([Module],[Module])
1479 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1480 return (ic_toplev_scope ic, ic_exports ic))
1482 -- | Returns 'True' if the specified module is interpreted, and hence has
1483 -- its full top-level scope available.
1484 moduleIsInterpreted :: Session -> Module -> IO Bool
1485 moduleIsInterpreted s modl = withSession s $ \h ->
1486 case lookupModuleEnv (hsc_HPT h) modl of
1487 Just details -> return (isJust (mi_globals (hm_iface details)))
1488 _not_a_home_module -> return False
1490 -- | Looks up an identifier in the current interactive context (for :info)
1491 getInfo :: Session -> String -> IO [GetInfoResult]
1492 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1494 -- -----------------------------------------------------------------------------
1495 -- Getting the type of an expression
1497 -- | Get the type of an expression
1498 exprType :: Session -> String -> IO (Maybe Type)
1499 exprType s expr = withSession s $ \hsc_env -> do
1500 maybe_stuff <- hscTcExpr hsc_env expr
1502 Nothing -> return Nothing
1503 Just ty -> return (Just tidy_ty)
1505 tidy_ty = tidyType emptyTidyEnv ty
1506 dflags = hsc_dflags hsc_env
1508 -- -----------------------------------------------------------------------------
1509 -- Getting the kind of a type
1511 -- | Get the kind of a type
1512 typeKind :: Session -> String -> IO (Maybe Kind)
1513 typeKind s str = withSession s $ \hsc_env -> do
1514 maybe_stuff <- hscKcType hsc_env str
1516 Nothing -> return Nothing
1517 Just kind -> return (Just kind)
1519 -----------------------------------------------------------------------------
1520 -- lookupName: returns the TyThing for a Name in the interactive context.
1521 -- ToDo: should look it up in the full environment
1523 lookupName :: Session -> Name -> IO (Maybe TyThing)
1524 lookupName s name = withSession s $ \hsc_env -> do
1525 return $! lookupNameEnv (ic_type_env (hsc_IC hsc_env)) name
1527 -----------------------------------------------------------------------------
1528 -- cmCompileExpr: compile an expression and deliver an HValue
1530 compileExpr :: Session -> String -> IO (Maybe HValue)
1531 compileExpr s expr = withSession s $ \hsc_env -> do
1532 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1534 Nothing -> return Nothing
1535 Just (new_ic, names, hval) -> do
1537 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1539 case (names,hvals) of
1540 ([n],[hv]) -> return (Just hv)
1541 _ -> panic "compileExpr"
1543 -- -----------------------------------------------------------------------------
1544 -- running a statement interactively
1547 = RunOk [Name] -- ^ names bound by this evaluation
1548 | RunFailed -- ^ statement failed compilation
1549 | RunException Exception -- ^ statement raised an exception
1551 -- | Run a statement in the current interactive context. Statemenet
1552 -- may bind multple values.
1553 runStmt :: Session -> String -> IO RunResult
1554 runStmt (Session ref) expr
1556 hsc_env <- readIORef ref
1558 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1559 -- warnings about the implicit bindings we introduce.
1560 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1561 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1563 maybe_stuff <- hscStmt hsc_env' expr
1566 Nothing -> return RunFailed
1567 Just (new_hsc_env, names, hval) -> do
1569 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1570 either_hvals <- sandboxIO thing_to_run
1572 case either_hvals of
1574 -- on error, keep the *old* interactive context,
1575 -- so that 'it' is not bound to something
1576 -- that doesn't exist.
1577 return (RunException e)
1580 -- Get the newly bound things, and bind them.
1581 -- Don't need to delete any shadowed bindings;
1582 -- the new ones override the old ones.
1583 extendLinkEnv (zip names hvals)
1585 writeIORef ref new_hsc_env
1586 return (RunOk names)
1589 -- We run the statement in a "sandbox" to protect the rest of the
1590 -- system from anything the expression might do. For now, this
1591 -- consists of just wrapping it in an exception handler, but see below
1592 -- for another version.
1594 sandboxIO :: IO a -> IO (Either Exception a)
1595 sandboxIO thing = Exception.try thing
1598 -- This version of sandboxIO runs the expression in a completely new
1599 -- RTS main thread. It is disabled for now because ^C exceptions
1600 -- won't be delivered to the new thread, instead they'll be delivered
1601 -- to the (blocked) GHCi main thread.
1603 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1605 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1606 sandboxIO thing = do
1607 st_thing <- newStablePtr (Exception.try thing)
1608 alloca $ \ p_st_result -> do
1609 stat <- rts_evalStableIO st_thing p_st_result
1610 freeStablePtr st_thing
1612 then do st_result <- peek p_st_result
1613 result <- deRefStablePtr st_result
1614 freeStablePtr st_result
1615 return (Right result)
1617 return (Left (fromIntegral stat))
1619 foreign import "rts_evalStableIO" {- safe -}
1620 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1621 -- more informative than the C type!
1624 -- ---------------------------------------------------------------------------
1625 -- cmBrowseModule: get all the TyThings defined in a module
1627 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1628 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1629 mb_decls <- getModuleContents hsc_env modl exports_only
1631 Nothing -> return [] -- An error of some kind
1632 Just ds -> return ds
1635 -----------------------------------------------------------------------------
1636 -- show a module and it's source/object filenames
1638 showModule :: Session -> ModSummary -> IO String
1639 showModule s mod_summary = withSession s $ \hsc_env -> do
1640 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1641 Nothing -> panic "missing linkable"
1642 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1644 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))