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 )
30 import RdrName ( emptyRdrEnv )
31 import Module ( Module, ModuleName, moduleName, isHomeModule,
32 mkModuleName, moduleNameUserString, moduleUserString )
33 import CmStaticInfo ( GhciMode(..) )
37 import HscMain ( initPersistentCompilerState )
39 import UniqFM ( lookupUFM, addToUFM, delListFromUFM,
41 import Unique ( Uniquable )
42 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
43 import DriverFlags ( getDynFlags )
45 import DriverUtil ( splitFilename3 )
46 import ErrUtils ( showPass )
52 import CmdLineOpts ( DynFlags(..) )
56 import Interpreter ( HValue )
57 import HscMain ( hscStmt )
58 import PrelGHC ( unsafeCoerce# )
62 import Exception ( throwDyn )
65 import Time ( ClockTime )
66 import Directory ( getModificationTime, doesFileExist )
70 import Maybe ( catMaybes, fromMaybe, isJust, fromJust )
75 -- Persistent state for the entire system
78 hst :: HomeSymbolTable, -- home symbol table
79 hit :: HomeIfaceTable, -- home interface table
80 ui :: UnlinkedImage, -- the unlinked images
81 mg :: ModuleGraph, -- the module graph
82 gmode :: GhciMode, -- NEVER CHANGES
83 ic :: InteractiveContext, -- command-line binding info
85 pcs :: PersistentCompilerState, -- compile's persistent state
86 pls :: PersistentLinkerState -- link's persistent state
89 emptyCmState :: GhciMode -> Module -> IO CmState
90 emptyCmState gmode mod
91 = do pcs <- initPersistentCompilerState
93 return (CmState { hst = emptySymbolTable,
94 hit = emptyIfaceTable,
98 ic = emptyInteractiveContext mod,
102 emptyInteractiveContext mod
103 = InteractiveContext { ic_module = mod,
104 ic_rn_env = emptyRdrEnv,
105 ic_type_env = emptyTypeEnv }
107 defaultCurrentModuleName = mkModuleName "Prelude"
108 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
111 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
112 emptyUI :: UnlinkedImage
115 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
116 emptyMG :: ModuleGraph
119 -----------------------------------------------------------------------------
120 -- Produce an initial CmState.
122 cmInit :: GhciMode -> IO CmState
124 prel <- moduleNameToModule defaultCurrentModuleName
125 writeIORef defaultCurrentModule prel
126 emptyCmState mode prel
128 -----------------------------------------------------------------------------
129 -- Setting the context doesn't throw away any bindings; the bindings
130 -- we've built up in the InteractiveContext simply move to the new
131 -- module. They always shadow anything in scope in the current context.
133 cmSetContext :: CmState -> String -> IO CmState
134 cmSetContext cmstate str
135 = do let mn = mkModuleName str
136 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
138 m <- case lookup mn modules_loaded of
141 mod <- moduleNameToModule mn
143 then throwDyn (OtherError (showSDoc
144 (quotes (ppr (moduleName mod))
145 <+> text "is not currently loaded")))
148 return cmstate{ ic = (ic cmstate){ic_module=m} }
150 cmGetContext :: CmState -> IO String
151 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
153 moduleNameToModule :: ModuleName -> IO Module
154 moduleNameToModule mn
155 = do maybe_stuff <- findModule mn
157 Nothing -> throwDyn (OtherError ("can't find module `"
158 ++ moduleNameUserString mn ++ "'"))
159 Just (m,_) -> return m
161 -----------------------------------------------------------------------------
162 -- cmRunStmt: Run a statement/expr.
165 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, [Name])
166 cmRunStmt cmstate dflags expr
167 = do (new_pcs, maybe_stuff) <- hscStmt dflags hst hit pcs (ic cmstate) expr
169 Nothing -> return (cmstate{ pcs=new_pcs }, [])
170 Just (new_ic, ids, bcos) -> do
171 hval <- linkExpr pls bcos
172 hvals <- unsafeCoerce# hval :: IO [HValue]
173 let names = map idName ids
174 new_pls <- updateClosureEnv pls (zip names hvals)
175 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
177 -- ToDo: check that the module we passed in is sane/exists?
179 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls } = cmstate
182 -----------------------------------------------------------------------------
183 -- cmTypeOf: returns a string representing the type of a name.
185 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
186 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
187 = case lookupNameEnv (ic_type_env ic) name of
188 Nothing -> return Nothing
190 let pit = pcs_PIT pcs
191 modname = moduleName (ic_module ic)
192 str = case lookupIfaceByModName hit pit modname of
193 Nothing -> showSDoc (ppr (idType id))
194 Just iface -> showSDocForUser unqual (ppr (idType id))
195 where unqual = unQualInScope (mi_globals iface)
198 _ -> panic "cmTypeOfName"
200 -----------------------------------------------------------------------------
201 -- cmInfo: return "info" about an expression. The info might be:
203 -- * its type, for an expression,
204 -- * the class definition, for a class
205 -- * the datatype definition, for a tycon (or synonym)
206 -- * the export list, for a module
208 -- Can be used to find the type of the last expression compiled, by looking
211 cmInfo :: CmState -> String -> IO (Maybe String)
213 = do error "cmInfo not implemented yet"
215 -----------------------------------------------------------------------------
216 -- Unload the compilation manager's state: everything it knows about the
217 -- current collection of modules in the Home package.
219 cmUnload :: CmState -> IO CmState
221 = do -- Throw away the old home dir cache
223 -- Throw away the HIT and the HST
224 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
226 CmState{ hst=hst, hit=hit } = state
227 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
229 -----------------------------------------------------------------------------
230 -- The real business of the compilation manager: given a system state and
231 -- a module name, try and bring the module up to date, probably changing
232 -- the system state at the same time.
234 cmLoadModule :: CmState
236 -> IO (CmState, -- new state
237 Bool, -- was successful
238 [String]) -- list of modules loaded
240 cmLoadModule cmstate1 rootname
241 = do -- version 1's are the original, before downsweep
242 let pls1 = pls cmstate1
243 let pcs1 = pcs cmstate1
244 let hst1 = hst cmstate1
245 let hit1 = hit cmstate1
246 -- similarly, ui1 is the (complete) set of linkables from
247 -- the previous pass, if any.
248 let ui1 = ui cmstate1
249 let mg1 = mg cmstate1
250 let ic1 = ic cmstate1
252 let ghci_mode = gmode cmstate1 -- this never changes
254 -- Do the downsweep to reestablish the module graph
255 -- then generate version 2's by retaining in HIT,HST,UI a
256 -- stable set S of modules, as defined below.
258 dflags <- getDynFlags
259 let verb = verbosity dflags
261 showPass dflags "Chasing dependencies"
262 when (verb >= 1 && ghci_mode == Batch) $
263 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
265 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
266 let mg2unsorted_names = map name_of_summary mg2unsorted
268 -- reachable_from follows source as well as normal imports
269 let reachable_from :: ModuleName -> [ModuleName]
270 reachable_from = downwards_closure_of_module mg2unsorted
272 -- should be cycle free; ignores 'import source's
273 let mg2 = topological_sort False mg2unsorted
274 -- ... whereas this takes them into account. Used for
275 -- backing out partially complete cycles following a failed
276 -- upsweep, and for removing from hst/hit all the modules
277 -- not in strict downwards closure, during calls to compile.
278 let mg2_with_srcimps = topological_sort True mg2unsorted
280 -- Sort out which linkables we wish to keep in the unlinked image.
281 -- See getValidLinkables below for details.
282 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
285 -- Figure out a stable set of modules which can be retained
286 -- the top level envs, to avoid upsweeping them. Goes to a
287 -- bit of trouble to avoid upsweeping module cycles.
289 -- Construct a set S of stable modules like this:
290 -- Travel upwards, over the sccified graph. For each scc
291 -- of modules ms, add ms to S only if:
292 -- 1. All home imports of ms are either in ms or S
293 -- 2. A valid linkable exists for each module in ms
296 <- preUpsweep valid_linkables ui1 mg2unsorted_names
300 = concatMap (findInSummaries mg2unsorted) stable_mods
303 = filter (\m -> linkableModName m `elem` stable_mods)
307 putStrLn (showSDoc (text "Stable modules:"
308 <+> sep (map (text.moduleNameUserString) stable_mods)))
310 -- unload any modules which aren't going to be re-linked this
312 pls2 <- unload ghci_mode dflags stable_linkables pls1
314 -- We could at this point detect cycles which aren't broken by
315 -- a source-import, and complain immediately, but it seems better
316 -- to let upsweep_mods do this, so at least some useful work gets
317 -- done before the upsweep is abandoned.
319 = filter (\scc -> any (`notElem` stable_mods)
320 (map name_of_summary (flattenSCC scc)))
323 --hPutStrLn stderr "after tsort:\n"
324 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
326 -- Because we don't take into account source imports when doing
327 -- the topological sort, there shouldn't be any cycles in mg2.
328 -- If there is, we complain and give up -- the user needs to
329 -- break the cycle using a boot file.
331 -- Now do the upsweep, calling compile for each module in
332 -- turn. Final result is version 3 of everything.
334 let threaded2 = CmThreaded pcs1 hst1 hit1
336 (upsweep_complete_success, threaded3, modsUpswept, newLis)
337 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
338 threaded2 upsweep_these
340 let ui3 = add_to_ui valid_linkables newLis
341 let (CmThreaded pcs3 hst3 hit3) = threaded3
343 -- At this point, modsUpswept and newLis should have the same
344 -- length, so there is one new (or old) linkable for each
345 -- mod which was processed (passed to compile).
347 -- Make modsDone be the summaries for each home module now
348 -- available; this should equal the domains of hst3 and hit3.
349 -- (NOT STRICTLY TRUE if an interactive session was started
350 -- with some object on disk ???)
351 -- Get in in a roughly top .. bottom order (hence reverse).
353 let modsDone = reverse modsUpswept ++ stable_summaries
355 -- Try and do linking in some form, depending on whether the
356 -- upsweep was completely or only partially successful.
358 if upsweep_complete_success
361 -- Easy; just relink it all.
362 do when (verb >= 2) $
363 hPutStrLn stderr "Upsweep completely successful."
365 -- clean up after ourselves
366 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
368 -- link everything together
369 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
371 cmLoadFinish True linkresult
372 hst3 hit3 ui3 modsDone ghci_mode pcs3
375 -- Tricky. We need to back out the effects of compiling any
376 -- half-done cycles, both so as to clean up the top level envs
377 -- and to avoid telling the interactive linker to link them.
378 do when (verb >= 2) $
379 hPutStrLn stderr "Upsweep partially successful."
382 = map name_of_summary modsDone
383 let mods_to_zap_names
384 = findPartiallyCompletedCycles modsDone_names
386 let (hst4, hit4, ui4)
387 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
390 = filter ((`notElem` mods_to_zap_names).name_of_summary)
393 -- clean up after ourselves
394 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
396 -- link everything together
397 linkresult <- link ghci_mode dflags False ui4 pls2
399 cmLoadFinish False linkresult
400 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
403 -- Finish up after a cmLoad.
405 -- Empty the interactive context and set the module context to the topmost
406 -- newly loaded module, or the Prelude if none were loaded.
407 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
408 = do case linkresult of {
409 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
412 def_mod <- readIORef defaultCurrentModule
413 let current_mod = case mods of
417 new_ic = emptyInteractiveContext current_mod
419 new_cmstate = CmState{ hst=hst, hit=hit,
421 gmode=ghci_mode, pcs=pcs,
424 mods_loaded = map (moduleNameUserString.name_of_summary) mods
426 return (new_cmstate, ok, mods_loaded)
429 ppFilesFromSummaries summaries
430 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
432 -----------------------------------------------------------------------------
435 -- For each module (or SCC of modules), we take:
437 -- - the old in-core linkable, if available
438 -- - an on-disk linkable, if available
440 -- and we take the youngest of these, provided it is younger than the
441 -- source file. We ignore the on-disk linkables unless all of the
442 -- dependents of this SCC also have on-disk linkables.
444 -- If a module has a valid linkable, then it may be STABLE (see below),
445 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
448 -- ToDo: this pass could be merged with the preUpsweep.
451 :: [Linkable] -- old linkables
452 -> [ModuleName] -- all home modules
453 -> [SCC ModSummary] -- all modules in the program, dependency order
454 -> IO [Linkable] -- still-valid linkables
456 getValidLinkables old_linkables all_home_mods module_graph
457 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
459 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
461 scc = flattenSCC scc0
462 scc_names = map name_of_summary scc
463 home_module m = m `elem` all_home_mods && m `notElem` scc_names
464 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
466 has_object m = case findModuleLinkable_maybe new_linkables m of
468 Just l -> isObjectLinkable l
470 objects_allowed = all has_object scc_allhomeimps
474 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
476 -- since an scc can contain only all objects or no objects at all,
477 -- we have to check whether we got all objects or not, and re-do
478 -- the linkable check if not.
480 <- if objects_allowed && not (all isObjectLinkable these_linkables)
481 then foldM (getValidLinkable old_linkables False) [] scc
482 else return these_linkables
484 return (adjusted_linkables ++ new_linkables)
487 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
489 getValidLinkable old_linkables objects_allowed new_linkables summary
491 let mod_name = name_of_summary summary
494 <- if (not objects_allowed)
496 else case ml_obj_file (ms_location summary) of
497 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
498 Nothing -> return Nothing
500 -- find an old in-core linkable if we have one. (forget about
501 -- on-disk linkables for now, we'll check again whether there's
502 -- one here below, just in case a new one has popped up recently).
503 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
506 Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
509 -- The most recent of the old UI linkable or whatever we could
510 -- find on disk is returned as the linkable if compile
511 -- doesn't think we need to recompile.
513 = case (maybe_old_linkable, maybe_disk_linkable) of
514 (Nothing, Nothing) -> []
515 (Nothing, Just di) -> [di]
516 (Just ui, Nothing) -> [ui]
518 | linkableTime ui >= linkableTime di -> [ui]
521 -- only linkables newer than the source code are valid
522 let maybe_src_date = ms_hs_date summary
525 = case maybe_src_date of
526 Nothing -> panic "valid_linkable_list"
528 -> filter (\li -> linkableTime li > src_date) linkable_list
530 return (valid_linkable_list ++ new_linkables)
533 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
534 maybe_getFileLinkable mod_name obj_fn
535 = do obj_exist <- doesFileExist obj_fn
539 do let stub_fn = case splitFilename3 obj_fn of
540 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
541 stub_exist <- doesFileExist stub_fn
542 obj_time <- getModificationTime obj_fn
544 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
545 else return (Just (LM obj_time mod_name [DotO obj_fn]))
548 -----------------------------------------------------------------------------
549 -- Do a pre-upsweep without use of "compile", to establish a
550 -- (downward-closed) set of stable modules for which we won't call compile.
552 preUpsweep :: [Linkable] -- new valid linkables
553 -> [Linkable] -- old linkables
554 -> [ModuleName] -- names of all mods encountered in downsweep
555 -> [ModuleName] -- accumulating stable modules
556 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
557 -> IO [ModuleName] -- stable modules
559 preUpsweep valid_lis old_lis all_home_mods stable []
561 preUpsweep valid_lis old_lis all_home_mods stable (scc0:sccs)
562 = do let scc = flattenSCC scc0
563 scc_allhomeimps :: [ModuleName]
565 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
566 all_imports_in_scc_or_stable
567 = all in_stable_or_scc scc_allhomeimps
569 = map name_of_summary scc
571 = m `elem` scc_names || m `elem` stable
573 -- now we check for valid linkables: each module in the SCC must
574 -- have a valid linkable (see getValidLinkables above), and the
575 -- newest linkable must be the same as the previous linkable for
576 -- this module (if one exists).
577 has_valid_linkable new_summary
578 = case findModuleLinkable_maybe valid_lis modname of
580 Just l -> case findModuleLinkable_maybe old_lis modname of
582 Just m -> linkableTime l == linkableTime m
583 where modname = name_of_summary new_summary
585 scc_is_stable = all_imports_in_scc_or_stable
586 && all has_valid_linkable scc
589 then preUpsweep valid_lis old_lis all_home_mods
590 (scc_names++stable) sccs
591 else preUpsweep valid_lis old_lis all_home_mods
597 -- Helper for preUpsweep. Assuming that new_summary's imports are all
598 -- stable (in the sense of preUpsweep), determine if new_summary is itself
599 -- stable, and, if so, in batch mode, return its linkable.
600 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
601 findInSummaries old_summaries mod_name
602 = [s | s <- old_summaries, name_of_summary s == mod_name]
604 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
605 findModInSummaries old_summaries mod
606 = case [s | s <- old_summaries, ms_mod s == mod] of
610 -- Return (names of) all those in modsDone who are part of a cycle
611 -- as defined by theGraph.
612 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
613 findPartiallyCompletedCycles modsDone theGraph
617 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
618 chew ((CyclicSCC vs):rest)
619 = let names_in_this_cycle = nub (map name_of_summary vs)
621 = nub ([done | done <- modsDone,
622 done `elem` names_in_this_cycle])
623 chewed_rest = chew rest
625 if not (null mods_in_this_cycle)
626 && length mods_in_this_cycle < length names_in_this_cycle
627 then mods_in_this_cycle ++ chewed_rest
631 -- Add the given (LM-form) Linkables to the UI, overwriting previous
632 -- versions if they exist.
633 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
635 = filter (not_in lis) ui ++ lis
637 not_in :: [Linkable] -> Linkable -> Bool
639 = all (\l -> linkableModName l /= mod) lis
640 where mod = linkableModName li
643 data CmThreaded -- stuff threaded through individual module compilations
644 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
647 -- Compile multiple modules, stopping as soon as an error appears.
648 -- There better had not be any cyclic groups here -- we check for them.
649 upsweep_mods :: GhciMode
651 -> UnlinkedImage -- valid linkables
652 -> (ModuleName -> [ModuleName]) -- to construct downward closures
653 -> CmThreaded -- PCS & HST & HIT
654 -> [SCC ModSummary] -- mods to do (the worklist)
655 -- ...... RETURNING ......
656 -> IO (Bool{-complete success?-},
658 [ModSummary], -- mods which succeeded
659 [Linkable]) -- new linkables
661 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
663 = return (True, threaded, [], [])
665 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
667 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
668 unwords (map (moduleNameUserString.name_of_summary) ms))
669 return (False, threaded, [], [])
671 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
672 ((AcyclicSCC mod):mods)
673 = do --case threaded of
674 -- CmThreaded pcsz hstz hitz
675 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
677 (threaded1, maybe_linkable)
678 <- upsweep_mod ghci_mode dflags oldUI threaded mod
679 (reachable_from (name_of_summary mod))
680 case maybe_linkable of
682 -> -- No errors; do the rest
683 do (restOK, threaded2, modOKs, linkables)
684 <- upsweep_mods ghci_mode dflags oldUI reachable_from
686 return (restOK, threaded2, mod:modOKs, linkable:linkables)
687 Nothing -- we got a compilation error; give up now
688 -> return (False, threaded1, [], [])
691 -- Compile a single module. Always produce a Linkable for it if
692 -- successful. If no compilation happened, return the old Linkable.
693 upsweep_mod :: GhciMode
699 -> IO (CmThreaded, Maybe Linkable)
701 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
703 let mod_name = name_of_summary summary1
704 let verb = verbosity dflags
706 let (CmThreaded pcs1 hst1 hit1) = threaded1
707 let old_iface = lookupUFM hit1 mod_name
709 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
711 source_unchanged = isJust maybe_old_linkable
713 (hst1_strictDC, hit1_strictDC)
714 = retainInTopLevelEnvs
715 (filter (/= (name_of_summary summary1)) reachable_from_here)
719 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
721 compresult <- compile ghci_mode summary1 source_unchanged
722 old_iface hst1_strictDC hit1_strictDC pcs1
726 -- Compilation "succeeded", but didn't return a new
727 -- linkable, meaning that compilation wasn't needed, and the
728 -- new details were manufactured from the old iface.
729 CompOK pcs2 new_details new_iface Nothing
730 -> do let hst2 = addToUFM hst1 mod_name new_details
731 hit2 = addToUFM hit1 mod_name new_iface
732 threaded2 = CmThreaded pcs2 hst2 hit2
734 if ghci_mode == Interactive && verb >= 1 then
735 -- if we're using an object file, tell the user
737 (LM _ _ objs@(DotO _:_))
738 -> do hPutStrLn stderr (showSDoc (space <>
739 parens (hsep (text "using":
741 [ text o | DotO o <- objs ]))))
746 return (threaded2, Just old_linkable)
748 -- Compilation really did happen, and succeeded. A new
749 -- details, iface and linkable are returned.
750 CompOK pcs2 new_details new_iface (Just new_linkable)
751 -> do let hst2 = addToUFM hst1 mod_name new_details
752 hit2 = addToUFM hit1 mod_name new_iface
753 threaded2 = CmThreaded pcs2 hst2 hit2
755 return (threaded2, Just new_linkable)
757 -- Compilation failed. compile may still have updated
760 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
761 return (threaded2, Nothing)
763 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
764 removeFromTopLevelEnvs :: [ModuleName]
765 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
766 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
767 removeFromTopLevelEnvs zap_these (hst, hit, ui)
768 = (delListFromUFM hst zap_these,
769 delListFromUFM hit zap_these,
770 filterModuleLinkables (`notElem` zap_these) ui
773 retainInTopLevelEnvs :: [ModuleName]
774 -> (HomeSymbolTable, HomeIfaceTable)
775 -> (HomeSymbolTable, HomeIfaceTable)
776 retainInTopLevelEnvs keep_these (hst, hit)
777 = (retainInUFM hst keep_these,
778 retainInUFM hit keep_these
781 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
782 retainInUFM ufm keys_to_keep
783 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
785 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
787 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
788 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
789 downwards_closure_of_module summaries root
790 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
791 toEdge summ = (name_of_summary summ, ms_allimps summ)
792 res = simple_transitive_closure (map toEdge summaries) [root]
794 --trace (showSDoc (text "DC of mod" <+> ppr root
795 -- <+> text "=" <+> ppr res)) (
799 -- Calculate transitive closures from a set of roots given an adjacency list
800 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
801 simple_transitive_closure graph set
802 = let set2 = nub (concatMap dsts set ++ set)
803 dsts node = fromMaybe [] (lookup node graph)
805 if length set == length set2
807 else simple_transitive_closure graph set2
810 -- Calculate SCCs of the module graph, with or without taking into
811 -- account source imports.
812 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
813 topological_sort include_source_imports summaries
815 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
817 = (summ, name_of_summary summ,
818 (if include_source_imports
819 then ms_srcimps summ else []) ++ ms_imps summ)
821 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
822 mash_edge (summ, m, m_imports)
823 = case lookup m key_map of
824 Nothing -> panic "reverse_topological_sort"
825 Just mk -> (summ, mk,
826 -- ignore imports not from the home package
827 catMaybes (map (flip lookup key_map) m_imports))
829 edges = map toEdge summaries
830 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
831 scc_input = map mash_edge edges
832 sccs = stronglyConnComp scc_input
837 -- Chase downwards from the specified root set, returning summaries
838 -- for all home modules encountered. Only follow source-import
839 -- links. Also returns a Bool to indicate whether any of the roots
841 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
842 downsweep rootNm old_summaries
843 = do rootSummaries <- mapM getRootSummary rootNm
845 = any ((=="Main").moduleNameUserString.name_of_summary)
848 <- loop (concat (map ms_imps rootSummaries))
849 (filter (isHomeModule.ms_mod) rootSummaries)
850 return (all_summaries, a_root_is_Main)
852 getRootSummary :: FilePath -> IO ModSummary
854 | haskellish_file file
855 = do exists <- doesFileExist file
856 if exists then summariseFile file else do
857 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
859 = do exists <- doesFileExist hs_file
860 if exists then summariseFile hs_file else do
861 exists <- doesFileExist lhs_file
862 if exists then summariseFile lhs_file else do
863 getSummary (mkModuleName file)
865 hs_file = file ++ ".hs"
866 lhs_file = file ++ ".lhs"
868 getSummary :: ModuleName -> IO ModSummary
870 = do found <- findModule nm
872 Just (mod, location) -> do
873 let old_summary = findModInSummaries old_summaries mod
874 new_summary <- summarise mod location old_summary
876 Nothing -> return (fromJust old_summary)
879 Nothing -> throwDyn (OtherError
880 ("can't find module `"
881 ++ showSDoc (ppr nm) ++ "'"))
883 -- loop invariant: home_summaries doesn't contain package modules
884 loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
885 loop [] home_summaries = return home_summaries
886 loop imps home_summaries
887 = do -- all modules currently in homeSummaries
888 let all_home = map (moduleName.ms_mod) home_summaries
890 -- imports for modules we don't already have
891 let needed_imps = nub (filter (`notElem` all_home) imps)
894 needed_summaries <- mapM getSummary needed_imps
896 -- get just the "home" modules
897 let new_home_summaries
898 = filter (isHomeModule.ms_mod) needed_summaries
900 -- loop, checking the new imports
901 let new_imps = concat (map ms_imps new_home_summaries)
902 loop new_imps (new_home_summaries ++ home_summaries)
904 -----------------------------------------------------------------------------
905 -- Summarising modules
907 -- We have two types of summarisation:
909 -- * Summarise a file. This is used for the root module passed to
910 -- cmLoadModule. The file is read, and used to determine the root
911 -- module name. The module name may differ from the filename.
913 -- * Summarise a module. We are given a module name, and must provide
914 -- a summary. The finder is used to locate the file in which the module
917 summariseFile :: FilePath -> IO ModSummary
919 = do hspp_fn <- preprocess file
920 modsrc <- readFile hspp_fn
922 let (srcimps,imps,mod_name) = getImports modsrc
923 (path, basename, ext) = splitFilename3 file
926 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
929 <- case ml_hs_file location of
930 Nothing -> return Nothing
931 Just src_fn -> maybe_getModificationTime src_fn
933 return (ModSummary mod
934 location{ml_hspp_file=Just hspp_fn}
938 -- Summarise a module, and pick up source and timestamp.
939 summarise :: Module -> ModuleLocation -> Maybe ModSummary
940 -> IO (Maybe ModSummary)
941 summarise mod location old_summary
943 = do let hs_fn = unJust "summarise" (ml_hs_file location)
946 <- case ml_hs_file location of
947 Nothing -> return Nothing
948 Just src_fn -> maybe_getModificationTime src_fn
950 -- return the cached summary if the source didn't change
951 case old_summary of {
952 Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
955 hspp_fn <- preprocess hs_fn
956 modsrc <- readFile hspp_fn
957 let (srcimps,imps,mod_name) = getImports modsrc
960 <- case ml_hs_file location of
961 Nothing -> return Nothing
962 Just src_fn -> maybe_getModificationTime src_fn
964 when (mod_name /= moduleName mod) $
966 (showSDoc (text "file name does not match module name: "
967 <+> ppr (moduleName mod) <+> text "vs"
970 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
972 maybe_src_timestamp))
976 = return (Just (ModSummary mod location [] [] Nothing))
978 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
979 maybe_getModificationTime fn
980 = (do time <- getModificationTime fn
983 (\err -> return Nothing)