2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
8 cmInit, -- :: GhciMode -> IO CmState
10 cmLoadModule, -- :: CmState -> FilePath -> IO (CmState, [String])
12 cmUnload, -- :: CmState -> IO CmState
14 cmSetContext, -- :: CmState -> String -> IO CmState
16 cmGetContext, -- :: CmState -> IO String
19 cmRunStmt, -- :: CmState -> DynFlags -> String -> IO (CmState, [Name])
21 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
22 -- -> IO (CmState, Maybe String)
24 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
26 cmCompileExpr,-- :: CmState -> DynFlags -> String
27 -- -> IO (CmState, Maybe HValue)#endif
29 CmState, emptyCmState -- abstract
33 #include "HsVersions.h"
38 import RnEnv ( unQualInScope )
39 import Id ( idType, idName )
40 import Name ( Name, NamedThing(..), nameRdrName )
42 import RdrName ( lookupRdrEnv, emptyRdrEnv )
43 import Module ( Module, ModuleName, moduleName, isHomeModule,
44 mkModuleName, moduleNameUserString, moduleUserString )
45 import CmStaticInfo ( GhciMode(..) )
48 import Type ( tidyType )
49 import VarEnv ( emptyTidyEnv )
51 import HscMain ( initPersistentCompilerState )
54 import Unique ( Uniquable )
55 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
56 import DriverFlags ( getDynFlags )
58 import DriverUtil ( splitFilename3 )
59 import ErrUtils ( showPass )
65 import CmdLineOpts ( DynFlags(..) )
69 import Interpreter ( HValue )
70 import HscMain ( hscStmt )
71 import PrelGHC ( unsafeCoerce# )
75 import Exception ( throwDyn )
78 import Time ( ClockTime )
79 import Directory ( getModificationTime, doesFileExist )
88 -- Persistent state for the entire system
91 hst :: HomeSymbolTable, -- home symbol table
92 hit :: HomeIfaceTable, -- home interface table
93 ui :: UnlinkedImage, -- the unlinked images
94 mg :: ModuleGraph, -- the module graph
95 gmode :: GhciMode, -- NEVER CHANGES
96 ic :: InteractiveContext, -- command-line binding info
98 pcs :: PersistentCompilerState, -- compile's persistent state
99 pls :: PersistentLinkerState -- link's persistent state
102 emptyCmState :: GhciMode -> Module -> IO CmState
103 emptyCmState gmode mod
104 = do pcs <- initPersistentCompilerState
106 return (CmState { hst = emptySymbolTable,
107 hit = emptyIfaceTable,
111 ic = emptyInteractiveContext mod,
115 emptyInteractiveContext mod
116 = InteractiveContext { ic_module = mod,
117 ic_rn_env = emptyRdrEnv,
118 ic_type_env = emptyTypeEnv }
120 defaultCurrentModuleName = mkModuleName "Prelude"
121 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
124 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
125 emptyUI :: UnlinkedImage
128 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
129 emptyMG :: ModuleGraph
132 -----------------------------------------------------------------------------
133 -- Produce an initial CmState.
135 cmInit :: GhciMode -> IO CmState
137 prel <- moduleNameToModule defaultCurrentModuleName
138 writeIORef defaultCurrentModule prel
139 emptyCmState mode prel
141 -----------------------------------------------------------------------------
142 -- Setting the context doesn't throw away any bindings; the bindings
143 -- we've built up in the InteractiveContext simply move to the new
144 -- module. They always shadow anything in scope in the current context.
146 cmSetContext :: CmState -> String -> IO CmState
147 cmSetContext cmstate str
148 = do let mn = mkModuleName str
149 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
151 m <- case lookup mn modules_loaded of
154 mod <- moduleNameToModule mn
156 then throwDyn (OtherError (showSDoc
157 (quotes (ppr (moduleName mod))
158 <+> text "is not currently loaded")))
161 return cmstate{ ic = (ic cmstate){ic_module=m} }
163 cmGetContext :: CmState -> IO String
164 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
166 moduleNameToModule :: ModuleName -> IO Module
167 moduleNameToModule mn
168 = do maybe_stuff <- findModule mn
170 Nothing -> throwDyn (OtherError ("can't find module `"
171 ++ moduleNameUserString mn ++ "'"))
172 Just (m,_) -> return m
174 -----------------------------------------------------------------------------
175 -- cmRunStmt: Run a statement/expr.
178 cmRunStmt :: CmState -> DynFlags -> String
179 -> IO (CmState, -- new state
180 [Name]) -- names bound by this evaluation
181 cmRunStmt cmstate dflags expr
183 let InteractiveContext {
185 ic_type_env = type_env,
186 ic_module = this_mod } = icontext
188 (new_pcs, maybe_stuff)
189 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
192 Nothing -> return (cmstate{ pcs=new_pcs }, [])
193 Just (ids, _, bcos) -> do
195 -- update the interactive context
197 names = map idName ids
199 -- these names have just been shadowed
200 shadowed = [ n | r <- map nameRdrName names,
201 Just n <- [lookupRdrEnv rn_env r] ]
203 new_rn_env = extendLocalRdrEnv rn_env names
205 -- remove any shadowed bindings from the type_env
206 filtered_type_env = delListFromNameEnv type_env shadowed
208 new_type_env = extendNameEnvList filtered_type_env
209 [ (getName id, AnId id) | id <- ids]
211 new_ic = icontext { ic_rn_env = new_rn_env,
212 ic_type_env = new_type_env }
215 hval <- linkExpr pls bcos
218 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
219 hvals <- thing_to_run
221 -- Get the newly bound things, and bind them. Don't forget
222 -- to delete any shadowed bindings from the closure_env, lest
223 -- we end up with a space leak.
224 pls <- delListFromClosureEnv pls shadowed
225 new_pls <- addListToClosureEnv pls (zip names hvals)
227 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
229 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
232 -----------------------------------------------------------------------------
233 -- cmTypeOfExpr: returns a string representing the type of an expression
236 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
237 cmTypeOfExpr cmstate dflags expr
238 = do (new_pcs, maybe_stuff)
239 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
241 let new_cmstate = cmstate{pcs = new_pcs}
244 Nothing -> return (new_cmstate, Nothing)
246 let pit = pcs_PIT pcs
247 modname = moduleName (ic_module ic)
248 tidy_ty = tidyType emptyTidyEnv ty
249 str = case lookupIfaceByModName hit pit modname of
250 Nothing -> showSDoc (ppr tidy_ty)
251 Just iface -> showSDocForUser unqual (ppr tidy_ty)
252 where unqual = unQualInScope (mi_globals iface)
253 in return (new_cmstate, Just str)
255 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
258 -----------------------------------------------------------------------------
259 -- cmTypeOfName: returns a string representing the type of a name.
262 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
263 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
264 = case lookupNameEnv (ic_type_env ic) name of
265 Nothing -> return Nothing
267 let pit = pcs_PIT pcs
268 modname = moduleName (ic_module ic)
269 ty = tidyType emptyTidyEnv (idType id)
270 str = case lookupIfaceByModName hit pit modname of
271 Nothing -> showSDoc (ppr ty)
272 Just iface -> showSDocForUser unqual (ppr ty)
273 where unqual = unQualInScope (mi_globals iface)
276 _ -> panic "cmTypeOfName"
279 -----------------------------------------------------------------------------
280 -- cmCompileExpr: compile an expression and deliver an HValue
283 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
284 cmCompileExpr cmstate dflags expr
286 let InteractiveContext {
288 ic_type_env = type_env,
289 ic_module = this_mod } = icontext
291 (new_pcs, maybe_stuff)
292 <- hscStmt dflags hst hit pcs icontext
293 ("let __cmCompileExpr = "++expr) False{-stmt-}
296 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
297 Just (ids, _, bcos) -> do
300 hval <- linkExpr pls bcos
303 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
304 hvals <- thing_to_run
307 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
308 _ -> panic "cmCompileExpr"
311 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
314 -----------------------------------------------------------------------------
315 -- cmInfo: return "info" about an expression. The info might be:
317 -- * its type, for an expression,
318 -- * the class definition, for a class
319 -- * the datatype definition, for a tycon (or synonym)
320 -- * the export list, for a module
322 -- Can be used to find the type of the last expression compiled, by looking
325 cmInfo :: CmState -> String -> IO (Maybe String)
327 = do error "cmInfo not implemented yet"
329 -----------------------------------------------------------------------------
330 -- Unload the compilation manager's state: everything it knows about the
331 -- current collection of modules in the Home package.
333 cmUnload :: CmState -> IO CmState
335 = do -- Throw away the old home dir cache
337 -- Throw away the HIT and the HST
338 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
340 CmState{ hst=hst, hit=hit } = state
341 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
343 -----------------------------------------------------------------------------
344 -- The real business of the compilation manager: given a system state and
345 -- a module name, try and bring the module up to date, probably changing
346 -- the system state at the same time.
348 cmLoadModule :: CmState
350 -> IO (CmState, -- new state
351 Bool, -- was successful
352 [String]) -- list of modules loaded
354 cmLoadModule cmstate1 rootname
355 = do -- version 1's are the original, before downsweep
356 let pls1 = pls cmstate1
357 let pcs1 = pcs cmstate1
358 let hst1 = hst cmstate1
359 let hit1 = hit cmstate1
360 -- similarly, ui1 is the (complete) set of linkables from
361 -- the previous pass, if any.
362 let ui1 = ui cmstate1
363 let mg1 = mg cmstate1
364 let ic1 = ic cmstate1
366 let ghci_mode = gmode cmstate1 -- this never changes
368 -- Do the downsweep to reestablish the module graph
369 dflags <- getDynFlags
370 let verb = verbosity dflags
372 showPass dflags "Chasing dependencies"
373 when (verb >= 1 && ghci_mode == Batch) $
374 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
376 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
377 let mg2unsorted_names = map name_of_summary mg2unsorted
379 -- reachable_from follows source as well as normal imports
380 let reachable_from :: ModuleName -> [ModuleName]
381 reachable_from = downwards_closure_of_module mg2unsorted
383 -- should be cycle free; ignores 'import source's
384 let mg2 = topological_sort False mg2unsorted
385 -- ... whereas this takes them into account. Used for
386 -- backing out partially complete cycles following a failed
387 -- upsweep, and for removing from hst/hit all the modules
388 -- not in strict downwards closure, during calls to compile.
389 let mg2_with_srcimps = topological_sort True mg2unsorted
391 -- Sort out which linkables we wish to keep in the unlinked image.
392 -- See getValidLinkables below for details.
393 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
396 -- Figure out a stable set of modules which can be retained
397 -- the top level envs, to avoid upsweeping them. Goes to a
398 -- bit of trouble to avoid upsweeping module cycles.
400 -- Construct a set S of stable modules like this:
401 -- Travel upwards, over the sccified graph. For each scc
402 -- of modules ms, add ms to S only if:
403 -- 1. All home imports of ms are either in ms or S
404 -- 2. A valid linkable exists for each module in ms
406 stable_mods <- preUpsweep valid_linkables hit1
407 mg2unsorted_names [] mg2_with_srcimps
410 = concatMap (findInSummaries mg2unsorted) stable_mods
413 = filter (\m -> linkableModName m `elem` stable_mods)
417 putStrLn (showSDoc (text "Stable modules:"
418 <+> sep (map (text.moduleNameUserString) stable_mods)))
420 -- unload any modules which aren't going to be re-linked this
422 pls2 <- unload ghci_mode dflags stable_linkables pls1
424 -- We could at this point detect cycles which aren't broken by
425 -- a source-import, and complain immediately, but it seems better
426 -- to let upsweep_mods do this, so at least some useful work gets
427 -- done before the upsweep is abandoned.
429 = filter (\scc -> any (`notElem` stable_mods)
430 (map name_of_summary (flattenSCC scc)))
433 --hPutStrLn stderr "after tsort:\n"
434 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
436 -- Because we don't take into account source imports when doing
437 -- the topological sort, there shouldn't be any cycles in mg2.
438 -- If there is, we complain and give up -- the user needs to
439 -- break the cycle using a boot file.
441 -- Now do the upsweep, calling compile for each module in
442 -- turn. Final result is version 3 of everything.
444 let threaded2 = CmThreaded pcs1 hst1 hit1
446 (upsweep_complete_success, threaded3, modsUpswept, newLis)
447 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
448 threaded2 upsweep_these
450 let ui3 = add_to_ui valid_linkables newLis
451 let (CmThreaded pcs3 hst3 hit3) = threaded3
453 -- At this point, modsUpswept and newLis should have the same
454 -- length, so there is one new (or old) linkable for each
455 -- mod which was processed (passed to compile).
457 -- Make modsDone be the summaries for each home module now
458 -- available; this should equal the domains of hst3 and hit3.
459 -- (NOT STRICTLY TRUE if an interactive session was started
460 -- with some object on disk ???)
461 -- Get in in a roughly top .. bottom order (hence reverse).
463 let modsDone = reverse modsUpswept ++ stable_summaries
465 -- Try and do linking in some form, depending on whether the
466 -- upsweep was completely or only partially successful.
468 if upsweep_complete_success
471 -- Easy; just relink it all.
472 do when (verb >= 2) $
473 hPutStrLn stderr "Upsweep completely successful."
475 -- clean up after ourselves
476 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
478 -- link everything together
479 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
481 cmLoadFinish True linkresult
482 hst3 hit3 ui3 modsDone ghci_mode pcs3
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 name_of_summary modsDone
493 let mods_to_zap_names
494 = findPartiallyCompletedCycles modsDone_names
496 let (hst4, hit4, ui4)
497 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
500 = filter ((`notElem` mods_to_zap_names).name_of_summary)
503 -- clean up after ourselves
504 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
506 -- link everything together
507 linkresult <- link ghci_mode dflags False ui4 pls2
509 cmLoadFinish False linkresult
510 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
513 -- Finish up after a cmLoad.
515 -- Empty the interactive context and set the module context to the topmost
516 -- newly loaded module, or the Prelude if none were loaded.
517 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
518 = do case linkresult of {
519 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
522 def_mod <- readIORef defaultCurrentModule
523 let current_mod = case mods of
527 new_ic = emptyInteractiveContext current_mod
529 new_cmstate = CmState{ hst=hst, hit=hit,
531 gmode=ghci_mode, pcs=pcs,
534 mods_loaded = map (moduleNameUserString.name_of_summary) mods
536 return (new_cmstate, ok, mods_loaded)
539 ppFilesFromSummaries summaries
540 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
542 -----------------------------------------------------------------------------
545 -- For each module (or SCC of modules), we take:
547 -- - an on-disk linkable, if this is the first time around and one
550 -- - the old linkable, otherwise (and if one is available).
552 -- and we throw away the linkable if it is older than the source
553 -- file. We ignore the on-disk linkables unless all of the dependents
554 -- of this SCC also have on-disk linkables.
556 -- If a module has a valid linkable, then it may be STABLE (see below),
557 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
560 -- ToDo: this pass could be merged with the preUpsweep.
563 :: [Linkable] -- old linkables
564 -> [ModuleName] -- all home modules
565 -> [SCC ModSummary] -- all modules in the program, dependency order
566 -> IO [Linkable] -- still-valid linkables
568 getValidLinkables old_linkables all_home_mods module_graph
569 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
571 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
573 scc = flattenSCC scc0
574 scc_names = map name_of_summary scc
575 home_module m = m `elem` all_home_mods && m `notElem` scc_names
576 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
578 has_object m = case findModuleLinkable_maybe new_linkables m of
580 Just l -> isObjectLinkable l
582 objects_allowed = all has_object scc_allhomeimps
586 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
588 -- since an scc can contain only all objects or no objects at all,
589 -- we have to check whether we got all objects or not, and re-do
590 -- the linkable check if not.
592 <- if objects_allowed && not (all isObjectLinkable these_linkables)
593 then foldM (getValidLinkable old_linkables False) [] scc
594 else return these_linkables
596 return (adjusted_linkables ++ new_linkables)
599 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
601 getValidLinkable old_linkables objects_allowed new_linkables summary
602 = do let mod_name = name_of_summary summary
605 <- if (not objects_allowed)
607 else case ml_obj_file (ms_location summary) of
608 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
609 Nothing -> return Nothing
611 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
614 Just l | not (isObjectLinkable l) || stillThere l
616 -- ToDo: emit a warning if not (stillThere l)
620 -- make sure that if we had an old disk linkable around, that it's
621 -- still there on the disk (in case we need to re-link it).
623 case maybe_disk_linkable of
625 Just l_disk -> linkableTime l == linkableTime l_disk
627 -- we only look for objects on disk the first time around;
628 -- if the user compiles a module on the side during a GHCi session,
629 -- it won't be picked up until the next ":load". This is what the
630 -- "null old_linkables" test below is.
631 linkable | null old_linkables = maybeToList maybe_disk_linkable
632 | otherwise = maybeToList maybe_old_linkable
634 -- only linkables newer than the source code are valid
635 maybe_src_date = ms_hs_date summary
638 = case maybe_src_date of
639 Nothing -> panic "valid_linkable_list"
641 -> filter (\l -> linkableTime l > src_date) linkable
643 return (valid_linkable ++ new_linkables)
647 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
648 maybe_getFileLinkable mod_name obj_fn
649 = do obj_exist <- doesFileExist obj_fn
653 do let stub_fn = case splitFilename3 obj_fn of
654 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
655 stub_exist <- doesFileExist stub_fn
656 obj_time <- getModificationTime obj_fn
658 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
659 else return (Just (LM obj_time mod_name [DotO obj_fn]))
662 -----------------------------------------------------------------------------
663 -- Do a pre-upsweep without use of "compile", to establish a
664 -- (downward-closed) set of stable modules for which we won't call compile.
667 -- * has a valid linkable (see getValidLinkables above)
668 -- * depends only on stable modules
669 -- * has an interface in the HIT (interactive mode only)
671 preUpsweep :: [Linkable] -- new valid linkables
673 -> [ModuleName] -- names of all mods encountered in downsweep
674 -> [ModuleName] -- accumulating stable modules
675 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
676 -> IO [ModuleName] -- stable modules
678 preUpsweep valid_lis hit all_home_mods stable [] = return stable
679 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
680 = do let scc = flattenSCC scc0
681 scc_allhomeimps :: [ModuleName]
683 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
684 all_imports_in_scc_or_stable
685 = all in_stable_or_scc scc_allhomeimps
687 = map name_of_summary scc
689 = m `elem` scc_names || m `elem` stable
691 -- now we check for valid linkables: each module in the SCC must
692 -- have a valid linkable (see getValidLinkables above).
693 has_valid_linkable new_summary
694 = isJust (findModuleLinkable_maybe valid_lis modname)
695 where modname = name_of_summary new_summary
697 has_interface summary = ms_mod summary `elemUFM` hit
699 scc_is_stable = all_imports_in_scc_or_stable
700 && all has_valid_linkable scc
701 && all has_interface scc
704 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
705 else preUpsweep valid_lis hit all_home_mods stable sccs
708 -- Helper for preUpsweep. Assuming that new_summary's imports are all
709 -- stable (in the sense of preUpsweep), determine if new_summary is itself
710 -- stable, and, if so, in batch mode, return its linkable.
711 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
712 findInSummaries old_summaries mod_name
713 = [s | s <- old_summaries, name_of_summary s == mod_name]
715 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
716 findModInSummaries old_summaries mod
717 = case [s | s <- old_summaries, ms_mod s == mod] of
721 -- Return (names of) all those in modsDone who are part of a cycle
722 -- as defined by theGraph.
723 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
724 findPartiallyCompletedCycles modsDone theGraph
728 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
729 chew ((CyclicSCC vs):rest)
730 = let names_in_this_cycle = nub (map name_of_summary vs)
732 = nub ([done | done <- modsDone,
733 done `elem` names_in_this_cycle])
734 chewed_rest = chew rest
736 if not (null mods_in_this_cycle)
737 && length mods_in_this_cycle < length names_in_this_cycle
738 then mods_in_this_cycle ++ chewed_rest
742 -- Add the given (LM-form) Linkables to the UI, overwriting previous
743 -- versions if they exist.
744 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
746 = filter (not_in lis) ui ++ lis
748 not_in :: [Linkable] -> Linkable -> Bool
750 = all (\l -> linkableModName l /= mod) lis
751 where mod = linkableModName li
754 data CmThreaded -- stuff threaded through individual module compilations
755 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
758 -- Compile multiple modules, stopping as soon as an error appears.
759 -- There better had not be any cyclic groups here -- we check for them.
760 upsweep_mods :: GhciMode
762 -> UnlinkedImage -- valid linkables
763 -> (ModuleName -> [ModuleName]) -- to construct downward closures
764 -> CmThreaded -- PCS & HST & HIT
765 -> [SCC ModSummary] -- mods to do (the worklist)
766 -- ...... RETURNING ......
767 -> IO (Bool{-complete success?-},
769 [ModSummary], -- mods which succeeded
770 [Linkable]) -- new linkables
772 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
774 = return (True, threaded, [], [])
776 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
778 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
779 unwords (map (moduleNameUserString.name_of_summary) ms))
780 return (False, threaded, [], [])
782 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
783 ((AcyclicSCC mod):mods)
784 = do --case threaded of
785 -- CmThreaded pcsz hstz hitz
786 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
788 (threaded1, maybe_linkable)
789 <- upsweep_mod ghci_mode dflags oldUI threaded mod
790 (reachable_from (name_of_summary mod))
791 case maybe_linkable of
793 -> -- No errors; do the rest
794 do (restOK, threaded2, modOKs, linkables)
795 <- upsweep_mods ghci_mode dflags oldUI reachable_from
797 return (restOK, threaded2, mod:modOKs, linkable:linkables)
798 Nothing -- we got a compilation error; give up now
799 -> return (False, threaded1, [], [])
802 -- Compile a single module. Always produce a Linkable for it if
803 -- successful. If no compilation happened, return the old Linkable.
804 upsweep_mod :: GhciMode
810 -> IO (CmThreaded, Maybe Linkable)
812 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
814 let mod_name = name_of_summary summary1
815 let verb = verbosity dflags
817 let (CmThreaded pcs1 hst1 hit1) = threaded1
818 let old_iface = lookupUFM hit1 mod_name
820 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
822 source_unchanged = isJust maybe_old_linkable
824 reachable_only = filter (/= (name_of_summary summary1))
827 -- in interactive mode, all home modules below us *must* have an
828 -- interface in the HIT. We never demand-load home interfaces in
830 (hst1_strictDC, hit1_strictDC)
831 = ASSERT(ghci_mode == Batch ||
832 all (`elemUFM` hit1) reachable_only)
833 retainInTopLevelEnvs reachable_only (hst1,hit1)
836 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
839 | Just l <- maybe_old_linkable, isObjectLinkable l = True
842 compresult <- compile ghci_mode summary1 source_unchanged
843 have_object old_iface hst1_strictDC hit1_strictDC pcs1
847 -- Compilation "succeeded", and may or may not have returned a new
848 -- linkable (depending on whether compilation was actually performed
850 CompOK pcs2 new_details new_iface maybe_new_linkable
851 -> do let hst2 = addToUFM hst1 mod_name new_details
852 hit2 = addToUFM hit1 mod_name new_iface
853 threaded2 = CmThreaded pcs2 hst2 hit2
855 return (threaded2, if isJust maybe_new_linkable
856 then maybe_new_linkable
857 else Just old_linkable)
859 -- Compilation failed. compile may still have updated
862 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
863 return (threaded2, Nothing)
865 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
866 removeFromTopLevelEnvs :: [ModuleName]
867 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
868 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
869 removeFromTopLevelEnvs zap_these (hst, hit, ui)
870 = (delListFromUFM hst zap_these,
871 delListFromUFM hit zap_these,
872 filterModuleLinkables (`notElem` zap_these) ui
875 retainInTopLevelEnvs :: [ModuleName]
876 -> (HomeSymbolTable, HomeIfaceTable)
877 -> (HomeSymbolTable, HomeIfaceTable)
878 retainInTopLevelEnvs keep_these (hst, hit)
879 = (retainInUFM hst keep_these,
880 retainInUFM hit keep_these
883 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
884 retainInUFM ufm keys_to_keep
885 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
887 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
889 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
890 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
891 downwards_closure_of_module summaries root
892 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
893 toEdge summ = (name_of_summary summ, ms_allimps summ)
894 res = simple_transitive_closure (map toEdge summaries) [root]
896 --trace (showSDoc (text "DC of mod" <+> ppr root
897 -- <+> text "=" <+> ppr res)) (
901 -- Calculate transitive closures from a set of roots given an adjacency list
902 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
903 simple_transitive_closure graph set
904 = let set2 = nub (concatMap dsts set ++ set)
905 dsts node = fromMaybe [] (lookup node graph)
907 if length set == length set2
909 else simple_transitive_closure graph set2
912 -- Calculate SCCs of the module graph, with or without taking into
913 -- account source imports.
914 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
915 topological_sort include_source_imports summaries
917 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
919 = (summ, name_of_summary summ,
920 (if include_source_imports
921 then ms_srcimps summ else []) ++ ms_imps summ)
923 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
924 mash_edge (summ, m, m_imports)
925 = case lookup m key_map of
926 Nothing -> panic "reverse_topological_sort"
927 Just mk -> (summ, mk,
928 -- ignore imports not from the home package
929 catMaybes (map (flip lookup key_map) m_imports))
931 edges = map toEdge summaries
932 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
933 scc_input = map mash_edge edges
934 sccs = stronglyConnComp scc_input
939 -- Chase downwards from the specified root set, returning summaries
940 -- for all home modules encountered. Only follow source-import
941 -- links. Also returns a Bool to indicate whether any of the roots
943 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
944 downsweep rootNm old_summaries
945 = do rootSummaries <- mapM getRootSummary rootNm
947 = any ((=="Main").moduleNameUserString.name_of_summary)
950 <- loop (concat (map ms_imps rootSummaries))
951 (filter (isHomeModule.ms_mod) rootSummaries)
952 return (all_summaries, a_root_is_Main)
954 getRootSummary :: FilePath -> IO ModSummary
956 | haskellish_file file
957 = do exists <- doesFileExist file
958 if exists then summariseFile file else do
959 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
961 = do exists <- doesFileExist hs_file
962 if exists then summariseFile hs_file else do
963 exists <- doesFileExist lhs_file
964 if exists then summariseFile lhs_file else do
965 getSummary (mkModuleName file)
967 hs_file = file ++ ".hs"
968 lhs_file = file ++ ".lhs"
970 getSummary :: ModuleName -> IO ModSummary
972 = do found <- findModule nm
974 Just (mod, location) -> do
975 let old_summary = findModInSummaries old_summaries mod
976 new_summary <- summarise mod location old_summary
978 Nothing -> return (fromJust old_summary)
981 Nothing -> throwDyn (OtherError
982 ("can't find module `"
983 ++ showSDoc (ppr nm) ++ "'"))
985 -- loop invariant: home_summaries doesn't contain package modules
986 loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
987 loop [] home_summaries = return home_summaries
988 loop imps home_summaries
989 = do -- all modules currently in homeSummaries
990 let all_home = map (moduleName.ms_mod) home_summaries
992 -- imports for modules we don't already have
993 let needed_imps = nub (filter (`notElem` all_home) imps)
996 needed_summaries <- mapM getSummary needed_imps
998 -- get just the "home" modules
999 let new_home_summaries
1000 = filter (isHomeModule.ms_mod) needed_summaries
1002 -- loop, checking the new imports
1003 let new_imps = concat (map ms_imps new_home_summaries)
1004 loop new_imps (new_home_summaries ++ home_summaries)
1006 -----------------------------------------------------------------------------
1007 -- Summarising modules
1009 -- We have two types of summarisation:
1011 -- * Summarise a file. This is used for the root module passed to
1012 -- cmLoadModule. The file is read, and used to determine the root
1013 -- module name. The module name may differ from the filename.
1015 -- * Summarise a module. We are given a module name, and must provide
1016 -- a summary. The finder is used to locate the file in which the module
1019 summariseFile :: FilePath -> IO ModSummary
1021 = do hspp_fn <- preprocess file
1022 modsrc <- readFile hspp_fn
1024 let (srcimps,imps,mod_name) = getImports modsrc
1025 (path, basename, ext) = splitFilename3 file
1027 Just (mod, location)
1028 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1031 <- case ml_hs_file location of
1032 Nothing -> return Nothing
1033 Just src_fn -> maybe_getModificationTime src_fn
1035 return (ModSummary mod
1036 location{ml_hspp_file=Just hspp_fn}
1038 maybe_src_timestamp)
1040 -- Summarise a module, and pick up source and timestamp.
1041 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1042 -> IO (Maybe ModSummary)
1043 summarise mod location old_summary
1045 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1048 <- case ml_hs_file location of
1049 Nothing -> return Nothing
1050 Just src_fn -> maybe_getModificationTime src_fn
1052 -- return the cached summary if the source didn't change
1053 case old_summary of {
1054 Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
1057 hspp_fn <- preprocess hs_fn
1058 modsrc <- readFile hspp_fn
1059 let (srcimps,imps,mod_name) = getImports modsrc
1062 <- case ml_hs_file location of
1063 Nothing -> return Nothing
1064 Just src_fn -> maybe_getModificationTime src_fn
1066 when (mod_name /= moduleName mod) $
1067 throwDyn (OtherError
1068 (showSDoc (text "file name does not match module name: "
1069 <+> ppr (moduleName mod) <+> text "vs"
1072 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1074 maybe_src_timestamp))
1078 = return (Just (ModSummary mod location [] [] Nothing))
1080 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
1081 maybe_getModificationTime fn
1082 = (do time <- getModificationTime fn
1085 (\err -> return Nothing)