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"
37 import CmStaticInfo ( GhciMode(..) )
39 import DriverFlags ( getDynFlags )
43 import HscMain ( initPersistentCompilerState )
45 import RnEnv ( unQualInScope )
46 import Id ( idType, idName )
47 import Name ( Name, NamedThing(..), nameRdrName )
49 import RdrName ( lookupRdrEnv, emptyRdrEnv )
52 import Type ( tidyType )
53 import VarEnv ( emptyTidyEnv )
55 import Unique ( Uniquable )
56 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
57 import ErrUtils ( showPass )
62 import CmdLineOpts ( DynFlags(..) )
66 import Interpreter ( HValue )
67 import HscMain ( hscStmt )
68 import PrelGHC ( unsafeCoerce# )
72 import Exception ( throwDyn )
75 import Directory ( getModificationTime, doesFileExist )
84 -- Persistent state for the entire system
87 hst :: HomeSymbolTable, -- home symbol table
88 hit :: HomeIfaceTable, -- home interface table
89 ui :: UnlinkedImage, -- the unlinked images
90 mg :: ModuleGraph, -- the module graph
91 gmode :: GhciMode, -- NEVER CHANGES
92 ic :: InteractiveContext, -- command-line binding info
94 pcs :: PersistentCompilerState, -- compile's persistent state
95 pls :: PersistentLinkerState -- link's persistent state
98 emptyCmState :: GhciMode -> Module -> IO CmState
99 emptyCmState gmode mod
100 = do pcs <- initPersistentCompilerState
102 return (CmState { hst = emptySymbolTable,
103 hit = emptyIfaceTable,
107 ic = emptyInteractiveContext mod,
111 emptyInteractiveContext mod
112 = InteractiveContext { ic_module = mod,
113 ic_rn_env = emptyRdrEnv,
114 ic_type_env = emptyTypeEnv }
116 defaultCurrentModuleName = mkModuleName "Prelude"
117 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
120 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
121 emptyUI :: UnlinkedImage
124 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
125 emptyMG :: ModuleGraph
128 -----------------------------------------------------------------------------
129 -- Produce an initial CmState.
131 cmInit :: GhciMode -> IO CmState
133 prel <- moduleNameToModule defaultCurrentModuleName
134 writeIORef defaultCurrentModule prel
135 emptyCmState mode prel
137 -----------------------------------------------------------------------------
138 -- Setting the context doesn't throw away any bindings; the bindings
139 -- we've built up in the InteractiveContext simply move to the new
140 -- module. They always shadow anything in scope in the current context.
142 cmSetContext :: CmState -> String -> IO CmState
143 cmSetContext cmstate str
144 = do let mn = mkModuleName str
145 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
147 m <- case lookup mn modules_loaded of
150 mod <- moduleNameToModule mn
152 then throwDyn (CmdLineError (showSDoc
153 (quotes (ppr (moduleName mod))
154 <+> text "is not currently loaded")))
157 return cmstate{ ic = (ic cmstate){ic_module=m} }
159 cmGetContext :: CmState -> IO String
160 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
162 moduleNameToModule :: ModuleName -> IO Module
163 moduleNameToModule mn
164 = do maybe_stuff <- findModule mn
166 Nothing -> throwDyn (CmdLineError ("can't find module `"
167 ++ moduleNameUserString mn ++ "'"))
168 Just (m,_) -> return m
170 -----------------------------------------------------------------------------
171 -- cmRunStmt: Run a statement/expr.
174 cmRunStmt :: CmState -> DynFlags -> String
175 -> IO (CmState, -- new state
176 [Name]) -- names bound by this evaluation
177 cmRunStmt cmstate dflags expr
179 let InteractiveContext {
181 ic_type_env = type_env,
182 ic_module = this_mod } = icontext
184 (new_pcs, maybe_stuff)
185 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
188 Nothing -> return (cmstate{ pcs=new_pcs }, [])
189 Just (ids, _, bcos) -> do
191 -- update the interactive context
193 names = map idName ids
195 -- these names have just been shadowed
196 shadowed = [ n | r <- map nameRdrName names,
197 Just n <- [lookupRdrEnv rn_env r] ]
199 new_rn_env = extendLocalRdrEnv rn_env names
201 -- remove any shadowed bindings from the type_env
202 filtered_type_env = delListFromNameEnv type_env shadowed
204 new_type_env = extendNameEnvList filtered_type_env
205 [ (getName id, AnId id) | id <- ids]
207 new_ic = icontext { ic_rn_env = new_rn_env,
208 ic_type_env = new_type_env }
211 hval <- linkExpr pls bcos
214 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
215 hvals <- thing_to_run
217 -- Get the newly bound things, and bind them. Don't forget
218 -- to delete any shadowed bindings from the closure_env, lest
219 -- we end up with a space leak.
220 pls <- delListFromClosureEnv pls shadowed
221 new_pls <- addListToClosureEnv pls (zip names hvals)
223 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
225 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
228 -----------------------------------------------------------------------------
229 -- cmTypeOfExpr: returns a string representing the type of an expression
232 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
233 cmTypeOfExpr cmstate dflags expr
234 = do (new_pcs, maybe_stuff)
235 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
237 let new_cmstate = cmstate{pcs = new_pcs}
240 Nothing -> return (new_cmstate, Nothing)
242 let pit = pcs_PIT pcs
243 modname = moduleName (ic_module ic)
244 tidy_ty = tidyType emptyTidyEnv ty
245 str = case lookupIfaceByModName hit pit modname of
246 Nothing -> showSDoc (ppr tidy_ty)
247 Just iface -> showSDocForUser unqual (ppr tidy_ty)
248 where unqual = unQualInScope (mi_globals iface)
249 in return (new_cmstate, Just str)
251 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
254 -----------------------------------------------------------------------------
255 -- cmTypeOfName: returns a string representing the type of a name.
258 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
259 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
260 = case lookupNameEnv (ic_type_env ic) name of
261 Nothing -> return Nothing
263 let pit = pcs_PIT pcs
264 modname = moduleName (ic_module ic)
265 ty = tidyType emptyTidyEnv (idType id)
266 str = case lookupIfaceByModName hit pit modname of
267 Nothing -> showSDoc (ppr ty)
268 Just iface -> showSDocForUser unqual (ppr ty)
269 where unqual = unQualInScope (mi_globals iface)
272 _ -> panic "cmTypeOfName"
275 -----------------------------------------------------------------------------
276 -- cmCompileExpr: compile an expression and deliver an HValue
279 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
280 cmCompileExpr cmstate dflags expr
282 let InteractiveContext {
284 ic_type_env = type_env,
285 ic_module = this_mod } = icontext
287 (new_pcs, maybe_stuff)
288 <- hscStmt dflags hst hit pcs icontext
289 ("let __cmCompileExpr = "++expr) False{-stmt-}
292 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
293 Just (ids, _, bcos) -> do
296 hval <- linkExpr pls bcos
299 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
300 hvals <- thing_to_run
303 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
304 _ -> panic "cmCompileExpr"
307 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
310 -----------------------------------------------------------------------------
311 -- cmInfo: return "info" about an expression. The info might be:
313 -- * its type, for an expression,
314 -- * the class definition, for a class
315 -- * the datatype definition, for a tycon (or synonym)
316 -- * the export list, for a module
318 -- Can be used to find the type of the last expression compiled, by looking
321 cmInfo :: CmState -> String -> IO (Maybe String)
323 = do error "cmInfo not implemented yet"
325 -----------------------------------------------------------------------------
326 -- Unload the compilation manager's state: everything it knows about the
327 -- current collection of modules in the Home package.
329 cmUnload :: CmState -> IO CmState
331 = do -- Throw away the old home dir cache
333 -- Throw away the HIT and the HST
334 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
336 CmState{ hst=hst, hit=hit } = state
337 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
339 -----------------------------------------------------------------------------
340 -- The real business of the compilation manager: given a system state and
341 -- a module name, try and bring the module up to date, probably changing
342 -- the system state at the same time.
344 cmLoadModule :: CmState
346 -> IO (CmState, -- new state
347 Bool, -- was successful
348 [String]) -- list of modules loaded
350 cmLoadModule cmstate1 rootname
351 = do -- version 1's are the original, before downsweep
352 let pls1 = pls cmstate1
353 let pcs1 = pcs cmstate1
354 let hst1 = hst cmstate1
355 let hit1 = hit cmstate1
356 -- similarly, ui1 is the (complete) set of linkables from
357 -- the previous pass, if any.
358 let ui1 = ui cmstate1
359 let mg1 = mg cmstate1
360 let ic1 = ic cmstate1
362 let ghci_mode = gmode cmstate1 -- this never changes
364 -- Do the downsweep to reestablish the module graph
365 dflags <- getDynFlags
366 let verb = verbosity dflags
368 showPass dflags "Chasing dependencies"
369 when (verb >= 1 && ghci_mode == Batch) $
370 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
372 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
373 let mg2unsorted_names = map name_of_summary mg2unsorted
375 -- reachable_from follows source as well as normal imports
376 let reachable_from :: ModuleName -> [ModuleName]
377 reachable_from = downwards_closure_of_module mg2unsorted
379 -- should be cycle free; ignores 'import source's
380 let mg2 = topological_sort False mg2unsorted
381 -- ... whereas this takes them into account. Used for
382 -- backing out partially complete cycles following a failed
383 -- upsweep, and for removing from hst/hit all the modules
384 -- not in strict downwards closure, during calls to compile.
385 let mg2_with_srcimps = topological_sort True mg2unsorted
387 -- Sort out which linkables we wish to keep in the unlinked image.
388 -- See getValidLinkables below for details.
389 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
392 -- Figure out a stable set of modules which can be retained
393 -- the top level envs, to avoid upsweeping them. Goes to a
394 -- bit of trouble to avoid upsweeping module cycles.
396 -- Construct a set S of stable modules like this:
397 -- Travel upwards, over the sccified graph. For each scc
398 -- of modules ms, add ms to S only if:
399 -- 1. All home imports of ms are either in ms or S
400 -- 2. A valid linkable exists for each module in ms
402 stable_mods <- preUpsweep valid_linkables hit1
403 mg2unsorted_names [] mg2_with_srcimps
406 = concatMap (findInSummaries mg2unsorted) stable_mods
409 = filter (\m -> linkableModName m `elem` stable_mods)
413 putStrLn (showSDoc (text "Stable modules:"
414 <+> sep (map (text.moduleNameUserString) stable_mods)))
416 -- unload any modules which aren't going to be re-linked this
418 pls2 <- unload ghci_mode dflags stable_linkables pls1
420 -- We could at this point detect cycles which aren't broken by
421 -- a source-import, and complain immediately, but it seems better
422 -- to let upsweep_mods do this, so at least some useful work gets
423 -- done before the upsweep is abandoned.
425 = filter (\scc -> any (`notElem` stable_mods)
426 (map name_of_summary (flattenSCC scc)))
429 --hPutStrLn stderr "after tsort:\n"
430 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
432 -- Because we don't take into account source imports when doing
433 -- the topological sort, there shouldn't be any cycles in mg2.
434 -- If there is, we complain and give up -- the user needs to
435 -- break the cycle using a boot file.
437 -- Now do the upsweep, calling compile for each module in
438 -- turn. Final result is version 3 of everything.
440 let threaded2 = CmThreaded pcs1 hst1 hit1
442 (upsweep_complete_success, threaded3, modsUpswept, newLis)
443 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
444 threaded2 upsweep_these
446 let ui3 = add_to_ui valid_linkables newLis
447 let (CmThreaded pcs3 hst3 hit3) = threaded3
449 -- At this point, modsUpswept and newLis should have the same
450 -- length, so there is one new (or old) linkable for each
451 -- mod which was processed (passed to compile).
453 -- Make modsDone be the summaries for each home module now
454 -- available; this should equal the domains of hst3 and hit3.
455 -- (NOT STRICTLY TRUE if an interactive session was started
456 -- with some object on disk ???)
457 -- Get in in a roughly top .. bottom order (hence reverse).
459 let modsDone = reverse modsUpswept ++ stable_summaries
461 -- Try and do linking in some form, depending on whether the
462 -- upsweep was completely or only partially successful.
464 if upsweep_complete_success
467 -- Easy; just relink it all.
468 do when (verb >= 2) $
469 hPutStrLn stderr "Upsweep completely successful."
471 -- clean up after ourselves
472 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
474 -- link everything together
475 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
477 cmLoadFinish True linkresult
478 hst3 hit3 ui3 modsDone ghci_mode pcs3
481 -- Tricky. We need to back out the effects of compiling any
482 -- half-done cycles, both so as to clean up the top level envs
483 -- and to avoid telling the interactive linker to link them.
484 do when (verb >= 2) $
485 hPutStrLn stderr "Upsweep partially successful."
488 = map name_of_summary modsDone
489 let mods_to_zap_names
490 = findPartiallyCompletedCycles modsDone_names
492 let (hst4, hit4, ui4)
493 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
496 = filter ((`notElem` mods_to_zap_names).name_of_summary)
499 -- clean up after ourselves
500 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
502 -- link everything together
503 linkresult <- link ghci_mode dflags False ui4 pls2
505 cmLoadFinish False linkresult
506 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
509 -- Finish up after a cmLoad.
511 -- Empty the interactive context and set the module context to the topmost
512 -- newly loaded module, or the Prelude if none were loaded.
513 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
514 = do case linkresult of {
515 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
518 def_mod <- readIORef defaultCurrentModule
519 let current_mod = case mods of
523 new_ic = emptyInteractiveContext current_mod
525 new_cmstate = CmState{ hst=hst, hit=hit,
527 gmode=ghci_mode, pcs=pcs,
530 mods_loaded = map (moduleNameUserString.name_of_summary) mods
532 return (new_cmstate, ok, mods_loaded)
535 ppFilesFromSummaries summaries
536 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
538 -----------------------------------------------------------------------------
541 -- For each module (or SCC of modules), we take:
543 -- - an on-disk linkable, if this is the first time around and one
546 -- - the old linkable, otherwise (and if one is available).
548 -- and we throw away the linkable if it is older than the source
549 -- file. We ignore the on-disk linkables unless all of the dependents
550 -- of this SCC also have on-disk linkables.
552 -- If a module has a valid linkable, then it may be STABLE (see below),
553 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
556 -- ToDo: this pass could be merged with the preUpsweep.
559 :: [Linkable] -- old linkables
560 -> [ModuleName] -- all home modules
561 -> [SCC ModSummary] -- all modules in the program, dependency order
562 -> IO [Linkable] -- still-valid linkables
564 getValidLinkables old_linkables all_home_mods module_graph
565 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
567 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
569 scc = flattenSCC scc0
570 scc_names = map name_of_summary scc
571 home_module m = m `elem` all_home_mods && m `notElem` scc_names
572 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
574 has_object m = case findModuleLinkable_maybe new_linkables m of
576 Just l -> isObjectLinkable l
578 objects_allowed = all has_object scc_allhomeimps
582 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
584 -- since an scc can contain only all objects or no objects at all,
585 -- we have to check whether we got all objects or not, and re-do
586 -- the linkable check if not.
588 <- if objects_allowed && not (all isObjectLinkable these_linkables)
589 then foldM (getValidLinkable old_linkables False) [] scc
590 else return these_linkables
592 return (adjusted_linkables ++ new_linkables)
595 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
597 getValidLinkable old_linkables objects_allowed new_linkables summary
598 = do let mod_name = name_of_summary summary
601 <- if (not objects_allowed)
603 else case ml_obj_file (ms_location summary) of
604 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
605 Nothing -> return Nothing
607 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
610 Just l | not (isObjectLinkable l) || stillThere l
612 -- ToDo: emit a warning if not (stillThere l)
616 -- make sure that if we had an old disk linkable around, that it's
617 -- still there on the disk (in case we need to re-link it).
619 case maybe_disk_linkable of
621 Just l_disk -> linkableTime l == linkableTime l_disk
623 -- we only look for objects on disk the first time around;
624 -- if the user compiles a module on the side during a GHCi session,
625 -- it won't be picked up until the next ":load". This is what the
626 -- "null old_linkables" test below is.
627 linkable | null old_linkables = maybeToList maybe_disk_linkable
628 | otherwise = maybeToList maybe_old_linkable
630 -- only linkables newer than the source code are valid
631 src_date = ms_hs_date summary
634 = filter (\l -> linkableTime l > src_date) linkable
636 return (valid_linkable ++ new_linkables)
640 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
641 maybe_getFileLinkable mod_name obj_fn
642 = do obj_exist <- doesFileExist obj_fn
646 do let stub_fn = case splitFilename3 obj_fn of
647 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
648 stub_exist <- doesFileExist stub_fn
649 obj_time <- getModificationTime obj_fn
651 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
652 else return (Just (LM obj_time mod_name [DotO obj_fn]))
655 -----------------------------------------------------------------------------
656 -- Do a pre-upsweep without use of "compile", to establish a
657 -- (downward-closed) set of stable modules for which we won't call compile.
660 -- * has a valid linkable (see getValidLinkables above)
661 -- * depends only on stable modules
662 -- * has an interface in the HIT (interactive mode only)
664 preUpsweep :: [Linkable] -- new valid linkables
666 -> [ModuleName] -- names of all mods encountered in downsweep
667 -> [ModuleName] -- accumulating stable modules
668 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
669 -> IO [ModuleName] -- stable modules
671 preUpsweep valid_lis hit all_home_mods stable [] = return stable
672 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
673 = do let scc = flattenSCC scc0
674 scc_allhomeimps :: [ModuleName]
676 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
677 all_imports_in_scc_or_stable
678 = all in_stable_or_scc scc_allhomeimps
680 = map name_of_summary scc
682 = m `elem` scc_names || m `elem` stable
684 -- now we check for valid linkables: each module in the SCC must
685 -- have a valid linkable (see getValidLinkables above).
686 has_valid_linkable new_summary
687 = isJust (findModuleLinkable_maybe valid_lis modname)
688 where modname = name_of_summary new_summary
690 has_interface summary = ms_mod summary `elemUFM` hit
692 scc_is_stable = all_imports_in_scc_or_stable
693 && all has_valid_linkable scc
694 && all has_interface scc
697 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
698 else preUpsweep valid_lis hit all_home_mods stable sccs
701 -- Helper for preUpsweep. Assuming that new_summary's imports are all
702 -- stable (in the sense of preUpsweep), determine if new_summary is itself
703 -- stable, and, if so, in batch mode, return its linkable.
704 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
705 findInSummaries old_summaries mod_name
706 = [s | s <- old_summaries, name_of_summary s == mod_name]
708 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
709 findModInSummaries old_summaries mod
710 = case [s | s <- old_summaries, ms_mod s == mod] of
714 -- Return (names of) all those in modsDone who are part of a cycle
715 -- as defined by theGraph.
716 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
717 findPartiallyCompletedCycles modsDone theGraph
721 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
722 chew ((CyclicSCC vs):rest)
723 = let names_in_this_cycle = nub (map name_of_summary vs)
725 = nub ([done | done <- modsDone,
726 done `elem` names_in_this_cycle])
727 chewed_rest = chew rest
729 if not (null mods_in_this_cycle)
730 && length mods_in_this_cycle < length names_in_this_cycle
731 then mods_in_this_cycle ++ chewed_rest
735 -- Add the given (LM-form) Linkables to the UI, overwriting previous
736 -- versions if they exist.
737 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
739 = filter (not_in lis) ui ++ lis
741 not_in :: [Linkable] -> Linkable -> Bool
743 = all (\l -> linkableModName l /= mod) lis
744 where mod = linkableModName li
747 data CmThreaded -- stuff threaded through individual module compilations
748 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
751 -- Compile multiple modules, stopping as soon as an error appears.
752 -- There better had not be any cyclic groups here -- we check for them.
753 upsweep_mods :: GhciMode
755 -> UnlinkedImage -- valid linkables
756 -> (ModuleName -> [ModuleName]) -- to construct downward closures
757 -> CmThreaded -- PCS & HST & HIT
758 -> [SCC ModSummary] -- mods to do (the worklist)
759 -- ...... RETURNING ......
760 -> IO (Bool{-complete success?-},
762 [ModSummary], -- mods which succeeded
763 [Linkable]) -- new linkables
765 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
767 = return (True, threaded, [], [])
769 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
771 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
772 unwords (map (moduleNameUserString.name_of_summary) ms))
773 return (False, threaded, [], [])
775 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
776 ((AcyclicSCC mod):mods)
777 = do --case threaded of
778 -- CmThreaded pcsz hstz hitz
779 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
781 (threaded1, maybe_linkable)
782 <- upsweep_mod ghci_mode dflags oldUI threaded mod
783 (reachable_from (name_of_summary mod))
784 case maybe_linkable of
786 -> -- No errors; do the rest
787 do (restOK, threaded2, modOKs, linkables)
788 <- upsweep_mods ghci_mode dflags oldUI reachable_from
790 return (restOK, threaded2, mod:modOKs, linkable:linkables)
791 Nothing -- we got a compilation error; give up now
792 -> return (False, threaded1, [], [])
795 -- Compile a single module. Always produce a Linkable for it if
796 -- successful. If no compilation happened, return the old Linkable.
797 upsweep_mod :: GhciMode
803 -> IO (CmThreaded, Maybe Linkable)
805 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
807 let mod_name = name_of_summary summary1
808 let verb = verbosity dflags
810 let (CmThreaded pcs1 hst1 hit1) = threaded1
811 let old_iface = lookupUFM hit1 mod_name
813 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
815 source_unchanged = isJust maybe_old_linkable
817 reachable_only = filter (/= (name_of_summary summary1))
820 -- in interactive mode, all home modules below us *must* have an
821 -- interface in the HIT. We never demand-load home interfaces in
823 (hst1_strictDC, hit1_strictDC)
824 = ASSERT(ghci_mode == Batch ||
825 all (`elemUFM` hit1) reachable_only)
826 retainInTopLevelEnvs reachable_only (hst1,hit1)
829 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
832 | Just l <- maybe_old_linkable, isObjectLinkable l = True
835 compresult <- compile ghci_mode summary1 source_unchanged
836 have_object old_iface hst1_strictDC hit1_strictDC pcs1
840 -- Compilation "succeeded", and may or may not have returned a new
841 -- linkable (depending on whether compilation was actually performed
843 CompOK pcs2 new_details new_iface maybe_new_linkable
844 -> do let hst2 = addToUFM hst1 mod_name new_details
845 hit2 = addToUFM hit1 mod_name new_iface
846 threaded2 = CmThreaded pcs2 hst2 hit2
848 return (threaded2, if isJust maybe_new_linkable
849 then maybe_new_linkable
850 else Just old_linkable)
852 -- Compilation failed. compile may still have updated
855 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
856 return (threaded2, Nothing)
858 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
859 removeFromTopLevelEnvs :: [ModuleName]
860 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
861 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
862 removeFromTopLevelEnvs zap_these (hst, hit, ui)
863 = (delListFromUFM hst zap_these,
864 delListFromUFM hit zap_these,
865 filterModuleLinkables (`notElem` zap_these) ui
868 retainInTopLevelEnvs :: [ModuleName]
869 -> (HomeSymbolTable, HomeIfaceTable)
870 -> (HomeSymbolTable, HomeIfaceTable)
871 retainInTopLevelEnvs keep_these (hst, hit)
872 = (retainInUFM hst keep_these,
873 retainInUFM hit keep_these
876 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
877 retainInUFM ufm keys_to_keep
878 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
880 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
882 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
883 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
884 downwards_closure_of_module summaries root
885 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
886 toEdge summ = (name_of_summary summ,
887 filter (`elem` all_mods) (ms_allimps summ))
889 all_mods = map name_of_summary summaries
891 res = simple_transitive_closure (map toEdge summaries) [root]
893 --trace (showSDoc (text "DC of mod" <+> ppr root
894 -- <+> text "=" <+> ppr res)) (
898 -- Calculate transitive closures from a set of roots given an adjacency list
899 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
900 simple_transitive_closure graph set
901 = let set2 = nub (concatMap dsts set ++ set)
902 dsts node = fromMaybe [] (lookup node graph)
904 if length set == length set2
906 else simple_transitive_closure graph set2
909 -- Calculate SCCs of the module graph, with or without taking into
910 -- account source imports.
911 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
912 topological_sort include_source_imports summaries
914 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
916 = (summ, name_of_summary summ,
917 (if include_source_imports
918 then ms_srcimps summ else []) ++ ms_imps summ)
920 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
921 mash_edge (summ, m, m_imports)
922 = case lookup m key_map of
923 Nothing -> panic "reverse_topological_sort"
924 Just mk -> (summ, mk,
925 -- ignore imports not from the home package
926 catMaybes (map (flip lookup key_map) m_imports))
928 edges = map toEdge summaries
929 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
930 scc_input = map mash_edge edges
931 sccs = stronglyConnComp scc_input
936 -- Chase downwards from the specified root set, returning summaries
937 -- for all home modules encountered. Only follow source-import
938 -- links. Also returns a Bool to indicate whether any of the roots
940 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
941 downsweep rootNm old_summaries
942 = do rootSummaries <- mapM getRootSummary rootNm
944 = any ((=="Main").moduleNameUserString.name_of_summary)
947 <- loop (concat (map ms_imps rootSummaries))
948 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
949 let mod = ms_mod s, isHomeModule mod
951 return (all_summaries, a_root_is_Main)
953 getRootSummary :: FilePath -> IO ModSummary
955 | haskellish_file file
956 = do exists <- doesFileExist file
957 if exists then summariseFile file else do
958 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
960 = do exists <- doesFileExist hs_file
961 if exists then summariseFile hs_file else do
962 exists <- doesFileExist lhs_file
963 if exists then summariseFile lhs_file else do
964 let mod_name = mkModuleName file
965 maybe_summary <- getSummary mod_name
966 case maybe_summary of
967 Nothing -> packageModErr mod_name
970 hs_file = file ++ ".hs"
971 lhs_file = file ++ ".lhs"
973 getSummary :: ModuleName -> IO (Maybe ModSummary)
975 = do found <- findModule nm
977 Just (mod, location) -> do
978 let old_summary = findModInSummaries old_summaries mod
979 summarise mod location old_summary
981 Nothing -> throwDyn (CmdLineError
982 ("can't find module `"
983 ++ showSDoc (ppr nm) ++ "'"))
985 -- loop invariant: env doesn't contain package modules
986 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
987 loop [] env = return (moduleEnvElts env)
989 = do -- imports for modules we don't already have
990 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
993 needed_summaries <- mapM getSummary needed_imps
995 -- get just the "home" modules
996 let new_home_summaries = [ s | Just s <- needed_summaries ]
998 -- loop, checking the new imports
999 let new_imps = concat (map ms_imps new_home_summaries)
1000 loop new_imps (extendModuleEnvList env
1001 [ (ms_mod s, s) | s <- new_home_summaries ])
1003 -----------------------------------------------------------------------------
1004 -- Summarising modules
1006 -- We have two types of summarisation:
1008 -- * Summarise a file. This is used for the root module passed to
1009 -- cmLoadModule. The file is read, and used to determine the root
1010 -- module name. The module name may differ from the filename.
1012 -- * Summarise a module. We are given a module name, and must provide
1013 -- a summary. The finder is used to locate the file in which the module
1016 summariseFile :: FilePath -> IO ModSummary
1018 = do hspp_fn <- preprocess file
1019 modsrc <- readFile hspp_fn
1021 let (srcimps,imps,mod_name) = getImports modsrc
1022 (path, basename, ext) = splitFilename3 file
1024 Just (mod, location)
1025 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1028 <- case ml_hs_file location of
1029 Nothing -> noHsFileErr mod_name
1030 Just src_fn -> getModificationTime src_fn
1032 return (ModSummary mod
1033 location{ml_hspp_file=Just hspp_fn}
1034 srcimps imps src_timestamp)
1036 -- Summarise a module, and pick up source and timestamp.
1037 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1038 -> IO (Maybe ModSummary)
1039 summarise mod location old_summary
1041 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1044 <- case ml_hs_file location of
1045 Nothing -> noHsFileErr mod
1046 Just src_fn -> getModificationTime src_fn
1048 -- return the cached summary if the source didn't change
1049 case old_summary of {
1050 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1053 hspp_fn <- preprocess hs_fn
1054 modsrc <- readFile hspp_fn
1055 let (srcimps,imps,mod_name) = getImports modsrc
1057 when (mod_name /= moduleName mod) $
1058 throwDyn (ProgramError
1059 (showSDoc (text modsrc
1060 <> text ": file name does not match module name"
1061 <+> quotes (ppr (moduleName mod)))))
1063 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1064 srcimps imps src_timestamp))
1067 | otherwise = return Nothing
1070 = panic (showSDoc (text "no source file for module" <+> quotes (ppr mod)))
1073 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1074 quotes (ppr mod) <+>
1075 text "is a package module")))