2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
8 cmInit, -- :: GhciMode -> IO CmState
9 cmLoadModule, -- :: CmState -> FilePath -> IO (CmState, [String])
10 cmUnload, -- :: CmState -> IO CmState
11 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
13 cmSetContext, -- :: CmState -> String -> IO CmState
14 cmGetContext, -- :: CmState -> IO String
16 cmRunStmt, -- :: CmState -> DynFlags -> String -> IO (CmState, [Name])
18 CmState, emptyCmState -- abstract
22 #include "HsVersions.h"
27 import RnEnv ( unQualInScope )
28 import Id ( idType, idName )
29 import Name ( Name, lookupNameEnv, extendNameEnvList,
31 import RdrName ( emptyRdrEnv )
32 import Module ( Module, ModuleName, moduleName, isHomeModule,
33 mkModuleName, moduleNameUserString, moduleUserString )
34 import CmStaticInfo ( GhciMode(..) )
37 import Type ( tidyType )
38 import VarEnv ( emptyTidyEnv )
40 import HscMain ( initPersistentCompilerState )
42 import UniqFM ( lookupUFM, addToUFM, delListFromUFM,
44 import Unique ( Uniquable )
45 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
46 import DriverFlags ( getDynFlags )
48 import DriverUtil ( splitFilename3 )
49 import ErrUtils ( showPass )
55 import CmdLineOpts ( DynFlags(..) )
59 import Interpreter ( HValue )
60 import HscMain ( hscStmt )
61 import PrelGHC ( unsafeCoerce# )
65 import Exception ( throwDyn )
68 import Time ( ClockTime )
69 import Directory ( getModificationTime, doesFileExist )
73 import Maybe ( catMaybes, fromMaybe, isJust, fromJust )
78 -- Persistent state for the entire system
81 hst :: HomeSymbolTable, -- home symbol table
82 hit :: HomeIfaceTable, -- home interface table
83 ui :: UnlinkedImage, -- the unlinked images
84 mg :: ModuleGraph, -- the module graph
85 gmode :: GhciMode, -- NEVER CHANGES
86 ic :: InteractiveContext, -- command-line binding info
88 pcs :: PersistentCompilerState, -- compile's persistent state
89 pls :: PersistentLinkerState -- link's persistent state
92 emptyCmState :: GhciMode -> Module -> IO CmState
93 emptyCmState gmode mod
94 = do pcs <- initPersistentCompilerState
96 return (CmState { hst = emptySymbolTable,
97 hit = emptyIfaceTable,
101 ic = emptyInteractiveContext mod,
105 emptyInteractiveContext mod
106 = InteractiveContext { ic_module = mod,
107 ic_rn_env = emptyRdrEnv,
108 ic_type_env = emptyTypeEnv }
110 defaultCurrentModuleName = mkModuleName "Prelude"
111 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
114 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
115 emptyUI :: UnlinkedImage
118 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
119 emptyMG :: ModuleGraph
122 -----------------------------------------------------------------------------
123 -- Produce an initial CmState.
125 cmInit :: GhciMode -> IO CmState
127 prel <- moduleNameToModule defaultCurrentModuleName
128 writeIORef defaultCurrentModule prel
129 emptyCmState mode prel
131 -----------------------------------------------------------------------------
132 -- Setting the context doesn't throw away any bindings; the bindings
133 -- we've built up in the InteractiveContext simply move to the new
134 -- module. They always shadow anything in scope in the current context.
136 cmSetContext :: CmState -> String -> IO CmState
137 cmSetContext cmstate str
138 = do let mn = mkModuleName str
139 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
141 m <- case lookup mn modules_loaded of
144 mod <- moduleNameToModule mn
146 then throwDyn (OtherError (showSDoc
147 (quotes (ppr (moduleName mod))
148 <+> text "is not currently loaded")))
151 return cmstate{ ic = (ic cmstate){ic_module=m} }
153 cmGetContext :: CmState -> IO String
154 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
156 moduleNameToModule :: ModuleName -> IO Module
157 moduleNameToModule mn
158 = do maybe_stuff <- findModule mn
160 Nothing -> throwDyn (OtherError ("can't find module `"
161 ++ moduleNameUserString mn ++ "'"))
162 Just (m,_) -> return m
164 -----------------------------------------------------------------------------
165 -- cmRunStmt: Run a statement/expr.
168 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, [Name])
169 cmRunStmt cmstate dflags expr
171 let icontext = ic cmstate
174 ic_type_env = type_env,
175 ic_module = this_mod } = icontext
177 (new_pcs, maybe_stuff) <- hscStmt dflags hst hit pcs icontext expr
179 Nothing -> return (cmstate{ pcs=new_pcs }, [])
180 Just (ids, bcos) -> do
182 new_rn_env = extendLocalRdrEnv rn_env (map idName ids)
184 -- Extend the renamer-env from bound_ids, not
185 -- bound_names, because the latter may contain
186 -- [it] when the former is empty
187 new_type_env = extendNameEnvList type_env
188 [ (getName id, AnId id) | id <- ids]
190 new_ic = icontext { ic_rn_env = new_rn_env,
191 ic_type_env = new_type_env }
193 hval <- linkExpr pls bcos
194 hvals <- unsafeCoerce# hval :: IO [HValue]
195 let names = map idName ids
196 new_pls <- updateClosureEnv pls (zip names hvals)
197 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
199 -- ToDo: check that the module we passed in is sane/exists?
201 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls } = cmstate
204 -----------------------------------------------------------------------------
205 -- cmTypeOf: returns a string representing the type of a name.
207 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
208 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
209 = case lookupNameEnv (ic_type_env ic) name of
210 Nothing -> return Nothing
212 let pit = pcs_PIT pcs
213 modname = moduleName (ic_module ic)
214 ty = tidyType emptyTidyEnv (idType id)
215 str = case lookupIfaceByModName hit pit modname of
216 Nothing -> showSDoc (ppr ty)
217 Just iface -> showSDocForUser unqual (ppr ty)
218 where unqual = unQualInScope (mi_globals iface)
221 _ -> panic "cmTypeOfName"
223 -----------------------------------------------------------------------------
224 -- cmInfo: return "info" about an expression. The info might be:
226 -- * its type, for an expression,
227 -- * the class definition, for a class
228 -- * the datatype definition, for a tycon (or synonym)
229 -- * the export list, for a module
231 -- Can be used to find the type of the last expression compiled, by looking
234 cmInfo :: CmState -> String -> IO (Maybe String)
236 = do error "cmInfo not implemented yet"
238 -----------------------------------------------------------------------------
239 -- Unload the compilation manager's state: everything it knows about the
240 -- current collection of modules in the Home package.
242 cmUnload :: CmState -> IO CmState
244 = do -- Throw away the old home dir cache
246 -- Throw away the HIT and the HST
247 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
249 CmState{ hst=hst, hit=hit } = state
250 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
252 -----------------------------------------------------------------------------
253 -- The real business of the compilation manager: given a system state and
254 -- a module name, try and bring the module up to date, probably changing
255 -- the system state at the same time.
257 cmLoadModule :: CmState
259 -> IO (CmState, -- new state
260 Bool, -- was successful
261 [String]) -- list of modules loaded
263 cmLoadModule cmstate1 rootname
264 = do -- version 1's are the original, before downsweep
265 let pls1 = pls cmstate1
266 let pcs1 = pcs cmstate1
267 let hst1 = hst cmstate1
268 let hit1 = hit cmstate1
269 -- similarly, ui1 is the (complete) set of linkables from
270 -- the previous pass, if any.
271 let ui1 = ui cmstate1
272 let mg1 = mg cmstate1
273 let ic1 = ic cmstate1
275 let ghci_mode = gmode cmstate1 -- this never changes
277 -- Do the downsweep to reestablish the module graph
278 -- then generate version 2's by retaining in HIT,HST,UI a
279 -- stable set S of modules, as defined below.
281 dflags <- getDynFlags
282 let verb = verbosity dflags
284 showPass dflags "Chasing dependencies"
285 when (verb >= 1 && ghci_mode == Batch) $
286 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
288 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
289 let mg2unsorted_names = map name_of_summary mg2unsorted
291 -- reachable_from follows source as well as normal imports
292 let reachable_from :: ModuleName -> [ModuleName]
293 reachable_from = downwards_closure_of_module mg2unsorted
295 -- should be cycle free; ignores 'import source's
296 let mg2 = topological_sort False mg2unsorted
297 -- ... whereas this takes them into account. Used for
298 -- backing out partially complete cycles following a failed
299 -- upsweep, and for removing from hst/hit all the modules
300 -- not in strict downwards closure, during calls to compile.
301 let mg2_with_srcimps = topological_sort True mg2unsorted
303 -- Sort out which linkables we wish to keep in the unlinked image.
304 -- See getValidLinkables below for details.
305 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
308 -- Figure out a stable set of modules which can be retained
309 -- the top level envs, to avoid upsweeping them. Goes to a
310 -- bit of trouble to avoid upsweeping module cycles.
312 -- Construct a set S of stable modules like this:
313 -- Travel upwards, over the sccified graph. For each scc
314 -- of modules ms, add ms to S only if:
315 -- 1. All home imports of ms are either in ms or S
316 -- 2. A valid linkable exists for each module in ms
319 <- preUpsweep valid_linkables ui1 mg2unsorted_names
323 = concatMap (findInSummaries mg2unsorted) stable_mods
326 = filter (\m -> linkableModName m `elem` stable_mods)
330 putStrLn (showSDoc (text "Stable modules:"
331 <+> sep (map (text.moduleNameUserString) stable_mods)))
333 -- unload any modules which aren't going to be re-linked this
335 pls2 <- unload ghci_mode dflags stable_linkables pls1
337 -- We could at this point detect cycles which aren't broken by
338 -- a source-import, and complain immediately, but it seems better
339 -- to let upsweep_mods do this, so at least some useful work gets
340 -- done before the upsweep is abandoned.
342 = filter (\scc -> any (`notElem` stable_mods)
343 (map name_of_summary (flattenSCC scc)))
346 --hPutStrLn stderr "after tsort:\n"
347 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
349 -- Because we don't take into account source imports when doing
350 -- the topological sort, there shouldn't be any cycles in mg2.
351 -- If there is, we complain and give up -- the user needs to
352 -- break the cycle using a boot file.
354 -- Now do the upsweep, calling compile for each module in
355 -- turn. Final result is version 3 of everything.
357 let threaded2 = CmThreaded pcs1 hst1 hit1
359 (upsweep_complete_success, threaded3, modsUpswept, newLis)
360 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
361 threaded2 upsweep_these
363 let ui3 = add_to_ui valid_linkables newLis
364 let (CmThreaded pcs3 hst3 hit3) = threaded3
366 -- At this point, modsUpswept and newLis should have the same
367 -- length, so there is one new (or old) linkable for each
368 -- mod which was processed (passed to compile).
370 -- Make modsDone be the summaries for each home module now
371 -- available; this should equal the domains of hst3 and hit3.
372 -- (NOT STRICTLY TRUE if an interactive session was started
373 -- with some object on disk ???)
374 -- Get in in a roughly top .. bottom order (hence reverse).
376 let modsDone = reverse modsUpswept ++ stable_summaries
378 -- Try and do linking in some form, depending on whether the
379 -- upsweep was completely or only partially successful.
381 if upsweep_complete_success
384 -- Easy; just relink it all.
385 do when (verb >= 2) $
386 hPutStrLn stderr "Upsweep completely successful."
388 -- clean up after ourselves
389 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
391 -- link everything together
392 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
394 cmLoadFinish True linkresult
395 hst3 hit3 ui3 modsDone ghci_mode pcs3
398 -- Tricky. We need to back out the effects of compiling any
399 -- half-done cycles, both so as to clean up the top level envs
400 -- and to avoid telling the interactive linker to link them.
401 do when (verb >= 2) $
402 hPutStrLn stderr "Upsweep partially successful."
405 = map name_of_summary modsDone
406 let mods_to_zap_names
407 = findPartiallyCompletedCycles modsDone_names
409 let (hst4, hit4, ui4)
410 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
413 = filter ((`notElem` mods_to_zap_names).name_of_summary)
416 -- clean up after ourselves
417 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
419 -- link everything together
420 linkresult <- link ghci_mode dflags False ui4 pls2
422 cmLoadFinish False linkresult
423 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
426 -- Finish up after a cmLoad.
428 -- Empty the interactive context and set the module context to the topmost
429 -- newly loaded module, or the Prelude if none were loaded.
430 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
431 = do case linkresult of {
432 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
435 def_mod <- readIORef defaultCurrentModule
436 let current_mod = case mods of
440 new_ic = emptyInteractiveContext current_mod
442 new_cmstate = CmState{ hst=hst, hit=hit,
444 gmode=ghci_mode, pcs=pcs,
447 mods_loaded = map (moduleNameUserString.name_of_summary) mods
449 return (new_cmstate, ok, mods_loaded)
452 ppFilesFromSummaries summaries
453 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
455 -----------------------------------------------------------------------------
458 -- For each module (or SCC of modules), we take:
460 -- - the old in-core linkable, if available
461 -- - an on-disk linkable, if available
463 -- and we take the youngest of these, provided it is younger than the
464 -- source file. We ignore the on-disk linkables unless all of the
465 -- dependents of this SCC also have on-disk linkables.
467 -- If a module has a valid linkable, then it may be STABLE (see below),
468 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
471 -- ToDo: this pass could be merged with the preUpsweep.
474 :: [Linkable] -- old linkables
475 -> [ModuleName] -- all home modules
476 -> [SCC ModSummary] -- all modules in the program, dependency order
477 -> IO [Linkable] -- still-valid linkables
479 getValidLinkables old_linkables all_home_mods module_graph
480 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
482 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
484 scc = flattenSCC scc0
485 scc_names = map name_of_summary scc
486 home_module m = m `elem` all_home_mods && m `notElem` scc_names
487 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
489 has_object m = case findModuleLinkable_maybe new_linkables m of
491 Just l -> isObjectLinkable l
493 objects_allowed = all has_object scc_allhomeimps
497 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
499 -- since an scc can contain only all objects or no objects at all,
500 -- we have to check whether we got all objects or not, and re-do
501 -- the linkable check if not.
503 <- if objects_allowed && not (all isObjectLinkable these_linkables)
504 then foldM (getValidLinkable old_linkables False) [] scc
505 else return these_linkables
507 return (adjusted_linkables ++ new_linkables)
510 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
512 getValidLinkable old_linkables objects_allowed new_linkables summary
514 let mod_name = name_of_summary summary
517 <- if (not objects_allowed)
519 else case ml_obj_file (ms_location summary) of
520 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
521 Nothing -> return Nothing
523 -- find an old in-core linkable if we have one. (forget about
524 -- on-disk linkables for now, we'll check again whether there's
525 -- one here below, just in case a new one has popped up recently).
526 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
529 Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
532 -- The most recent of the old UI linkable or whatever we could
533 -- find on disk is returned as the linkable if compile
534 -- doesn't think we need to recompile.
536 = case (maybe_old_linkable, maybe_disk_linkable) of
537 (Nothing, Nothing) -> []
538 (Nothing, Just di) -> [di]
539 (Just ui, Nothing) -> [ui]
541 | linkableTime ui >= linkableTime di -> [ui]
544 -- only linkables newer than the source code are valid
545 let maybe_src_date = ms_hs_date summary
548 = case maybe_src_date of
549 Nothing -> panic "valid_linkable_list"
551 -> filter (\li -> linkableTime li > src_date) linkable_list
553 return (valid_linkable_list ++ new_linkables)
556 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
557 maybe_getFileLinkable mod_name obj_fn
558 = do obj_exist <- doesFileExist obj_fn
562 do let stub_fn = case splitFilename3 obj_fn of
563 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
564 stub_exist <- doesFileExist stub_fn
565 obj_time <- getModificationTime obj_fn
567 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
568 else return (Just (LM obj_time mod_name [DotO obj_fn]))
571 -----------------------------------------------------------------------------
572 -- Do a pre-upsweep without use of "compile", to establish a
573 -- (downward-closed) set of stable modules for which we won't call compile.
575 preUpsweep :: [Linkable] -- new valid linkables
576 -> [Linkable] -- old linkables
577 -> [ModuleName] -- names of all mods encountered in downsweep
578 -> [ModuleName] -- accumulating stable modules
579 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
580 -> IO [ModuleName] -- stable modules
582 preUpsweep valid_lis old_lis all_home_mods stable []
584 preUpsweep valid_lis old_lis all_home_mods stable (scc0:sccs)
585 = do let scc = flattenSCC scc0
586 scc_allhomeimps :: [ModuleName]
588 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
589 all_imports_in_scc_or_stable
590 = all in_stable_or_scc scc_allhomeimps
592 = map name_of_summary scc
594 = m `elem` scc_names || m `elem` stable
596 -- now we check for valid linkables: each module in the SCC must
597 -- have a valid linkable (see getValidLinkables above), and the
598 -- newest linkable must be the same as the previous linkable for
599 -- this module (if one exists).
600 has_valid_linkable new_summary
601 = case findModuleLinkable_maybe valid_lis modname of
603 Just l -> case findModuleLinkable_maybe old_lis modname of
605 Just m -> linkableTime l == linkableTime m
606 where modname = name_of_summary new_summary
608 scc_is_stable = all_imports_in_scc_or_stable
609 && all has_valid_linkable scc
612 then preUpsweep valid_lis old_lis all_home_mods
613 (scc_names++stable) sccs
614 else preUpsweep valid_lis old_lis all_home_mods
620 -- Helper for preUpsweep. Assuming that new_summary's imports are all
621 -- stable (in the sense of preUpsweep), determine if new_summary is itself
622 -- stable, and, if so, in batch mode, return its linkable.
623 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
624 findInSummaries old_summaries mod_name
625 = [s | s <- old_summaries, name_of_summary s == mod_name]
627 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
628 findModInSummaries old_summaries mod
629 = case [s | s <- old_summaries, ms_mod s == mod] of
633 -- Return (names of) all those in modsDone who are part of a cycle
634 -- as defined by theGraph.
635 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
636 findPartiallyCompletedCycles modsDone theGraph
640 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
641 chew ((CyclicSCC vs):rest)
642 = let names_in_this_cycle = nub (map name_of_summary vs)
644 = nub ([done | done <- modsDone,
645 done `elem` names_in_this_cycle])
646 chewed_rest = chew rest
648 if not (null mods_in_this_cycle)
649 && length mods_in_this_cycle < length names_in_this_cycle
650 then mods_in_this_cycle ++ chewed_rest
654 -- Add the given (LM-form) Linkables to the UI, overwriting previous
655 -- versions if they exist.
656 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
658 = filter (not_in lis) ui ++ lis
660 not_in :: [Linkable] -> Linkable -> Bool
662 = all (\l -> linkableModName l /= mod) lis
663 where mod = linkableModName li
666 data CmThreaded -- stuff threaded through individual module compilations
667 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
670 -- Compile multiple modules, stopping as soon as an error appears.
671 -- There better had not be any cyclic groups here -- we check for them.
672 upsweep_mods :: GhciMode
674 -> UnlinkedImage -- valid linkables
675 -> (ModuleName -> [ModuleName]) -- to construct downward closures
676 -> CmThreaded -- PCS & HST & HIT
677 -> [SCC ModSummary] -- mods to do (the worklist)
678 -- ...... RETURNING ......
679 -> IO (Bool{-complete success?-},
681 [ModSummary], -- mods which succeeded
682 [Linkable]) -- new linkables
684 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
686 = return (True, threaded, [], [])
688 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
690 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
691 unwords (map (moduleNameUserString.name_of_summary) ms))
692 return (False, threaded, [], [])
694 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
695 ((AcyclicSCC mod):mods)
696 = do --case threaded of
697 -- CmThreaded pcsz hstz hitz
698 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
700 (threaded1, maybe_linkable)
701 <- upsweep_mod ghci_mode dflags oldUI threaded mod
702 (reachable_from (name_of_summary mod))
703 case maybe_linkable of
705 -> -- No errors; do the rest
706 do (restOK, threaded2, modOKs, linkables)
707 <- upsweep_mods ghci_mode dflags oldUI reachable_from
709 return (restOK, threaded2, mod:modOKs, linkable:linkables)
710 Nothing -- we got a compilation error; give up now
711 -> return (False, threaded1, [], [])
714 -- Compile a single module. Always produce a Linkable for it if
715 -- successful. If no compilation happened, return the old Linkable.
716 upsweep_mod :: GhciMode
722 -> IO (CmThreaded, Maybe Linkable)
724 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
726 let mod_name = name_of_summary summary1
727 let verb = verbosity dflags
729 let (CmThreaded pcs1 hst1 hit1) = threaded1
730 let old_iface = lookupUFM hit1 mod_name
732 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
734 source_unchanged = isJust maybe_old_linkable
736 (hst1_strictDC, hit1_strictDC)
737 = retainInTopLevelEnvs
738 (filter (/= (name_of_summary summary1)) reachable_from_here)
742 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
744 compresult <- compile ghci_mode summary1 source_unchanged
745 old_iface hst1_strictDC hit1_strictDC pcs1
749 -- Compilation "succeeded", but didn't return a new
750 -- linkable, meaning that compilation wasn't needed, and the
751 -- new details were manufactured from the old iface.
752 CompOK pcs2 new_details new_iface Nothing
753 -> do let hst2 = addToUFM hst1 mod_name new_details
754 hit2 = addToUFM hit1 mod_name new_iface
755 threaded2 = CmThreaded pcs2 hst2 hit2
757 if ghci_mode == Interactive && verb >= 1 then
758 -- if we're using an object file, tell the user
760 (LM _ _ objs@(DotO _:_))
761 -> do hPutStrLn stderr (showSDoc (space <>
762 parens (hsep (text "using":
764 [ text o | DotO o <- objs ]))))
769 return (threaded2, Just old_linkable)
771 -- Compilation really did happen, and succeeded. A new
772 -- details, iface and linkable are returned.
773 CompOK pcs2 new_details new_iface (Just new_linkable)
774 -> do let hst2 = addToUFM hst1 mod_name new_details
775 hit2 = addToUFM hit1 mod_name new_iface
776 threaded2 = CmThreaded pcs2 hst2 hit2
778 return (threaded2, Just new_linkable)
780 -- Compilation failed. compile may still have updated
783 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
784 return (threaded2, Nothing)
786 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
787 removeFromTopLevelEnvs :: [ModuleName]
788 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
789 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
790 removeFromTopLevelEnvs zap_these (hst, hit, ui)
791 = (delListFromUFM hst zap_these,
792 delListFromUFM hit zap_these,
793 filterModuleLinkables (`notElem` zap_these) ui
796 retainInTopLevelEnvs :: [ModuleName]
797 -> (HomeSymbolTable, HomeIfaceTable)
798 -> (HomeSymbolTable, HomeIfaceTable)
799 retainInTopLevelEnvs keep_these (hst, hit)
800 = (retainInUFM hst keep_these,
801 retainInUFM hit keep_these
804 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
805 retainInUFM ufm keys_to_keep
806 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
808 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
810 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
811 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
812 downwards_closure_of_module summaries root
813 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
814 toEdge summ = (name_of_summary summ, ms_allimps summ)
815 res = simple_transitive_closure (map toEdge summaries) [root]
817 --trace (showSDoc (text "DC of mod" <+> ppr root
818 -- <+> text "=" <+> ppr res)) (
822 -- Calculate transitive closures from a set of roots given an adjacency list
823 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
824 simple_transitive_closure graph set
825 = let set2 = nub (concatMap dsts set ++ set)
826 dsts node = fromMaybe [] (lookup node graph)
828 if length set == length set2
830 else simple_transitive_closure graph set2
833 -- Calculate SCCs of the module graph, with or without taking into
834 -- account source imports.
835 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
836 topological_sort include_source_imports summaries
838 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
840 = (summ, name_of_summary summ,
841 (if include_source_imports
842 then ms_srcimps summ else []) ++ ms_imps summ)
844 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
845 mash_edge (summ, m, m_imports)
846 = case lookup m key_map of
847 Nothing -> panic "reverse_topological_sort"
848 Just mk -> (summ, mk,
849 -- ignore imports not from the home package
850 catMaybes (map (flip lookup key_map) m_imports))
852 edges = map toEdge summaries
853 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
854 scc_input = map mash_edge edges
855 sccs = stronglyConnComp scc_input
860 -- Chase downwards from the specified root set, returning summaries
861 -- for all home modules encountered. Only follow source-import
862 -- links. Also returns a Bool to indicate whether any of the roots
864 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
865 downsweep rootNm old_summaries
866 = do rootSummaries <- mapM getRootSummary rootNm
868 = any ((=="Main").moduleNameUserString.name_of_summary)
871 <- loop (concat (map ms_imps rootSummaries))
872 (filter (isHomeModule.ms_mod) rootSummaries)
873 return (all_summaries, a_root_is_Main)
875 getRootSummary :: FilePath -> IO ModSummary
877 | haskellish_file file
878 = do exists <- doesFileExist file
879 if exists then summariseFile file else do
880 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
882 = do exists <- doesFileExist hs_file
883 if exists then summariseFile hs_file else do
884 exists <- doesFileExist lhs_file
885 if exists then summariseFile lhs_file else do
886 getSummary (mkModuleName file)
888 hs_file = file ++ ".hs"
889 lhs_file = file ++ ".lhs"
891 getSummary :: ModuleName -> IO ModSummary
893 = do found <- findModule nm
895 Just (mod, location) -> do
896 let old_summary = findModInSummaries old_summaries mod
897 new_summary <- summarise mod location old_summary
899 Nothing -> return (fromJust old_summary)
902 Nothing -> throwDyn (OtherError
903 ("can't find module `"
904 ++ showSDoc (ppr nm) ++ "'"))
906 -- loop invariant: home_summaries doesn't contain package modules
907 loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
908 loop [] home_summaries = return home_summaries
909 loop imps home_summaries
910 = do -- all modules currently in homeSummaries
911 let all_home = map (moduleName.ms_mod) home_summaries
913 -- imports for modules we don't already have
914 let needed_imps = nub (filter (`notElem` all_home) imps)
917 needed_summaries <- mapM getSummary needed_imps
919 -- get just the "home" modules
920 let new_home_summaries
921 = filter (isHomeModule.ms_mod) needed_summaries
923 -- loop, checking the new imports
924 let new_imps = concat (map ms_imps new_home_summaries)
925 loop new_imps (new_home_summaries ++ home_summaries)
927 -----------------------------------------------------------------------------
928 -- Summarising modules
930 -- We have two types of summarisation:
932 -- * Summarise a file. This is used for the root module passed to
933 -- cmLoadModule. The file is read, and used to determine the root
934 -- module name. The module name may differ from the filename.
936 -- * Summarise a module. We are given a module name, and must provide
937 -- a summary. The finder is used to locate the file in which the module
940 summariseFile :: FilePath -> IO ModSummary
942 = do hspp_fn <- preprocess file
943 modsrc <- readFile hspp_fn
945 let (srcimps,imps,mod_name) = getImports modsrc
946 (path, basename, ext) = splitFilename3 file
949 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
952 <- case ml_hs_file location of
953 Nothing -> return Nothing
954 Just src_fn -> maybe_getModificationTime src_fn
956 return (ModSummary mod
957 location{ml_hspp_file=Just hspp_fn}
961 -- Summarise a module, and pick up source and timestamp.
962 summarise :: Module -> ModuleLocation -> Maybe ModSummary
963 -> IO (Maybe ModSummary)
964 summarise mod location old_summary
966 = do let hs_fn = unJust "summarise" (ml_hs_file location)
969 <- case ml_hs_file location of
970 Nothing -> return Nothing
971 Just src_fn -> maybe_getModificationTime src_fn
973 -- return the cached summary if the source didn't change
974 case old_summary of {
975 Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
978 hspp_fn <- preprocess hs_fn
979 modsrc <- readFile hspp_fn
980 let (srcimps,imps,mod_name) = getImports modsrc
983 <- case ml_hs_file location of
984 Nothing -> return Nothing
985 Just src_fn -> maybe_getModificationTime src_fn
987 when (mod_name /= moduleName mod) $
989 (showSDoc (text "file name does not match module name: "
990 <+> ppr (moduleName mod) <+> text "vs"
993 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
995 maybe_src_timestamp))
999 = return (Just (ModSummary mod location [] [] Nothing))
1001 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
1002 maybe_getModificationTime fn
1003 = (do time <- getModificationTime fn
1006 (\err -> return Nothing)