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)
615 -- make sure that if we had an old disk linkable around, that it's
616 -- still there on the disk (in case we need to re-link it).
618 case maybe_disk_linkable of
620 Just l_disk -> linkableTime l == linkableTime l_disk
622 -- we only look for objects on disk the first time around;
623 -- if the user compiles a module on the side during a GHCi session,
624 -- it won't be picked up until the next ":load". This is what the
625 -- "null old_linkables" test below is.
626 linkable | null old_linkables = maybeToList maybe_disk_linkable
627 | otherwise = maybeToList maybe_old_linkable
629 -- only linkables newer than the source code are valid
630 src_date = ms_hs_date summary
633 = filter (\l -> linkableTime l > src_date) linkable
635 return (valid_linkable ++ new_linkables)
639 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
640 maybe_getFileLinkable mod_name obj_fn
641 = do obj_exist <- doesFileExist obj_fn
645 do let stub_fn = case splitFilename3 obj_fn of
646 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
647 stub_exist <- doesFileExist stub_fn
648 obj_time <- getModificationTime obj_fn
650 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
651 else return (Just (LM obj_time mod_name [DotO obj_fn]))
654 -----------------------------------------------------------------------------
655 -- Do a pre-upsweep without use of "compile", to establish a
656 -- (downward-closed) set of stable modules for which we won't call compile.
659 -- * has a valid linkable (see getValidLinkables above)
660 -- * depends only on stable modules
661 -- * has an interface in the HIT (interactive mode only)
663 preUpsweep :: [Linkable] -- new valid linkables
665 -> [ModuleName] -- names of all mods encountered in downsweep
666 -> [ModuleName] -- accumulating stable modules
667 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
668 -> IO [ModuleName] -- stable modules
670 preUpsweep valid_lis hit all_home_mods stable [] = return stable
671 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
672 = do let scc = flattenSCC scc0
673 scc_allhomeimps :: [ModuleName]
675 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
676 all_imports_in_scc_or_stable
677 = all in_stable_or_scc scc_allhomeimps
679 = map name_of_summary scc
681 = m `elem` scc_names || m `elem` stable
683 -- now we check for valid linkables: each module in the SCC must
684 -- have a valid linkable (see getValidLinkables above).
685 has_valid_linkable new_summary
686 = isJust (findModuleLinkable_maybe valid_lis modname)
687 where modname = name_of_summary new_summary
689 has_interface summary = ms_mod summary `elemUFM` hit
691 scc_is_stable = all_imports_in_scc_or_stable
692 && all has_valid_linkable scc
693 && all has_interface scc
696 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
697 else preUpsweep valid_lis hit all_home_mods stable sccs
700 -- Helper for preUpsweep. Assuming that new_summary's imports are all
701 -- stable (in the sense of preUpsweep), determine if new_summary is itself
702 -- stable, and, if so, in batch mode, return its linkable.
703 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
704 findInSummaries old_summaries mod_name
705 = [s | s <- old_summaries, name_of_summary s == mod_name]
707 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
708 findModInSummaries old_summaries mod
709 = case [s | s <- old_summaries, ms_mod s == mod] of
713 -- Return (names of) all those in modsDone who are part of a cycle
714 -- as defined by theGraph.
715 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
716 findPartiallyCompletedCycles modsDone theGraph
720 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
721 chew ((CyclicSCC vs):rest)
722 = let names_in_this_cycle = nub (map name_of_summary vs)
724 = nub ([done | done <- modsDone,
725 done `elem` names_in_this_cycle])
726 chewed_rest = chew rest
728 if not (null mods_in_this_cycle)
729 && length mods_in_this_cycle < length names_in_this_cycle
730 then mods_in_this_cycle ++ chewed_rest
734 -- Add the given (LM-form) Linkables to the UI, overwriting previous
735 -- versions if they exist.
736 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
738 = filter (not_in lis) ui ++ lis
740 not_in :: [Linkable] -> Linkable -> Bool
742 = all (\l -> linkableModName l /= mod) lis
743 where mod = linkableModName li
746 data CmThreaded -- stuff threaded through individual module compilations
747 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
750 -- Compile multiple modules, stopping as soon as an error appears.
751 -- There better had not be any cyclic groups here -- we check for them.
752 upsweep_mods :: GhciMode
754 -> UnlinkedImage -- valid linkables
755 -> (ModuleName -> [ModuleName]) -- to construct downward closures
756 -> CmThreaded -- PCS & HST & HIT
757 -> [SCC ModSummary] -- mods to do (the worklist)
758 -- ...... RETURNING ......
759 -> IO (Bool{-complete success?-},
761 [ModSummary], -- mods which succeeded
762 [Linkable]) -- new linkables
764 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
766 = return (True, threaded, [], [])
768 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
770 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
771 unwords (map (moduleNameUserString.name_of_summary) ms))
772 return (False, threaded, [], [])
774 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
775 ((AcyclicSCC mod):mods)
776 = do --case threaded of
777 -- CmThreaded pcsz hstz hitz
778 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
780 (threaded1, maybe_linkable)
781 <- upsweep_mod ghci_mode dflags oldUI threaded mod
782 (reachable_from (name_of_summary mod))
783 case maybe_linkable of
785 -> -- No errors; do the rest
786 do (restOK, threaded2, modOKs, linkables)
787 <- upsweep_mods ghci_mode dflags oldUI reachable_from
789 return (restOK, threaded2, mod:modOKs, linkable:linkables)
790 Nothing -- we got a compilation error; give up now
791 -> return (False, threaded1, [], [])
794 -- Compile a single module. Always produce a Linkable for it if
795 -- successful. If no compilation happened, return the old Linkable.
796 upsweep_mod :: GhciMode
802 -> IO (CmThreaded, Maybe Linkable)
804 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
806 let mod_name = name_of_summary summary1
807 let verb = verbosity dflags
809 let (CmThreaded pcs1 hst1 hit1) = threaded1
810 let old_iface = lookupUFM hit1 mod_name
812 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
814 source_unchanged = isJust maybe_old_linkable
816 reachable_only = filter (/= (name_of_summary summary1))
819 -- in interactive mode, all home modules below us *must* have an
820 -- interface in the HIT. We never demand-load home interfaces in
822 (hst1_strictDC, hit1_strictDC)
823 = ASSERT(ghci_mode == Batch ||
824 all (`elemUFM` hit1) reachable_only)
825 retainInTopLevelEnvs reachable_only (hst1,hit1)
828 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
831 | Just l <- maybe_old_linkable, isObjectLinkable l = True
834 compresult <- compile ghci_mode summary1 source_unchanged
835 have_object old_iface hst1_strictDC hit1_strictDC pcs1
839 -- Compilation "succeeded", and may or may not have returned a new
840 -- linkable (depending on whether compilation was actually performed
842 CompOK pcs2 new_details new_iface maybe_new_linkable
843 -> do let hst2 = addToUFM hst1 mod_name new_details
844 hit2 = addToUFM hit1 mod_name new_iface
845 threaded2 = CmThreaded pcs2 hst2 hit2
847 return (threaded2, if isJust maybe_new_linkable
848 then maybe_new_linkable
849 else Just old_linkable)
851 -- Compilation failed. compile may still have updated
854 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
855 return (threaded2, Nothing)
857 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
858 removeFromTopLevelEnvs :: [ModuleName]
859 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
860 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
861 removeFromTopLevelEnvs zap_these (hst, hit, ui)
862 = (delListFromUFM hst zap_these,
863 delListFromUFM hit zap_these,
864 filterModuleLinkables (`notElem` zap_these) ui
867 retainInTopLevelEnvs :: [ModuleName]
868 -> (HomeSymbolTable, HomeIfaceTable)
869 -> (HomeSymbolTable, HomeIfaceTable)
870 retainInTopLevelEnvs keep_these (hst, hit)
871 = (retainInUFM hst keep_these,
872 retainInUFM hit keep_these
875 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
876 retainInUFM ufm keys_to_keep
877 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
879 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
881 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
882 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
883 downwards_closure_of_module summaries root
884 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
885 toEdge summ = (name_of_summary summ,
886 filter (`elem` all_mods) (ms_allimps summ))
888 all_mods = map name_of_summary summaries
890 res = simple_transitive_closure (map toEdge summaries) [root]
892 --trace (showSDoc (text "DC of mod" <+> ppr root
893 -- <+> text "=" <+> ppr res)) (
897 -- Calculate transitive closures from a set of roots given an adjacency list
898 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
899 simple_transitive_closure graph set
900 = let set2 = nub (concatMap dsts set ++ set)
901 dsts node = fromMaybe [] (lookup node graph)
903 if length set == length set2
905 else simple_transitive_closure graph set2
908 -- Calculate SCCs of the module graph, with or without taking into
909 -- account source imports.
910 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
911 topological_sort include_source_imports summaries
913 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
915 = (summ, name_of_summary summ,
916 (if include_source_imports
917 then ms_srcimps summ else []) ++ ms_imps summ)
919 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
920 mash_edge (summ, m, m_imports)
921 = case lookup m key_map of
922 Nothing -> panic "reverse_topological_sort"
923 Just mk -> (summ, mk,
924 -- ignore imports not from the home package
925 catMaybes (map (flip lookup key_map) m_imports))
927 edges = map toEdge summaries
928 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
929 scc_input = map mash_edge edges
930 sccs = stronglyConnComp scc_input
935 -- Chase downwards from the specified root set, returning summaries
936 -- for all home modules encountered. Only follow source-import
937 -- links. Also returns a Bool to indicate whether any of the roots
939 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
940 downsweep rootNm old_summaries
941 = do rootSummaries <- mapM getRootSummary rootNm
943 = any ((=="Main").moduleNameUserString.name_of_summary)
946 <- loop (concat (map ms_imps rootSummaries))
947 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
948 let mod = ms_mod s, isHomeModule mod
950 return (all_summaries, a_root_is_Main)
952 getRootSummary :: FilePath -> IO ModSummary
954 | haskellish_file file
955 = do exists <- doesFileExist file
956 if exists then summariseFile file else do
957 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
959 = do exists <- doesFileExist hs_file
960 if exists then summariseFile hs_file else do
961 exists <- doesFileExist lhs_file
962 if exists then summariseFile lhs_file else do
963 let mod_name = mkModuleName file
964 maybe_summary <- getSummary mod_name
965 case maybe_summary of
966 Nothing -> packageModErr mod_name
969 hs_file = file ++ ".hs"
970 lhs_file = file ++ ".lhs"
972 getSummary :: ModuleName -> IO (Maybe ModSummary)
974 = do found <- findModule nm
976 Just (mod, location) -> do
977 let old_summary = findModInSummaries old_summaries mod
978 summarise mod location old_summary
980 Nothing -> throwDyn (CmdLineError
981 ("can't find module `"
982 ++ showSDoc (ppr nm) ++ "'"))
984 -- loop invariant: env doesn't contain package modules
985 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
986 loop [] env = return (moduleEnvElts env)
988 = do -- imports for modules we don't already have
989 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
992 needed_summaries <- mapM getSummary needed_imps
994 -- get just the "home" modules
995 let new_home_summaries = [ s | Just s <- needed_summaries ]
997 -- loop, checking the new imports
998 let new_imps = concat (map ms_imps new_home_summaries)
999 loop new_imps (extendModuleEnvList env
1000 [ (ms_mod s, s) | s <- new_home_summaries ])
1002 -----------------------------------------------------------------------------
1003 -- Summarising modules
1005 -- We have two types of summarisation:
1007 -- * Summarise a file. This is used for the root module passed to
1008 -- cmLoadModule. The file is read, and used to determine the root
1009 -- module name. The module name may differ from the filename.
1011 -- * Summarise a module. We are given a module name, and must provide
1012 -- a summary. The finder is used to locate the file in which the module
1015 summariseFile :: FilePath -> IO ModSummary
1017 = do hspp_fn <- preprocess file
1018 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1020 let (path, basename, ext) = splitFilename3 file
1022 Just (mod, location)
1023 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1026 <- case ml_hs_file location of
1027 Nothing -> noHsFileErr mod_name
1028 Just src_fn -> getModificationTime src_fn
1030 return (ModSummary mod
1031 location{ml_hspp_file=Just hspp_fn}
1032 srcimps imps src_timestamp)
1034 -- Summarise a module, and pick up source and timestamp.
1035 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1036 -> IO (Maybe ModSummary)
1037 summarise mod location old_summary
1039 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1042 <- case ml_hs_file location of
1043 Nothing -> noHsFileErr mod
1044 Just src_fn -> getModificationTime src_fn
1046 -- return the cached summary if the source didn't change
1047 case old_summary of {
1048 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1051 hspp_fn <- preprocess hs_fn
1052 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1054 when (mod_name /= moduleName mod) $
1055 throwDyn (ProgramError
1056 (showSDoc (text hs_fn
1057 <> text ": file name does not match module name"
1058 <+> quotes (ppr (moduleName mod)))))
1060 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1061 srcimps imps src_timestamp))
1064 | otherwise = return Nothing
1067 = panic (showSDoc (text "no source file for module" <+> quotes (ppr mod)))
1070 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1071 quotes (ppr mod) <+>
1072 text "is a package module")))