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 -> DynFlags -> 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 DriverFlags ( getDynFlags )
42 import HscMain ( initPersistentCompilerState )
44 import RnEnv ( unQualInScope )
45 import Id ( idType, idName )
46 import Name ( Name, NamedThing(..), nameRdrName )
48 import RdrName ( lookupRdrEnv, emptyRdrEnv )
51 import Type ( tidyType )
52 import VarEnv ( emptyTidyEnv )
54 import Unique ( Uniquable )
55 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
56 import ErrUtils ( showPass )
57 import SysTools ( cleanTempFilesExcept )
61 import CmdLineOpts ( DynFlags(..) )
65 import Interpreter ( HValue )
66 import HscMain ( hscStmt )
67 import PrelGHC ( unsafeCoerce# )
71 import Exception ( throwDyn )
74 import Directory ( getModificationTime, doesFileExist )
83 -- Persistent state for the entire system
86 hst :: HomeSymbolTable, -- home symbol table
87 hit :: HomeIfaceTable, -- home interface table
88 ui :: UnlinkedImage, -- the unlinked images
89 mg :: ModuleGraph, -- the module graph
90 gmode :: GhciMode, -- NEVER CHANGES
91 ic :: InteractiveContext, -- command-line binding info
93 pcs :: PersistentCompilerState, -- compile's persistent state
94 pls :: PersistentLinkerState -- link's persistent state
97 emptyCmState :: GhciMode -> Module -> IO CmState
98 emptyCmState gmode mod
99 = do pcs <- initPersistentCompilerState
101 return (CmState { hst = emptySymbolTable,
102 hit = emptyIfaceTable,
106 ic = emptyInteractiveContext mod,
110 emptyInteractiveContext mod
111 = InteractiveContext { ic_module = mod,
112 ic_rn_env = emptyRdrEnv,
113 ic_type_env = emptyTypeEnv }
115 defaultCurrentModuleName = mkModuleName "Prelude"
116 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
119 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
120 emptyUI :: UnlinkedImage
123 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
124 emptyMG :: ModuleGraph
127 -----------------------------------------------------------------------------
128 -- Produce an initial CmState.
130 cmInit :: GhciMode -> IO CmState
132 prel <- moduleNameToModule defaultCurrentModuleName
133 writeIORef defaultCurrentModule prel
134 emptyCmState mode prel
136 -----------------------------------------------------------------------------
137 -- Setting the context doesn't throw away any bindings; the bindings
138 -- we've built up in the InteractiveContext simply move to the new
139 -- module. They always shadow anything in scope in the current context.
141 cmSetContext :: CmState -> String -> IO CmState
142 cmSetContext cmstate str
143 = do let mn = mkModuleName str
144 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
146 m <- case lookup mn modules_loaded of
149 mod <- moduleNameToModule mn
151 then throwDyn (CmdLineError (showSDoc
152 (quotes (ppr (moduleName mod))
153 <+> text "is not currently loaded")))
156 return cmstate{ ic = (ic cmstate){ic_module=m} }
158 cmGetContext :: CmState -> IO String
159 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
161 moduleNameToModule :: ModuleName -> IO Module
162 moduleNameToModule mn
163 = do maybe_stuff <- findModule mn
165 Nothing -> throwDyn (CmdLineError ("can't find module `"
166 ++ moduleNameUserString mn ++ "'"))
167 Just (m,_) -> return m
169 -----------------------------------------------------------------------------
170 -- cmRunStmt: Run a statement/expr.
173 cmRunStmt :: CmState -> DynFlags -> String
174 -> IO (CmState, -- new state
175 [Name]) -- names bound by this evaluation
176 cmRunStmt cmstate dflags expr
178 let InteractiveContext {
180 ic_type_env = type_env,
181 ic_module = this_mod } = icontext
183 (new_pcs, maybe_stuff)
184 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
187 Nothing -> return (cmstate{ pcs=new_pcs }, [])
188 Just (ids, _, bcos) -> do
190 -- update the interactive context
192 names = map idName ids
194 -- these names have just been shadowed
195 shadowed = [ n | r <- map nameRdrName names,
196 Just n <- [lookupRdrEnv rn_env r] ]
198 new_rn_env = extendLocalRdrEnv rn_env names
200 -- remove any shadowed bindings from the type_env
201 filtered_type_env = delListFromNameEnv type_env shadowed
203 new_type_env = extendNameEnvList filtered_type_env
204 [ (getName id, AnId id) | id <- ids]
206 new_ic = icontext { ic_rn_env = new_rn_env,
207 ic_type_env = new_type_env }
210 hval <- linkExpr pls bcos
213 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
214 hvals <- thing_to_run
216 -- Get the newly bound things, and bind them. Don't forget
217 -- to delete any shadowed bindings from the closure_env, lest
218 -- we end up with a space leak.
219 pls <- delListFromClosureEnv pls shadowed
220 new_pls <- addListToClosureEnv pls (zip names hvals)
222 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
224 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
227 -----------------------------------------------------------------------------
228 -- cmTypeOfExpr: returns a string representing the type of an expression
231 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
232 cmTypeOfExpr cmstate dflags expr
233 = do (new_pcs, maybe_stuff)
234 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
236 let new_cmstate = cmstate{pcs = new_pcs}
239 Nothing -> return (new_cmstate, Nothing)
241 let pit = pcs_PIT pcs
242 modname = moduleName (ic_module ic)
243 tidy_ty = tidyType emptyTidyEnv ty
244 str = case lookupIfaceByModName hit pit modname of
245 Nothing -> showSDoc (ppr tidy_ty)
246 Just iface -> showSDocForUser unqual (ppr tidy_ty)
247 where unqual = unQualInScope (mi_globals iface)
248 in return (new_cmstate, Just str)
250 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
253 -----------------------------------------------------------------------------
254 -- cmTypeOfName: returns a string representing the type of a name.
257 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
258 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
259 = case lookupNameEnv (ic_type_env ic) name of
260 Nothing -> return Nothing
262 let pit = pcs_PIT pcs
263 modname = moduleName (ic_module ic)
264 ty = tidyType emptyTidyEnv (idType id)
265 str = case lookupIfaceByModName hit pit modname of
266 Nothing -> showSDoc (ppr ty)
267 Just iface -> showSDocForUser unqual (ppr ty)
268 where unqual = unQualInScope (mi_globals iface)
271 _ -> panic "cmTypeOfName"
274 -----------------------------------------------------------------------------
275 -- cmCompileExpr: compile an expression and deliver an HValue
278 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
279 cmCompileExpr cmstate dflags expr
281 let InteractiveContext {
283 ic_type_env = type_env,
284 ic_module = this_mod } = icontext
286 (new_pcs, maybe_stuff)
287 <- hscStmt dflags hst hit pcs icontext
288 ("let __cmCompileExpr = "++expr) False{-stmt-}
291 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
292 Just (ids, _, bcos) -> do
295 hval <- linkExpr pls bcos
298 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
299 hvals <- thing_to_run
302 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
303 _ -> panic "cmCompileExpr"
306 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
309 -----------------------------------------------------------------------------
310 -- cmInfo: return "info" about an expression. The info might be:
312 -- * its type, for an expression,
313 -- * the class definition, for a class
314 -- * the datatype definition, for a tycon (or synonym)
315 -- * the export list, for a module
317 -- Can be used to find the type of the last expression compiled, by looking
320 cmInfo :: CmState -> String -> IO (Maybe String)
322 = do error "cmInfo not implemented yet"
324 -----------------------------------------------------------------------------
325 -- Unload the compilation manager's state: everything it knows about the
326 -- current collection of modules in the Home package.
328 cmUnload :: CmState -> DynFlags -> IO CmState
329 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
330 = do -- Throw away the old home dir cache
333 -- Unload everything the linker knows about
334 new_pls <- CmLink.unload mode dflags [] pls
336 -- Start with a fresh CmState, but keep the PersistentCompilerState
337 new_state <- cmInit mode
338 return new_state{ pcs=pcs, pls=new_pls }
340 -----------------------------------------------------------------------------
341 -- The real business of the compilation manager: given a system state and
342 -- a module name, try and bring the module up to date, probably changing
343 -- the system state at the same time.
345 cmLoadModule :: CmState
347 -> IO (CmState, -- new state
348 Bool, -- was successful
349 [String]) -- list of modules loaded
351 cmLoadModule cmstate1 rootnames
352 = do -- version 1's are the original, before downsweep
353 let pls1 = pls cmstate1
354 let pcs1 = pcs cmstate1
355 let hst1 = hst cmstate1
356 let hit1 = hit cmstate1
357 -- similarly, ui1 is the (complete) set of linkables from
358 -- the previous pass, if any.
359 let ui1 = ui cmstate1
360 let mg1 = mg cmstate1
361 let ic1 = ic cmstate1
363 let ghci_mode = gmode cmstate1 -- this never changes
365 -- Do the downsweep to reestablish the module graph
366 dflags <- getDynFlags
367 let verb = verbosity dflags
369 showPass dflags "Chasing dependencies"
370 when (verb >= 1 && ghci_mode == Batch) $
371 hPutStrLn stderr (showSDoc (hcat [
372 text progName, text ": chasing modules from: ",
373 hcat (punctuate comma (map text rootnames))]))
375 (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
376 let mg2unsorted_names = map name_of_summary mg2unsorted
378 -- reachable_from follows source as well as normal imports
379 let reachable_from :: ModuleName -> [ModuleName]
380 reachable_from = downwards_closure_of_module mg2unsorted
382 -- should be cycle free; ignores 'import source's
383 let mg2 = topological_sort False mg2unsorted
384 -- ... whereas this takes them into account. Used for
385 -- backing out partially complete cycles following a failed
386 -- upsweep, and for removing from hst/hit all the modules
387 -- not in strict downwards closure, during calls to compile.
388 let mg2_with_srcimps = topological_sort True mg2unsorted
390 -- Sort out which linkables we wish to keep in the unlinked image.
391 -- See getValidLinkables below for details.
392 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
394 -- when (verb >= 2) $
395 -- putStrLn (showSDoc (text "Valid linkables:"
396 -- <+> ppr valid_linkables))
398 -- Figure out a stable set of modules which can be retained
399 -- the top level envs, to avoid upsweeping them. Goes to a
400 -- bit of trouble to avoid upsweeping module cycles.
402 -- Construct a set S of stable modules like this:
403 -- Travel upwards, over the sccified graph. For each scc
404 -- of modules ms, add ms to S only if:
405 -- 1. All home imports of ms are either in ms or S
406 -- 2. A valid linkable exists for each module in ms
408 stable_mods <- preUpsweep valid_linkables hit1
409 mg2unsorted_names [] mg2_with_srcimps
412 = concatMap (findInSummaries mg2unsorted) stable_mods
415 = filter (\m -> linkableModName m `elem` stable_mods)
419 putStrLn (showSDoc (text "Stable modules:"
420 <+> sep (map (text.moduleNameUserString) stable_mods)))
422 -- unload any modules which aren't going to be re-linked this
424 pls2 <- unload ghci_mode dflags stable_linkables pls1
426 -- We could at this point detect cycles which aren't broken by
427 -- a source-import, and complain immediately, but it seems better
428 -- to let upsweep_mods do this, so at least some useful work gets
429 -- done before the upsweep is abandoned.
431 = filter (\scc -> any (`notElem` stable_mods)
432 (map name_of_summary (flattenSCC scc)))
435 --hPutStrLn stderr "after tsort:\n"
436 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
438 -- Because we don't take into account source imports when doing
439 -- the topological sort, there shouldn't be any cycles in mg2.
440 -- If there is, we complain and give up -- the user needs to
441 -- break the cycle using a boot file.
443 -- Now do the upsweep, calling compile for each module in
444 -- turn. Final result is version 3 of everything.
446 let threaded2 = CmThreaded pcs1 hst1 hit1
448 (upsweep_complete_success, threaded3, modsUpswept, newLis)
449 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
450 threaded2 upsweep_these
452 let ui3 = add_to_ui valid_linkables newLis
453 let (CmThreaded pcs3 hst3 hit3) = threaded3
455 -- At this point, modsUpswept and newLis should have the same
456 -- length, so there is one new (or old) linkable for each
457 -- mod which was processed (passed to compile).
459 -- Make modsDone be the summaries for each home module now
460 -- available; this should equal the domains of hst3 and hit3.
461 -- (NOT STRICTLY TRUE if an interactive session was started
462 -- with some object on disk ???)
463 -- Get in in a roughly top .. bottom order (hence reverse).
465 let modsDone = reverse modsUpswept ++ stable_summaries
467 -- Try and do linking in some form, depending on whether the
468 -- upsweep was completely or only partially successful.
470 if upsweep_complete_success
473 -- Easy; just relink it all.
474 do when (verb >= 2) $
475 hPutStrLn stderr "Upsweep completely successful."
477 -- clean up after ourselves
478 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
480 -- link everything together
481 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
483 cmLoadFinish True linkresult
484 hst3 hit3 ui3 modsDone ghci_mode pcs3
487 -- Tricky. We need to back out the effects of compiling any
488 -- half-done cycles, both so as to clean up the top level envs
489 -- and to avoid telling the interactive linker to link them.
490 do when (verb >= 2) $
491 hPutStrLn stderr "Upsweep partially successful."
494 = map name_of_summary modsDone
495 let mods_to_zap_names
496 = findPartiallyCompletedCycles modsDone_names
499 = filter ((`notElem` mods_to_zap_names).name_of_summary)
502 let (hst4, hit4, ui4)
503 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
506 -- clean up after ourselves
507 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
509 -- link everything together
510 linkresult <- link ghci_mode dflags False ui4 pls2
512 cmLoadFinish False linkresult
513 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
516 -- Finish up after a cmLoad.
518 -- Empty the interactive context and set the module context to the topmost
519 -- newly loaded module, or the Prelude if none were loaded.
520 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
521 = do case linkresult of {
522 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
525 def_mod <- readIORef defaultCurrentModule
526 let current_mod = case mods of
530 new_ic = emptyInteractiveContext current_mod
532 new_cmstate = CmState{ hst=hst, hit=hit,
534 gmode=ghci_mode, pcs=pcs,
537 mods_loaded = map (moduleNameUserString.name_of_summary) mods
539 return (new_cmstate, ok, mods_loaded)
542 -- used to fish out the preprocess output files for the purposes
544 ppFilesFromSummaries summaries
545 = [ fn | Just fn <- map toPpFile summaries ]
548 | hspp /= ml_hs_file loc = hspp
549 | otherwise = Nothing
551 loc = ms_location sum
552 hspp = ml_hspp_file loc
555 -----------------------------------------------------------------------------
558 -- For each module (or SCC of modules), we take:
560 -- - an on-disk linkable, if this is the first time around and one
563 -- - the old linkable, otherwise (and if one is available).
565 -- and we throw away the linkable if it is older than the source
566 -- file. We ignore the on-disk linkables unless all of the dependents
567 -- of this SCC also have on-disk linkables.
569 -- If a module has a valid linkable, then it may be STABLE (see below),
570 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
573 -- ToDo: this pass could be merged with the preUpsweep.
576 :: [Linkable] -- old linkables
577 -> [ModuleName] -- all home modules
578 -> [SCC ModSummary] -- all modules in the program, dependency order
579 -> IO [Linkable] -- still-valid linkables
581 getValidLinkables old_linkables all_home_mods module_graph
582 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
584 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
586 scc = flattenSCC scc0
587 scc_names = map name_of_summary scc
588 home_module m = m `elem` all_home_mods && m `notElem` scc_names
589 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
590 -- NOTE: ms_imps, not ms_allimps above. We don't want to
591 -- force a module's SOURCE imports to be already compiled for
592 -- its object linkable to be valid.
594 has_object m = case findModuleLinkable_maybe new_linkables m of
596 Just l -> isObjectLinkable l
598 objects_allowed = all has_object scc_allhomeimps
602 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
604 -- since an scc can contain only all objects or no objects at all,
605 -- we have to check whether we got all objects or not, and re-do
606 -- the linkable check if not.
608 <- if objects_allowed && not (all isObjectLinkable these_linkables)
609 then foldM (getValidLinkable old_linkables False) [] scc
610 else return these_linkables
612 return (adjusted_linkables ++ new_linkables)
615 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
617 getValidLinkable old_linkables objects_allowed new_linkables summary
618 = do let mod_name = name_of_summary summary
621 <- if (not objects_allowed)
623 else case ml_obj_file (ms_location summary) of
624 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
625 Nothing -> return Nothing
627 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
630 Just l | not (isObjectLinkable l) || stillThere l
632 -- ToDo: emit a warning if not (stillThere l)
635 -- make sure that if we had an old disk linkable around, that it's
636 -- still there on the disk (in case we need to re-link it).
638 case maybe_disk_linkable of
640 Just l_disk -> linkableTime l == linkableTime l_disk
642 -- we only look for objects on disk the first time around;
643 -- if the user compiles a module on the side during a GHCi session,
644 -- it won't be picked up until the next ":load". This is what the
645 -- "null old_linkables" test below is.
646 linkable | null old_linkables = maybeToList maybe_disk_linkable
647 | otherwise = maybeToList maybe_old_linkable
649 -- only linkables newer than the source code are valid
650 src_date = ms_hs_date summary
653 = filter (\l -> linkableTime l >= src_date) linkable
654 -- why '>=' rather than '>' above? If the filesystem stores
655 -- times to the nearset second, we may occasionally find that
656 -- the object & source have the same modification time,
657 -- especially if the source was automatically generated
658 -- and compiled. Using >= is slightly unsafe, but it matches
661 return (valid_linkable ++ new_linkables)
664 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
665 maybe_getFileLinkable mod_name obj_fn
666 = do obj_exist <- doesFileExist obj_fn
670 do let stub_fn = case splitFilename3 obj_fn of
671 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
672 stub_exist <- doesFileExist stub_fn
673 obj_time <- getModificationTime obj_fn
675 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
676 else return (Just (LM obj_time mod_name [DotO obj_fn]))
679 -----------------------------------------------------------------------------
680 -- Do a pre-upsweep without use of "compile", to establish a
681 -- (downward-closed) set of stable modules for which we won't call compile.
684 -- * has a valid linkable (see getValidLinkables above)
685 -- * depends only on stable modules
686 -- * has an interface in the HIT (interactive mode only)
688 preUpsweep :: [Linkable] -- new valid linkables
690 -> [ModuleName] -- names of all mods encountered in downsweep
691 -> [ModuleName] -- accumulating stable modules
692 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
693 -> IO [ModuleName] -- stable modules
695 preUpsweep valid_lis hit all_home_mods stable [] = return stable
696 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
697 = do let scc = flattenSCC scc0
698 scc_allhomeimps :: [ModuleName]
700 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
701 all_imports_in_scc_or_stable
702 = all in_stable_or_scc scc_allhomeimps
704 = map name_of_summary scc
706 = m `elem` scc_names || m `elem` stable
708 -- now we check for valid linkables: each module in the SCC must
709 -- have a valid linkable (see getValidLinkables above).
710 has_valid_linkable new_summary
711 = isJust (findModuleLinkable_maybe valid_lis modname)
712 where modname = name_of_summary new_summary
714 has_interface summary = ms_mod summary `elemUFM` hit
716 scc_is_stable = all_imports_in_scc_or_stable
717 && all has_valid_linkable scc
718 && all has_interface scc
721 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
722 else preUpsweep valid_lis hit all_home_mods stable sccs
725 -- Helper for preUpsweep. Assuming that new_summary's imports are all
726 -- stable (in the sense of preUpsweep), determine if new_summary is itself
727 -- stable, and, if so, in batch mode, return its linkable.
728 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
729 findInSummaries old_summaries mod_name
730 = [s | s <- old_summaries, name_of_summary s == mod_name]
732 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
733 findModInSummaries old_summaries mod
734 = case [s | s <- old_summaries, ms_mod s == mod] of
738 -- Return (names of) all those in modsDone who are part of a cycle
739 -- as defined by theGraph.
740 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
741 findPartiallyCompletedCycles modsDone theGraph
745 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
746 chew ((CyclicSCC vs):rest)
747 = let names_in_this_cycle = nub (map name_of_summary vs)
749 = nub ([done | done <- modsDone,
750 done `elem` names_in_this_cycle])
751 chewed_rest = chew rest
753 if not (null mods_in_this_cycle)
754 && length mods_in_this_cycle < length names_in_this_cycle
755 then mods_in_this_cycle ++ chewed_rest
759 -- Add the given (LM-form) Linkables to the UI, overwriting previous
760 -- versions if they exist.
761 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
763 = filter (not_in lis) ui ++ lis
765 not_in :: [Linkable] -> Linkable -> Bool
767 = all (\l -> linkableModName l /= mod) lis
768 where mod = linkableModName li
771 data CmThreaded -- stuff threaded through individual module compilations
772 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
775 -- Compile multiple modules, stopping as soon as an error appears.
776 -- There better had not be any cyclic groups here -- we check for them.
777 upsweep_mods :: GhciMode
779 -> UnlinkedImage -- valid linkables
780 -> (ModuleName -> [ModuleName]) -- to construct downward closures
781 -> CmThreaded -- PCS & HST & HIT
782 -> [SCC ModSummary] -- mods to do (the worklist)
783 -- ...... RETURNING ......
784 -> IO (Bool{-complete success?-},
786 [ModSummary], -- mods which succeeded
787 [Linkable]) -- new linkables
789 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
791 = return (True, threaded, [], [])
793 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
795 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
796 unwords (map (moduleNameUserString.name_of_summary) ms))
797 return (False, threaded, [], [])
799 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
800 ((AcyclicSCC mod):mods)
801 = do --case threaded of
802 -- CmThreaded pcsz hstz hitz
803 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
805 (threaded1, maybe_linkable)
806 <- upsweep_mod ghci_mode dflags oldUI threaded mod
807 (reachable_from (name_of_summary mod))
808 case maybe_linkable of
810 -> -- No errors; do the rest
811 do (restOK, threaded2, modOKs, linkables)
812 <- upsweep_mods ghci_mode dflags oldUI reachable_from
814 return (restOK, threaded2, mod:modOKs, linkable:linkables)
815 Nothing -- we got a compilation error; give up now
816 -> return (False, threaded1, [], [])
819 -- Compile a single module. Always produce a Linkable for it if
820 -- successful. If no compilation happened, return the old Linkable.
821 upsweep_mod :: GhciMode
827 -> IO (CmThreaded, Maybe Linkable)
829 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
831 let mod_name = name_of_summary summary1
832 let verb = verbosity dflags
834 let (CmThreaded pcs1 hst1 hit1) = threaded1
835 let old_iface = lookupUFM hit1 mod_name
837 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
839 source_unchanged = isJust maybe_old_linkable
841 reachable_only = filter (/= (name_of_summary summary1))
844 -- in interactive mode, all home modules below us *must* have an
845 -- interface in the HIT. We never demand-load home interfaces in
847 (hst1_strictDC, hit1_strictDC, [])
848 = ASSERT(ghci_mode == Batch ||
849 all (`elemUFM` hit1) reachable_only)
850 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
853 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
856 | Just l <- maybe_old_linkable, isObjectLinkable l = True
859 compresult <- compile ghci_mode summary1 source_unchanged
860 have_object old_iface hst1_strictDC hit1_strictDC pcs1
864 -- Compilation "succeeded", and may or may not have returned a new
865 -- linkable (depending on whether compilation was actually performed
867 CompOK pcs2 new_details new_iface maybe_new_linkable
868 -> do let hst2 = addToUFM hst1 mod_name new_details
869 hit2 = addToUFM hit1 mod_name new_iface
870 threaded2 = CmThreaded pcs2 hst2 hit2
872 return (threaded2, if isJust maybe_new_linkable
873 then maybe_new_linkable
874 else Just old_linkable)
876 -- Compilation failed. compile may still have updated
879 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
880 return (threaded2, Nothing)
882 -- Filter modules in the top level envs (HST, HIT, UI).
883 retainInTopLevelEnvs :: [ModuleName]
884 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
885 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
886 retainInTopLevelEnvs keep_these (hst, hit, ui)
887 = (retainInUFM hst keep_these,
888 retainInUFM hit keep_these,
889 filterModuleLinkables (`elem` keep_these) ui
892 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
893 retainInUFM ufm keys_to_keep
894 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
896 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
898 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
899 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
900 downwards_closure_of_module summaries root
901 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
902 toEdge summ = (name_of_summary summ,
903 filter (`elem` all_mods) (ms_allimps summ))
905 all_mods = map name_of_summary summaries
907 res = simple_transitive_closure (map toEdge summaries) [root]
909 -- trace (showSDoc (text "DC of mod" <+> ppr root
910 -- <+> text "=" <+> ppr res)) $
913 -- Calculate transitive closures from a set of roots given an adjacency list
914 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
915 simple_transitive_closure graph set
916 = let set2 = nub (concatMap dsts set ++ set)
917 dsts node = fromMaybe [] (lookup node graph)
919 if length set == length set2
921 else simple_transitive_closure graph set2
924 -- Calculate SCCs of the module graph, with or without taking into
925 -- account source imports.
926 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
927 topological_sort include_source_imports summaries
929 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
931 = (summ, name_of_summary summ,
932 (if include_source_imports
933 then ms_srcimps summ else []) ++ ms_imps summ)
935 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
936 mash_edge (summ, m, m_imports)
937 = case lookup m key_map of
938 Nothing -> panic "reverse_topological_sort"
939 Just mk -> (summ, mk,
940 -- ignore imports not from the home package
941 catMaybes (map (flip lookup key_map) m_imports))
943 edges = map toEdge summaries
944 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
945 scc_input = map mash_edge edges
946 sccs = stronglyConnComp scc_input
951 -- Chase downwards from the specified root set, returning summaries
952 -- for all home modules encountered. Only follow source-import
953 -- links. Also returns a Bool to indicate whether any of the roots
955 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
956 downsweep rootNm old_summaries
957 = do rootSummaries <- mapM getRootSummary rootNm
959 = any ((=="Main").moduleNameUserString.name_of_summary)
962 <- loop (concat (map ms_imps rootSummaries))
963 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
964 let mod = ms_mod s, isHomeModule mod
966 return (all_summaries, a_root_is_Main)
968 getRootSummary :: FilePath -> IO ModSummary
970 | haskellish_src_file file
971 = do exists <- doesFileExist file
972 if exists then summariseFile file else do
973 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
975 = do exists <- doesFileExist hs_file
976 if exists then summariseFile hs_file else do
977 exists <- doesFileExist lhs_file
978 if exists then summariseFile lhs_file else do
979 let mod_name = mkModuleName file
980 maybe_summary <- getSummary mod_name
981 case maybe_summary of
982 Nothing -> packageModErr mod_name
985 hs_file = file ++ ".hs"
986 lhs_file = file ++ ".lhs"
988 getSummary :: ModuleName -> IO (Maybe ModSummary)
990 = do found <- findModule nm
992 Just (mod, location) -> do
993 let old_summary = findModInSummaries old_summaries mod
994 summarise mod location old_summary
996 Nothing -> throwDyn (CmdLineError
997 ("can't find module `"
998 ++ showSDoc (ppr nm) ++ "'"))
1000 -- loop invariant: env doesn't contain package modules
1001 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1002 loop [] env = return (moduleEnvElts env)
1004 = do -- imports for modules we don't already have
1005 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1008 needed_summaries <- mapM getSummary needed_imps
1010 -- get just the "home" modules
1011 let new_home_summaries = [ s | Just s <- needed_summaries ]
1013 -- loop, checking the new imports
1014 let new_imps = concat (map ms_imps new_home_summaries)
1015 loop new_imps (extendModuleEnvList env
1016 [ (ms_mod s, s) | s <- new_home_summaries ])
1018 -----------------------------------------------------------------------------
1019 -- Summarising modules
1021 -- We have two types of summarisation:
1023 -- * Summarise a file. This is used for the root module passed to
1024 -- cmLoadModule. The file is read, and used to determine the root
1025 -- module name. The module name may differ from the filename.
1027 -- * Summarise a module. We are given a module name, and must provide
1028 -- a summary. The finder is used to locate the file in which the module
1031 summariseFile :: FilePath -> IO ModSummary
1033 = do hspp_fn <- preprocess file
1034 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1036 let (path, basename, ext) = splitFilename3 file
1038 Just (mod, location)
1039 <- mkHomeModuleLocn mod_name (path ++ '/':basename) (Just file)
1042 <- case ml_hs_file location of
1043 Nothing -> noHsFileErr mod_name
1044 Just src_fn -> getModificationTime src_fn
1046 return (ModSummary mod
1047 location{ml_hspp_file=Just hspp_fn}
1048 srcimps imps src_timestamp)
1050 -- Summarise a module, and pick up source and timestamp.
1051 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1052 -> IO (Maybe ModSummary)
1053 summarise mod location old_summary
1054 | not (isHomeModule mod) = return Nothing
1056 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1058 case ml_hs_file location of {
1060 dflags <- getDynFlags;
1061 when (verbosity dflags >= 1) $
1062 hPutStrLn stderr ("WARNING: module `" ++
1063 moduleUserString mod ++ "' has no source file.");
1069 src_timestamp <- getModificationTime src_fn
1071 -- return the cached summary if the source didn't change
1072 case old_summary of {
1073 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1076 hspp_fn <- preprocess hs_fn
1077 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1079 when (mod_name /= moduleName mod) $
1080 throwDyn (ProgramError
1081 (showSDoc (text hs_fn
1082 <> text ": file name does not match module name"
1083 <+> quotes (ppr (moduleName mod)))))
1085 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1086 srcimps imps src_timestamp))
1092 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1095 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1096 quotes (ppr mod) <+>
1097 text "is a package module")))