2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
8 cmInit, -- :: GhciMode -> IO CmState
10 cmLoadModule, -- :: CmState -> FilePath -> IO (CmState, [String])
12 cmUnload, -- :: CmState -> IO CmState
14 cmSetContext, -- :: CmState -> String -> IO CmState
16 cmGetContext, -- :: CmState -> IO String
19 cmRunStmt, -- :: CmState -> DynFlags -> String -> IO (CmState, [Name])
21 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
22 -- -> IO (CmState, Maybe String)
24 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
26 cmCompileExpr,-- :: CmState -> DynFlags -> String
27 -- -> IO (CmState, Maybe HValue)#endif
29 CmState, emptyCmState -- abstract
33 #include "HsVersions.h"
38 import RnEnv ( unQualInScope )
39 import Id ( idType, idName )
40 import Name ( Name, lookupNameEnv, extendNameEnvList,
42 import RdrName ( emptyRdrEnv )
43 import Module ( Module, ModuleName, moduleName, isHomeModule,
44 mkModuleName, moduleNameUserString, moduleUserString )
45 import CmStaticInfo ( GhciMode(..) )
48 import Type ( tidyType )
49 import VarEnv ( emptyTidyEnv )
51 import HscMain ( initPersistentCompilerState )
54 import Unique ( Uniquable )
55 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
56 import DriverFlags ( getDynFlags )
58 import DriverUtil ( splitFilename3 )
59 import ErrUtils ( showPass )
65 import CmdLineOpts ( DynFlags(..) )
69 import Interpreter ( HValue )
70 import HscMain ( hscStmt )
71 import PrelGHC ( unsafeCoerce# )
75 import Exception ( throwDyn )
78 import Time ( ClockTime )
79 import Directory ( getModificationTime, doesFileExist )
88 -- Persistent state for the entire system
91 hst :: HomeSymbolTable, -- home symbol table
92 hit :: HomeIfaceTable, -- home interface table
93 ui :: UnlinkedImage, -- the unlinked images
94 mg :: ModuleGraph, -- the module graph
95 gmode :: GhciMode, -- NEVER CHANGES
96 ic :: InteractiveContext, -- command-line binding info
98 pcs :: PersistentCompilerState, -- compile's persistent state
99 pls :: PersistentLinkerState -- link's persistent state
102 emptyCmState :: GhciMode -> Module -> IO CmState
103 emptyCmState gmode mod
104 = do pcs <- initPersistentCompilerState
106 return (CmState { hst = emptySymbolTable,
107 hit = emptyIfaceTable,
111 ic = emptyInteractiveContext mod,
115 emptyInteractiveContext mod
116 = InteractiveContext { ic_module = mod,
117 ic_rn_env = emptyRdrEnv,
118 ic_type_env = emptyTypeEnv }
120 defaultCurrentModuleName = mkModuleName "Prelude"
121 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
124 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
125 emptyUI :: UnlinkedImage
128 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
129 emptyMG :: ModuleGraph
132 -----------------------------------------------------------------------------
133 -- Produce an initial CmState.
135 cmInit :: GhciMode -> IO CmState
137 prel <- moduleNameToModule defaultCurrentModuleName
138 writeIORef defaultCurrentModule prel
139 emptyCmState mode prel
141 -----------------------------------------------------------------------------
142 -- Setting the context doesn't throw away any bindings; the bindings
143 -- we've built up in the InteractiveContext simply move to the new
144 -- module. They always shadow anything in scope in the current context.
146 cmSetContext :: CmState -> String -> IO CmState
147 cmSetContext cmstate str
148 = do let mn = mkModuleName str
149 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
151 m <- case lookup mn modules_loaded of
154 mod <- moduleNameToModule mn
156 then throwDyn (OtherError (showSDoc
157 (quotes (ppr (moduleName mod))
158 <+> text "is not currently loaded")))
161 return cmstate{ ic = (ic cmstate){ic_module=m} }
163 cmGetContext :: CmState -> IO String
164 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
166 moduleNameToModule :: ModuleName -> IO Module
167 moduleNameToModule mn
168 = do maybe_stuff <- findModule mn
170 Nothing -> throwDyn (OtherError ("can't find module `"
171 ++ moduleNameUserString mn ++ "'"))
172 Just (m,_) -> return m
174 -----------------------------------------------------------------------------
175 -- cmRunStmt: Run a statement/expr.
178 cmRunStmt :: CmState -> DynFlags -> String
179 -> IO (CmState, -- new state
180 [Name]) -- names bound by this evaluation
181 cmRunStmt cmstate dflags expr
183 let InteractiveContext {
185 ic_type_env = type_env,
186 ic_module = this_mod } = icontext
188 (new_pcs, maybe_stuff)
189 <- hscStmt dflags hst hit pcs icontext expr
192 Nothing -> return (cmstate{ pcs=new_pcs }, [])
193 Just (ids, bcos) -> do
195 -- update the interactive context
197 new_rn_env = extendLocalRdrEnv rn_env (map idName ids)
199 -- Extend the renamer-env from bound_ids, not
200 -- bound_names, because the latter may contain
201 -- [it] when the former is empty
202 new_type_env = extendNameEnvList type_env
203 [ (getName id, AnId id) | id <- ids]
205 new_ic = icontext { ic_rn_env = new_rn_env,
206 ic_type_env = new_type_env }
209 hval <- linkExpr pls bcos
212 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
213 hvals <- thing_to_run
215 -- get the newly bound things, and bind them
216 let names = map idName ids
217 new_pls <- updateClosureEnv pls (zip names hvals)
219 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
221 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
224 -----------------------------------------------------------------------------
225 -- cmTypeOfExpr: returns a string representing the type of an expression
228 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
229 cmTypeOfExpr cmstate dflags expr
230 = do (new_cmstate, names)
231 <- cmRunStmt cmstate dflags ("let __cmTypeOfExpr=" ++ expr)
233 [name] -> do maybe_tystr <- cmTypeOfName new_cmstate name
234 return (new_cmstate, maybe_tystr)
235 _other -> return (new_cmstate, Nothing)
238 -----------------------------------------------------------------------------
239 -- cmTypeOfName: returns a string representing the type of a name.
242 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
243 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
244 = case lookupNameEnv (ic_type_env ic) name of
245 Nothing -> return Nothing
247 let pit = pcs_PIT pcs
248 modname = moduleName (ic_module ic)
249 ty = tidyType emptyTidyEnv (idType id)
250 str = case lookupIfaceByModName hit pit modname of
251 Nothing -> showSDoc (ppr ty)
252 Just iface -> showSDocForUser unqual (ppr ty)
253 where unqual = unQualInScope (mi_globals iface)
256 _ -> panic "cmTypeOfName"
259 -----------------------------------------------------------------------------
260 -- cmCompileExpr: compile an expression and deliver an HValue
263 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
264 cmCompileExpr cmstate dflags expr
266 let InteractiveContext {
268 ic_type_env = type_env,
269 ic_module = this_mod } = icontext
271 (new_pcs, maybe_stuff)
272 <- hscStmt dflags hst hit pcs icontext
273 ("let __cmCompileExpr="++expr)
276 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
277 Just (ids, bcos) -> do
280 hval <- linkExpr pls bcos
283 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
284 hvals <- thing_to_run
287 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
288 _ -> panic "cmCompileExpr"
291 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
294 -----------------------------------------------------------------------------
295 -- cmInfo: return "info" about an expression. The info might be:
297 -- * its type, for an expression,
298 -- * the class definition, for a class
299 -- * the datatype definition, for a tycon (or synonym)
300 -- * the export list, for a module
302 -- Can be used to find the type of the last expression compiled, by looking
305 cmInfo :: CmState -> String -> IO (Maybe String)
307 = do error "cmInfo not implemented yet"
309 -----------------------------------------------------------------------------
310 -- Unload the compilation manager's state: everything it knows about the
311 -- current collection of modules in the Home package.
313 cmUnload :: CmState -> IO CmState
315 = do -- Throw away the old home dir cache
317 -- Throw away the HIT and the HST
318 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
320 CmState{ hst=hst, hit=hit } = state
321 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
323 -----------------------------------------------------------------------------
324 -- The real business of the compilation manager: given a system state and
325 -- a module name, try and bring the module up to date, probably changing
326 -- the system state at the same time.
328 cmLoadModule :: CmState
330 -> IO (CmState, -- new state
331 Bool, -- was successful
332 [String]) -- list of modules loaded
334 cmLoadModule cmstate1 rootname
335 = do -- version 1's are the original, before downsweep
336 let pls1 = pls cmstate1
337 let pcs1 = pcs cmstate1
338 let hst1 = hst cmstate1
339 let hit1 = hit cmstate1
340 -- similarly, ui1 is the (complete) set of linkables from
341 -- the previous pass, if any.
342 let ui1 = ui cmstate1
343 let mg1 = mg cmstate1
344 let ic1 = ic cmstate1
346 let ghci_mode = gmode cmstate1 -- this never changes
348 -- Do the downsweep to reestablish the module graph
349 dflags <- getDynFlags
350 let verb = verbosity dflags
352 showPass dflags "Chasing dependencies"
353 when (verb >= 1 && ghci_mode == Batch) $
354 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
356 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
357 let mg2unsorted_names = map name_of_summary mg2unsorted
359 -- reachable_from follows source as well as normal imports
360 let reachable_from :: ModuleName -> [ModuleName]
361 reachable_from = downwards_closure_of_module mg2unsorted
363 -- should be cycle free; ignores 'import source's
364 let mg2 = topological_sort False mg2unsorted
365 -- ... whereas this takes them into account. Used for
366 -- backing out partially complete cycles following a failed
367 -- upsweep, and for removing from hst/hit all the modules
368 -- not in strict downwards closure, during calls to compile.
369 let mg2_with_srcimps = topological_sort True mg2unsorted
371 -- Sort out which linkables we wish to keep in the unlinked image.
372 -- See getValidLinkables below for details.
373 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
376 -- Figure out a stable set of modules which can be retained
377 -- the top level envs, to avoid upsweeping them. Goes to a
378 -- bit of trouble to avoid upsweeping module cycles.
380 -- Construct a set S of stable modules like this:
381 -- Travel upwards, over the sccified graph. For each scc
382 -- of modules ms, add ms to S only if:
383 -- 1. All home imports of ms are either in ms or S
384 -- 2. A valid linkable exists for each module in ms
386 stable_mods <- preUpsweep valid_linkables hit1
387 mg2unsorted_names [] mg2_with_srcimps
390 = concatMap (findInSummaries mg2unsorted) stable_mods
393 = filter (\m -> linkableModName m `elem` stable_mods)
397 putStrLn (showSDoc (text "Stable modules:"
398 <+> sep (map (text.moduleNameUserString) stable_mods)))
400 -- unload any modules which aren't going to be re-linked this
402 pls2 <- unload ghci_mode dflags stable_linkables pls1
404 -- We could at this point detect cycles which aren't broken by
405 -- a source-import, and complain immediately, but it seems better
406 -- to let upsweep_mods do this, so at least some useful work gets
407 -- done before the upsweep is abandoned.
409 = filter (\scc -> any (`notElem` stable_mods)
410 (map name_of_summary (flattenSCC scc)))
413 --hPutStrLn stderr "after tsort:\n"
414 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
416 -- Because we don't take into account source imports when doing
417 -- the topological sort, there shouldn't be any cycles in mg2.
418 -- If there is, we complain and give up -- the user needs to
419 -- break the cycle using a boot file.
421 -- Now do the upsweep, calling compile for each module in
422 -- turn. Final result is version 3 of everything.
424 let threaded2 = CmThreaded pcs1 hst1 hit1
426 (upsweep_complete_success, threaded3, modsUpswept, newLis)
427 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
428 threaded2 upsweep_these
430 let ui3 = add_to_ui valid_linkables newLis
431 let (CmThreaded pcs3 hst3 hit3) = threaded3
433 -- At this point, modsUpswept and newLis should have the same
434 -- length, so there is one new (or old) linkable for each
435 -- mod which was processed (passed to compile).
437 -- Make modsDone be the summaries for each home module now
438 -- available; this should equal the domains of hst3 and hit3.
439 -- (NOT STRICTLY TRUE if an interactive session was started
440 -- with some object on disk ???)
441 -- Get in in a roughly top .. bottom order (hence reverse).
443 let modsDone = reverse modsUpswept ++ stable_summaries
445 -- Try and do linking in some form, depending on whether the
446 -- upsweep was completely or only partially successful.
448 if upsweep_complete_success
451 -- Easy; just relink it all.
452 do when (verb >= 2) $
453 hPutStrLn stderr "Upsweep completely successful."
455 -- clean up after ourselves
456 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
458 -- link everything together
459 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
461 cmLoadFinish True linkresult
462 hst3 hit3 ui3 modsDone ghci_mode pcs3
465 -- Tricky. We need to back out the effects of compiling any
466 -- half-done cycles, both so as to clean up the top level envs
467 -- and to avoid telling the interactive linker to link them.
468 do when (verb >= 2) $
469 hPutStrLn stderr "Upsweep partially successful."
472 = map name_of_summary modsDone
473 let mods_to_zap_names
474 = findPartiallyCompletedCycles modsDone_names
476 let (hst4, hit4, ui4)
477 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
480 = filter ((`notElem` mods_to_zap_names).name_of_summary)
483 -- clean up after ourselves
484 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
486 -- link everything together
487 linkresult <- link ghci_mode dflags False ui4 pls2
489 cmLoadFinish False linkresult
490 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
493 -- Finish up after a cmLoad.
495 -- Empty the interactive context and set the module context to the topmost
496 -- newly loaded module, or the Prelude if none were loaded.
497 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
498 = do case linkresult of {
499 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
502 def_mod <- readIORef defaultCurrentModule
503 let current_mod = case mods of
507 new_ic = emptyInteractiveContext current_mod
509 new_cmstate = CmState{ hst=hst, hit=hit,
511 gmode=ghci_mode, pcs=pcs,
514 mods_loaded = map (moduleNameUserString.name_of_summary) mods
516 return (new_cmstate, ok, mods_loaded)
519 ppFilesFromSummaries summaries
520 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
522 -----------------------------------------------------------------------------
525 -- For each module (or SCC of modules), we take:
527 -- - an on-disk linkable, if this is the first time around and one
530 -- - the old linkable, otherwise (and if one is available).
532 -- and we throw away the linkable if it is older than the source
533 -- file. We ignore the on-disk linkables unless all of the dependents
534 -- of this SCC also have on-disk linkables.
536 -- If a module has a valid linkable, then it may be STABLE (see below),
537 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
540 -- ToDo: this pass could be merged with the preUpsweep.
543 :: [Linkable] -- old linkables
544 -> [ModuleName] -- all home modules
545 -> [SCC ModSummary] -- all modules in the program, dependency order
546 -> IO [Linkable] -- still-valid linkables
548 getValidLinkables old_linkables all_home_mods module_graph
549 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
551 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
553 scc = flattenSCC scc0
554 scc_names = map name_of_summary scc
555 home_module m = m `elem` all_home_mods && m `notElem` scc_names
556 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
558 has_object m = case findModuleLinkable_maybe new_linkables m of
560 Just l -> isObjectLinkable l
562 objects_allowed = all has_object scc_allhomeimps
566 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
568 -- since an scc can contain only all objects or no objects at all,
569 -- we have to check whether we got all objects or not, and re-do
570 -- the linkable check if not.
572 <- if objects_allowed && not (all isObjectLinkable these_linkables)
573 then foldM (getValidLinkable old_linkables False) [] scc
574 else return these_linkables
576 return (adjusted_linkables ++ new_linkables)
579 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
581 getValidLinkable old_linkables objects_allowed new_linkables summary
582 = do let mod_name = name_of_summary summary
585 <- if (not objects_allowed)
587 else case ml_obj_file (ms_location summary) of
588 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
589 Nothing -> return Nothing
591 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
594 Just l | not (isObjectLinkable l) || stillThere l
596 -- ToDo: emit a warning if not (stillThere l)
600 -- make sure that if we had an old disk linkable around, that it's
601 -- still there on the disk (in case we need to re-link it).
603 case maybe_disk_linkable of
605 Just l_disk -> linkableTime l == linkableTime l_disk
607 -- we only look for objects on disk the first time around;
608 -- if the user compiles a module on the side during a GHCi session,
609 -- it won't be picked up until the next ":load". This is what the
610 -- "null old_linkables" test below is.
611 linkable | null old_linkables = maybeToList maybe_disk_linkable
612 | otherwise = maybeToList maybe_old_linkable
614 -- only linkables newer than the source code are valid
615 maybe_src_date = ms_hs_date summary
618 = case maybe_src_date of
619 Nothing -> panic "valid_linkable_list"
621 -> filter (\l -> linkableTime l > src_date) linkable
623 return (valid_linkable ++ new_linkables)
627 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
628 maybe_getFileLinkable mod_name obj_fn
629 = do obj_exist <- doesFileExist obj_fn
633 do let stub_fn = case splitFilename3 obj_fn of
634 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
635 stub_exist <- doesFileExist stub_fn
636 obj_time <- getModificationTime obj_fn
638 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
639 else return (Just (LM obj_time mod_name [DotO obj_fn]))
642 -----------------------------------------------------------------------------
643 -- Do a pre-upsweep without use of "compile", to establish a
644 -- (downward-closed) set of stable modules for which we won't call compile.
647 -- * has a valid linkable (see getValidLinkables above)
648 -- * depends only on stable modules
649 -- * has an interface in the HIT (interactive mode only)
651 preUpsweep :: [Linkable] -- new valid linkables
653 -> [ModuleName] -- names of all mods encountered in downsweep
654 -> [ModuleName] -- accumulating stable modules
655 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
656 -> IO [ModuleName] -- stable modules
658 preUpsweep valid_lis hit all_home_mods stable [] = return stable
659 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
660 = do let scc = flattenSCC scc0
661 scc_allhomeimps :: [ModuleName]
663 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
664 all_imports_in_scc_or_stable
665 = all in_stable_or_scc scc_allhomeimps
667 = map name_of_summary scc
669 = m `elem` scc_names || m `elem` stable
671 -- now we check for valid linkables: each module in the SCC must
672 -- have a valid linkable (see getValidLinkables above).
673 has_valid_linkable new_summary
674 = isJust (findModuleLinkable_maybe valid_lis modname)
675 where modname = name_of_summary new_summary
677 has_interface summary = ms_mod summary `elemUFM` hit
679 scc_is_stable = all_imports_in_scc_or_stable
680 && all has_valid_linkable scc
681 && all has_interface scc
684 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
685 else preUpsweep valid_lis hit all_home_mods stable sccs
688 -- Helper for preUpsweep. Assuming that new_summary's imports are all
689 -- stable (in the sense of preUpsweep), determine if new_summary is itself
690 -- stable, and, if so, in batch mode, return its linkable.
691 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
692 findInSummaries old_summaries mod_name
693 = [s | s <- old_summaries, name_of_summary s == mod_name]
695 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
696 findModInSummaries old_summaries mod
697 = case [s | s <- old_summaries, ms_mod s == mod] of
701 -- Return (names of) all those in modsDone who are part of a cycle
702 -- as defined by theGraph.
703 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
704 findPartiallyCompletedCycles modsDone theGraph
708 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
709 chew ((CyclicSCC vs):rest)
710 = let names_in_this_cycle = nub (map name_of_summary vs)
712 = nub ([done | done <- modsDone,
713 done `elem` names_in_this_cycle])
714 chewed_rest = chew rest
716 if not (null mods_in_this_cycle)
717 && length mods_in_this_cycle < length names_in_this_cycle
718 then mods_in_this_cycle ++ chewed_rest
722 -- Add the given (LM-form) Linkables to the UI, overwriting previous
723 -- versions if they exist.
724 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
726 = filter (not_in lis) ui ++ lis
728 not_in :: [Linkable] -> Linkable -> Bool
730 = all (\l -> linkableModName l /= mod) lis
731 where mod = linkableModName li
734 data CmThreaded -- stuff threaded through individual module compilations
735 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
738 -- Compile multiple modules, stopping as soon as an error appears.
739 -- There better had not be any cyclic groups here -- we check for them.
740 upsweep_mods :: GhciMode
742 -> UnlinkedImage -- valid linkables
743 -> (ModuleName -> [ModuleName]) -- to construct downward closures
744 -> CmThreaded -- PCS & HST & HIT
745 -> [SCC ModSummary] -- mods to do (the worklist)
746 -- ...... RETURNING ......
747 -> IO (Bool{-complete success?-},
749 [ModSummary], -- mods which succeeded
750 [Linkable]) -- new linkables
752 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
754 = return (True, threaded, [], [])
756 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
758 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
759 unwords (map (moduleNameUserString.name_of_summary) ms))
760 return (False, threaded, [], [])
762 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
763 ((AcyclicSCC mod):mods)
764 = do --case threaded of
765 -- CmThreaded pcsz hstz hitz
766 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
768 (threaded1, maybe_linkable)
769 <- upsweep_mod ghci_mode dflags oldUI threaded mod
770 (reachable_from (name_of_summary mod))
771 case maybe_linkable of
773 -> -- No errors; do the rest
774 do (restOK, threaded2, modOKs, linkables)
775 <- upsweep_mods ghci_mode dflags oldUI reachable_from
777 return (restOK, threaded2, mod:modOKs, linkable:linkables)
778 Nothing -- we got a compilation error; give up now
779 -> return (False, threaded1, [], [])
782 -- Compile a single module. Always produce a Linkable for it if
783 -- successful. If no compilation happened, return the old Linkable.
784 upsweep_mod :: GhciMode
790 -> IO (CmThreaded, Maybe Linkable)
792 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
794 let mod_name = name_of_summary summary1
795 let verb = verbosity dflags
797 let (CmThreaded pcs1 hst1 hit1) = threaded1
798 let old_iface = lookupUFM hit1 mod_name
800 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
802 source_unchanged = isJust maybe_old_linkable
804 (hst1_strictDC, hit1_strictDC)
805 = retainInTopLevelEnvs
806 (filter (/= (name_of_summary summary1)) reachable_from_here)
810 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
812 compresult <- compile ghci_mode summary1 source_unchanged
813 old_iface hst1_strictDC hit1_strictDC pcs1
817 -- Compilation "succeeded", but didn't return a new
818 -- linkable, meaning that compilation wasn't needed, and the
819 -- new details were manufactured from the old iface.
820 CompOK pcs2 new_details new_iface Nothing
821 -> do let hst2 = addToUFM hst1 mod_name new_details
822 hit2 = addToUFM hit1 mod_name new_iface
823 threaded2 = CmThreaded pcs2 hst2 hit2
825 if ghci_mode == Interactive && verb >= 1 then
826 -- if we're using an object file, tell the user
828 (LM _ _ objs@(DotO _:_))
829 -> do hPutStrLn stderr (showSDoc (space <>
830 parens (hsep (text "using":
832 [ text o | DotO o <- objs ]))))
837 return (threaded2, Just old_linkable)
839 -- Compilation really did happen, and succeeded. A new
840 -- details, iface and linkable are returned.
841 CompOK pcs2 new_details new_iface (Just new_linkable)
842 -> do let hst2 = addToUFM hst1 mod_name new_details
843 hit2 = addToUFM hit1 mod_name new_iface
844 threaded2 = CmThreaded pcs2 hst2 hit2
846 return (threaded2, Just new_linkable)
848 -- Compilation failed. compile may still have updated
851 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
852 return (threaded2, Nothing)
854 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
855 removeFromTopLevelEnvs :: [ModuleName]
856 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
857 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
858 removeFromTopLevelEnvs zap_these (hst, hit, ui)
859 = (delListFromUFM hst zap_these,
860 delListFromUFM hit zap_these,
861 filterModuleLinkables (`notElem` zap_these) ui
864 retainInTopLevelEnvs :: [ModuleName]
865 -> (HomeSymbolTable, HomeIfaceTable)
866 -> (HomeSymbolTable, HomeIfaceTable)
867 retainInTopLevelEnvs keep_these (hst, hit)
868 = (retainInUFM hst keep_these,
869 retainInUFM hit keep_these
872 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
873 retainInUFM ufm keys_to_keep
874 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
876 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
878 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
879 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
880 downwards_closure_of_module summaries root
881 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
882 toEdge summ = (name_of_summary summ, ms_allimps summ)
883 res = simple_transitive_closure (map toEdge summaries) [root]
885 --trace (showSDoc (text "DC of mod" <+> ppr root
886 -- <+> text "=" <+> ppr res)) (
890 -- Calculate transitive closures from a set of roots given an adjacency list
891 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
892 simple_transitive_closure graph set
893 = let set2 = nub (concatMap dsts set ++ set)
894 dsts node = fromMaybe [] (lookup node graph)
896 if length set == length set2
898 else simple_transitive_closure graph set2
901 -- Calculate SCCs of the module graph, with or without taking into
902 -- account source imports.
903 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
904 topological_sort include_source_imports summaries
906 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
908 = (summ, name_of_summary summ,
909 (if include_source_imports
910 then ms_srcimps summ else []) ++ ms_imps summ)
912 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
913 mash_edge (summ, m, m_imports)
914 = case lookup m key_map of
915 Nothing -> panic "reverse_topological_sort"
916 Just mk -> (summ, mk,
917 -- ignore imports not from the home package
918 catMaybes (map (flip lookup key_map) m_imports))
920 edges = map toEdge summaries
921 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
922 scc_input = map mash_edge edges
923 sccs = stronglyConnComp scc_input
928 -- Chase downwards from the specified root set, returning summaries
929 -- for all home modules encountered. Only follow source-import
930 -- links. Also returns a Bool to indicate whether any of the roots
932 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
933 downsweep rootNm old_summaries
934 = do rootSummaries <- mapM getRootSummary rootNm
936 = any ((=="Main").moduleNameUserString.name_of_summary)
939 <- loop (concat (map ms_imps rootSummaries))
940 (filter (isHomeModule.ms_mod) rootSummaries)
941 return (all_summaries, a_root_is_Main)
943 getRootSummary :: FilePath -> IO ModSummary
945 | haskellish_file file
946 = do exists <- doesFileExist file
947 if exists then summariseFile file else do
948 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
950 = do exists <- doesFileExist hs_file
951 if exists then summariseFile hs_file else do
952 exists <- doesFileExist lhs_file
953 if exists then summariseFile lhs_file else do
954 getSummary (mkModuleName file)
956 hs_file = file ++ ".hs"
957 lhs_file = file ++ ".lhs"
959 getSummary :: ModuleName -> IO ModSummary
961 = do found <- findModule nm
963 Just (mod, location) -> do
964 let old_summary = findModInSummaries old_summaries mod
965 new_summary <- summarise mod location old_summary
967 Nothing -> return (fromJust old_summary)
970 Nothing -> throwDyn (OtherError
971 ("can't find module `"
972 ++ showSDoc (ppr nm) ++ "'"))
974 -- loop invariant: home_summaries doesn't contain package modules
975 loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
976 loop [] home_summaries = return home_summaries
977 loop imps home_summaries
978 = do -- all modules currently in homeSummaries
979 let all_home = map (moduleName.ms_mod) home_summaries
981 -- imports for modules we don't already have
982 let needed_imps = nub (filter (`notElem` all_home) imps)
985 needed_summaries <- mapM getSummary needed_imps
987 -- get just the "home" modules
988 let new_home_summaries
989 = filter (isHomeModule.ms_mod) needed_summaries
991 -- loop, checking the new imports
992 let new_imps = concat (map ms_imps new_home_summaries)
993 loop new_imps (new_home_summaries ++ home_summaries)
995 -----------------------------------------------------------------------------
996 -- Summarising modules
998 -- We have two types of summarisation:
1000 -- * Summarise a file. This is used for the root module passed to
1001 -- cmLoadModule. The file is read, and used to determine the root
1002 -- module name. The module name may differ from the filename.
1004 -- * Summarise a module. We are given a module name, and must provide
1005 -- a summary. The finder is used to locate the file in which the module
1008 summariseFile :: FilePath -> IO ModSummary
1010 = do hspp_fn <- preprocess file
1011 modsrc <- readFile hspp_fn
1013 let (srcimps,imps,mod_name) = getImports modsrc
1014 (path, basename, ext) = splitFilename3 file
1016 Just (mod, location)
1017 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1020 <- case ml_hs_file location of
1021 Nothing -> return Nothing
1022 Just src_fn -> maybe_getModificationTime src_fn
1024 return (ModSummary mod
1025 location{ml_hspp_file=Just hspp_fn}
1027 maybe_src_timestamp)
1029 -- Summarise a module, and pick up source and timestamp.
1030 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1031 -> IO (Maybe ModSummary)
1032 summarise mod location old_summary
1034 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1037 <- case ml_hs_file location of
1038 Nothing -> return Nothing
1039 Just src_fn -> maybe_getModificationTime src_fn
1041 -- return the cached summary if the source didn't change
1042 case old_summary of {
1043 Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
1046 hspp_fn <- preprocess hs_fn
1047 modsrc <- readFile hspp_fn
1048 let (srcimps,imps,mod_name) = getImports modsrc
1051 <- case ml_hs_file location of
1052 Nothing -> return Nothing
1053 Just src_fn -> maybe_getModificationTime src_fn
1055 when (mod_name /= moduleName mod) $
1056 throwDyn (OtherError
1057 (showSDoc (text "file name does not match module name: "
1058 <+> ppr (moduleName mod) <+> text "vs"
1061 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1063 maybe_src_timestamp))
1067 = return (Just (ModSummary mod location [] [] Nothing))
1069 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
1070 maybe_getModificationTime fn
1071 = (do time <- getModificationTime fn
1074 (\err -> return Nothing)