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 cmInfoThing, -- :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
21 cmRunStmt, -- :: CmState -> DynFlags -> String -> IO (CmState, [Name])
23 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
24 -- -> IO (CmState, Maybe String)
26 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
28 cmCompileExpr,-- :: CmState -> DynFlags -> String
29 -- -> IO (CmState, Maybe HValue)#endif
31 CmState, emptyCmState -- abstract
35 #include "HsVersions.h"
40 import DriverFlags ( getDynFlags )
45 import HscMain ( initPersistentCompilerState, hscThing )
47 import HscMain ( initPersistentCompilerState )
50 import RnEnv ( unQualInScope )
51 import Id ( idType, idName )
52 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
55 import RdrName ( lookupRdrEnv, emptyRdrEnv )
58 import Type ( tidyType )
59 import VarEnv ( emptyTidyEnv )
61 import Unique ( Uniquable )
62 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
63 import ErrUtils ( showPass )
64 import SysTools ( cleanTempFilesExcept )
67 import BasicTypes ( Fixity, defaultFixity )
69 import CmdLineOpts ( DynFlags(..) )
74 import Interpreter ( HValue )
75 import HscMain ( hscStmt )
76 import PrelGHC ( unsafeCoerce# )
80 import Exception ( throwDyn )
83 import Directory ( getModificationTime, doesFileExist )
92 -- Persistent state for the entire system
95 hst :: HomeSymbolTable, -- home symbol table
96 hit :: HomeIfaceTable, -- home interface table
97 ui :: UnlinkedImage, -- the unlinked images
98 mg :: ModuleGraph, -- the module graph
99 gmode :: GhciMode, -- NEVER CHANGES
100 ic :: InteractiveContext, -- command-line binding info
102 pcs :: PersistentCompilerState, -- compile's persistent state
103 pls :: PersistentLinkerState -- link's persistent state
106 emptyCmState :: GhciMode -> Module -> IO CmState
107 emptyCmState gmode mod
108 = do pcs <- initPersistentCompilerState
110 return (CmState { hst = emptySymbolTable,
111 hit = emptyIfaceTable,
115 ic = emptyInteractiveContext mod,
119 emptyInteractiveContext mod
120 = InteractiveContext { ic_module = mod,
121 ic_rn_env = emptyRdrEnv,
122 ic_type_env = emptyTypeEnv }
124 defaultCurrentModuleName = mkModuleName "Prelude"
125 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
128 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
129 emptyUI :: UnlinkedImage
132 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
133 emptyMG :: ModuleGraph
136 -----------------------------------------------------------------------------
137 -- Produce an initial CmState.
139 cmInit :: GhciMode -> IO CmState
141 prel <- moduleNameToModule defaultCurrentModuleName
142 writeIORef defaultCurrentModule prel
143 emptyCmState mode prel
145 -----------------------------------------------------------------------------
146 -- Setting the context doesn't throw away any bindings; the bindings
147 -- we've built up in the InteractiveContext simply move to the new
148 -- module. They always shadow anything in scope in the current context.
150 cmSetContext :: CmState -> String -> IO CmState
151 cmSetContext cmstate str
152 = do let mn = mkModuleName str
153 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
155 m <- case lookup mn modules_loaded of
158 mod <- moduleNameToModule mn
160 then throwDyn (CmdLineError (showSDoc
161 (quotes (ppr (moduleName mod))
162 <+> text "is not currently loaded")))
165 return cmstate{ ic = (ic cmstate){ic_module=m} }
167 cmGetContext :: CmState -> IO String
168 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
170 moduleNameToModule :: ModuleName -> IO Module
171 moduleNameToModule mn
172 = do maybe_stuff <- findModule mn
174 Nothing -> throwDyn (CmdLineError ("can't find module `"
175 ++ moduleNameUserString mn ++ "'"))
176 Just (m,_) -> return m
178 -----------------------------------------------------------------------------
179 -- cmInfoThing: convert a String to a TyThing
181 -- A string may refer to more than one TyThing (eg. a constructor,
182 -- and type constructor), so we return a list of all the possible TyThings.
185 cmInfoThing :: CmState -> DynFlags -> String
186 -> IO (CmState, PrintUnqualified, [(TyThing,Fixity)])
187 cmInfoThing cmstate dflags id
188 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
189 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
190 return (cmstate{ pcs=new_pcs }, unqual, pairs)
192 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
193 unqual = getUnqual pcs hit icontext
195 getFixity :: PersistentCompilerState -> Name -> Fixity
197 | Just iface <- lookupModuleEnv iface_table (nameModule name),
198 Just fixity <- lookupNameEnv (mi_fixities iface) name
202 where iface_table | isHomePackageName name = hit
203 | otherwise = pcs_PIT pcs
206 -----------------------------------------------------------------------------
207 -- cmRunStmt: Run a statement/expr.
210 cmRunStmt :: CmState -> DynFlags -> String
211 -> IO (CmState, -- new state
212 [Name]) -- names bound by this evaluation
213 cmRunStmt cmstate dflags expr
215 let InteractiveContext {
217 ic_type_env = type_env,
218 ic_module = this_mod } = icontext
220 (new_pcs, maybe_stuff)
221 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
224 Nothing -> return (cmstate{ pcs=new_pcs }, [])
225 Just (ids, _, bcos) -> do
227 -- update the interactive context
229 names = map idName ids
231 -- these names have just been shadowed
232 shadowed = [ n | r <- map nameRdrName names,
233 Just n <- [lookupRdrEnv rn_env r] ]
235 new_rn_env = extendLocalRdrEnv rn_env names
237 -- remove any shadowed bindings from the type_env
238 filtered_type_env = delListFromNameEnv type_env shadowed
240 new_type_env = extendNameEnvList filtered_type_env
241 [ (getName id, AnId id) | id <- ids]
243 new_ic = icontext { ic_rn_env = new_rn_env,
244 ic_type_env = new_type_env }
247 hval <- linkExpr pls bcos
250 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
251 hvals <- thing_to_run
253 -- Get the newly bound things, and bind them. Don't forget
254 -- to delete any shadowed bindings from the closure_env, lest
255 -- we end up with a space leak.
256 pls <- delListFromClosureEnv pls shadowed
257 new_pls <- addListToClosureEnv pls (zip names hvals)
259 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
261 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
264 -----------------------------------------------------------------------------
265 -- cmTypeOfExpr: returns a string representing the type of an expression
268 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
269 cmTypeOfExpr cmstate dflags expr
270 = do (new_pcs, maybe_stuff)
271 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
273 let new_cmstate = cmstate{pcs = new_pcs}
276 Nothing -> return (new_cmstate, Nothing)
277 Just (_, ty, _) -> return (new_cmstate, Just str)
279 str = showSDocForUser unqual (ppr tidy_ty)
280 unqual = getUnqual pcs hit ic
281 tidy_ty = tidyType emptyTidyEnv ty
283 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
287 = case lookupIfaceByModName hit pit modname of
288 Nothing -> alwaysQualify
289 Just iface -> unQualInScope (mi_globals iface)
292 modname = moduleName (ic_module ic)
294 -----------------------------------------------------------------------------
295 -- cmTypeOfName: returns a string representing the type of a name.
298 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
299 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
300 = case lookupNameEnv (ic_type_env ic) name of
301 Nothing -> return Nothing
302 Just (AnId id) -> return (Just str)
304 unqual = getUnqual pcs hit ic
305 ty = tidyType emptyTidyEnv (idType id)
306 str = showSDocForUser unqual (ppr ty)
308 _ -> panic "cmTypeOfName"
311 -----------------------------------------------------------------------------
312 -- cmCompileExpr: compile an expression and deliver an HValue
315 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
316 cmCompileExpr cmstate dflags expr
318 let InteractiveContext {
320 ic_type_env = type_env,
321 ic_module = this_mod } = icontext
323 (new_pcs, maybe_stuff)
324 <- hscStmt dflags hst hit pcs icontext
325 ("let __cmCompileExpr = "++expr) False{-stmt-}
328 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
329 Just (ids, _, bcos) -> do
332 hval <- linkExpr pls bcos
335 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
336 hvals <- thing_to_run
339 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
340 _ -> panic "cmCompileExpr"
343 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
346 -----------------------------------------------------------------------------
347 -- cmInfo: return "info" about an expression. The info might be:
349 -- * its type, for an expression,
350 -- * the class definition, for a class
351 -- * the datatype definition, for a tycon (or synonym)
352 -- * the export list, for a module
354 -- Can be used to find the type of the last expression compiled, by looking
357 cmInfo :: CmState -> String -> IO (Maybe String)
359 = do error "cmInfo not implemented yet"
361 -----------------------------------------------------------------------------
362 -- Unload the compilation manager's state: everything it knows about the
363 -- current collection of modules in the Home package.
365 cmUnload :: CmState -> DynFlags -> IO CmState
366 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
367 = do -- Throw away the old home dir cache
370 -- Unload everything the linker knows about
371 new_pls <- CmLink.unload mode dflags [] pls
373 -- Start with a fresh CmState, but keep the PersistentCompilerState
374 new_state <- cmInit mode
375 return new_state{ pcs=pcs, pls=new_pls }
377 -----------------------------------------------------------------------------
378 -- The real business of the compilation manager: given a system state and
379 -- a module name, try and bring the module up to date, probably changing
380 -- the system state at the same time.
382 cmLoadModule :: CmState
384 -> IO (CmState, -- new state
385 Bool, -- was successful
386 [String]) -- list of modules loaded
388 cmLoadModule cmstate1 rootnames
389 = do -- version 1's are the original, before downsweep
390 let pls1 = pls cmstate1
391 let pcs1 = pcs cmstate1
392 let hst1 = hst cmstate1
393 let hit1 = hit cmstate1
394 -- similarly, ui1 is the (complete) set of linkables from
395 -- the previous pass, if any.
396 let ui1 = ui cmstate1
397 let mg1 = mg cmstate1
398 let ic1 = ic cmstate1
400 let ghci_mode = gmode cmstate1 -- this never changes
402 -- Do the downsweep to reestablish the module graph
403 dflags <- getDynFlags
404 let verb = verbosity dflags
406 showPass dflags "Chasing dependencies"
407 when (verb >= 1 && ghci_mode == Batch) $
408 hPutStrLn stderr (showSDoc (hcat [
409 text progName, text ": chasing modules from: ",
410 hcat (punctuate comma (map text rootnames))]))
412 (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
413 let mg2unsorted_names = map name_of_summary mg2unsorted
415 -- reachable_from follows source as well as normal imports
416 let reachable_from :: ModuleName -> [ModuleName]
417 reachable_from = downwards_closure_of_module mg2unsorted
419 -- should be cycle free; ignores 'import source's
420 let mg2 = topological_sort False mg2unsorted
421 -- ... whereas this takes them into account. Used for
422 -- backing out partially complete cycles following a failed
423 -- upsweep, and for removing from hst/hit all the modules
424 -- not in strict downwards closure, during calls to compile.
425 let mg2_with_srcimps = topological_sort True mg2unsorted
427 -- Sort out which linkables we wish to keep in the unlinked image.
428 -- See getValidLinkables below for details.
429 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
431 -- when (verb >= 2) $
432 -- putStrLn (showSDoc (text "Valid linkables:"
433 -- <+> ppr valid_linkables))
435 -- Figure out a stable set of modules which can be retained
436 -- the top level envs, to avoid upsweeping them. Goes to a
437 -- bit of trouble to avoid upsweeping module cycles.
439 -- Construct a set S of stable modules like this:
440 -- Travel upwards, over the sccified graph. For each scc
441 -- of modules ms, add ms to S only if:
442 -- 1. All home imports of ms are either in ms or S
443 -- 2. A valid linkable exists for each module in ms
445 stable_mods <- preUpsweep valid_linkables hit1
446 mg2unsorted_names [] mg2_with_srcimps
449 = concatMap (findInSummaries mg2unsorted) stable_mods
452 = filter (\m -> linkableModName m `elem` stable_mods)
456 putStrLn (showSDoc (text "Stable modules:"
457 <+> sep (map (text.moduleNameUserString) stable_mods)))
459 -- unload any modules which aren't going to be re-linked this
461 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
463 -- We could at this point detect cycles which aren't broken by
464 -- a source-import, and complain immediately, but it seems better
465 -- to let upsweep_mods do this, so at least some useful work gets
466 -- done before the upsweep is abandoned.
468 = filter (\scc -> any (`notElem` stable_mods)
469 (map name_of_summary (flattenSCC scc)))
472 --hPutStrLn stderr "after tsort:\n"
473 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
475 -- Because we don't take into account source imports when doing
476 -- the topological sort, there shouldn't be any cycles in mg2.
477 -- If there is, we complain and give up -- the user needs to
478 -- break the cycle using a boot file.
480 -- Now do the upsweep, calling compile for each module in
481 -- turn. Final result is version 3 of everything.
483 let threaded2 = CmThreaded pcs1 hst1 hit1
485 -- clean up between compilations
486 let cleanup = cleanTempFilesExcept verb
487 (ppFilesFromSummaries (flattenSCCs upsweep_these))
489 (upsweep_complete_success, threaded3, modsUpswept, newLis)
490 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
491 threaded2 cleanup upsweep_these
493 let ui3 = add_to_ui valid_linkables newLis
494 let (CmThreaded pcs3 hst3 hit3) = threaded3
496 -- At this point, modsUpswept and newLis should have the same
497 -- length, so there is one new (or old) linkable for each
498 -- mod which was processed (passed to compile).
500 -- Make modsDone be the summaries for each home module now
501 -- available; this should equal the domains of hst3 and hit3.
502 -- (NOT STRICTLY TRUE if an interactive session was started
503 -- with some object on disk ???)
504 -- Get in in a roughly top .. bottom order (hence reverse).
506 let modsDone = reverse modsUpswept ++ stable_summaries
508 -- Try and do linking in some form, depending on whether the
509 -- upsweep was completely or only partially successful.
511 if upsweep_complete_success
514 -- Easy; just relink it all.
515 do when (verb >= 2) $
516 hPutStrLn stderr "Upsweep completely successful."
518 -- clean up after ourselves
519 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
521 -- link everything together
522 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
524 cmLoadFinish True linkresult
525 hst3 hit3 ui3 modsDone ghci_mode pcs3
528 -- Tricky. We need to back out the effects of compiling any
529 -- half-done cycles, both so as to clean up the top level envs
530 -- and to avoid telling the interactive linker to link them.
531 do when (verb >= 2) $
532 hPutStrLn stderr "Upsweep partially successful."
535 = map name_of_summary modsDone
536 let mods_to_zap_names
537 = findPartiallyCompletedCycles modsDone_names
540 = filter ((`notElem` mods_to_zap_names).name_of_summary)
543 let (hst4, hit4, ui4)
544 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
547 -- clean up after ourselves
548 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
550 -- link everything together
551 linkresult <- link ghci_mode dflags False ui4 pls2
553 cmLoadFinish False linkresult
554 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
557 -- Finish up after a cmLoad.
559 -- If the link failed, unload everything and return.
560 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
561 dflags <- getDynFlags
562 new_pls <- CmLink.unload ghci_mode dflags [] pls
563 new_state <- cmInit ghci_mode
564 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
566 -- Empty the interactive context and set the module context to the topmost
567 -- newly loaded module, or the Prelude if none were loaded.
568 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
569 = do def_mod <- readIORef defaultCurrentModule
570 let current_mod = case mods of
574 new_ic = emptyInteractiveContext current_mod
576 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
577 gmode=ghci_mode, pcs=pcs, pls=pls,
579 mods_loaded = map (moduleNameUserString.name_of_summary) mods
581 return (new_cmstate, ok, mods_loaded)
583 -- used to fish out the preprocess output files for the purposes
585 ppFilesFromSummaries summaries
586 = [ fn | Just fn <- map toPpFile summaries ]
589 | hspp /= ml_hs_file loc = hspp
590 | otherwise = Nothing
592 loc = ms_location sum
593 hspp = ml_hspp_file loc
596 -----------------------------------------------------------------------------
599 -- For each module (or SCC of modules), we take:
601 -- - an on-disk linkable, if this is the first time around and one
604 -- - the old linkable, otherwise (and if one is available).
606 -- and we throw away the linkable if it is older than the source
607 -- file. We ignore the on-disk linkables unless all of the dependents
608 -- of this SCC also have on-disk linkables.
610 -- If a module has a valid linkable, then it may be STABLE (see below),
611 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
614 -- ToDo: this pass could be merged with the preUpsweep.
617 :: [Linkable] -- old linkables
618 -> [ModuleName] -- all home modules
619 -> [SCC ModSummary] -- all modules in the program, dependency order
620 -> IO [Linkable] -- still-valid linkables
622 getValidLinkables old_linkables all_home_mods module_graph
623 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
625 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
627 scc = flattenSCC scc0
628 scc_names = map name_of_summary scc
629 home_module m = m `elem` all_home_mods && m `notElem` scc_names
630 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
631 -- NOTE: ms_imps, not ms_allimps above. We don't want to
632 -- force a module's SOURCE imports to be already compiled for
633 -- its object linkable to be valid.
635 has_object m = case findModuleLinkable_maybe new_linkables m of
637 Just l -> isObjectLinkable l
639 objects_allowed = all has_object scc_allhomeimps
643 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
645 -- since an scc can contain only all objects or no objects at all,
646 -- we have to check whether we got all objects or not, and re-do
647 -- the linkable check if not.
649 <- if objects_allowed && not (all isObjectLinkable these_linkables)
650 then foldM (getValidLinkable old_linkables False) [] scc
651 else return these_linkables
653 return (adjusted_linkables ++ new_linkables)
656 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
658 getValidLinkable old_linkables objects_allowed new_linkables summary
659 = do let mod_name = name_of_summary summary
662 <- if (not objects_allowed)
664 else case ml_obj_file (ms_location summary) of
665 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
666 Nothing -> return Nothing
668 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
671 Just l | not (isObjectLinkable l) || stillThere l
673 -- ToDo: emit a warning if not (stillThere l)
676 -- make sure that if we had an old disk linkable around, that it's
677 -- still there on the disk (in case we need to re-link it).
679 case maybe_disk_linkable of
681 Just l_disk -> linkableTime l == linkableTime l_disk
683 -- we only look for objects on disk the first time around;
684 -- if the user compiles a module on the side during a GHCi session,
685 -- it won't be picked up until the next ":load". This is what the
686 -- "null old_linkables" test below is.
687 linkable | null old_linkables = maybeToList maybe_disk_linkable
688 | otherwise = maybeToList maybe_old_linkable
690 -- only linkables newer than the source code are valid
691 src_date = ms_hs_date summary
694 = filter (\l -> linkableTime l >= src_date) linkable
695 -- why '>=' rather than '>' above? If the filesystem stores
696 -- times to the nearset second, we may occasionally find that
697 -- the object & source have the same modification time,
698 -- especially if the source was automatically generated
699 -- and compiled. Using >= is slightly unsafe, but it matches
702 return (valid_linkable ++ new_linkables)
705 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
706 maybe_getFileLinkable mod_name obj_fn
707 = do obj_exist <- doesFileExist obj_fn
711 do let stub_fn = case splitFilename3 obj_fn of
712 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
713 stub_exist <- doesFileExist stub_fn
714 obj_time <- getModificationTime obj_fn
716 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
717 else return (Just (LM obj_time mod_name [DotO obj_fn]))
720 -----------------------------------------------------------------------------
721 -- Do a pre-upsweep without use of "compile", to establish a
722 -- (downward-closed) set of stable modules for which we won't call compile.
725 -- * has a valid linkable (see getValidLinkables above)
726 -- * depends only on stable modules
727 -- * has an interface in the HIT (interactive mode only)
729 preUpsweep :: [Linkable] -- new valid linkables
731 -> [ModuleName] -- names of all mods encountered in downsweep
732 -> [ModuleName] -- accumulating stable modules
733 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
734 -> IO [ModuleName] -- stable modules
736 preUpsweep valid_lis hit all_home_mods stable [] = return stable
737 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
738 = do let scc = flattenSCC scc0
739 scc_allhomeimps :: [ModuleName]
741 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
742 all_imports_in_scc_or_stable
743 = all in_stable_or_scc scc_allhomeimps
745 = map name_of_summary scc
747 = m `elem` scc_names || m `elem` stable
749 -- now we check for valid linkables: each module in the SCC must
750 -- have a valid linkable (see getValidLinkables above).
751 has_valid_linkable new_summary
752 = isJust (findModuleLinkable_maybe valid_lis modname)
753 where modname = name_of_summary new_summary
755 has_interface summary = ms_mod summary `elemUFM` hit
757 scc_is_stable = all_imports_in_scc_or_stable
758 && all has_valid_linkable scc
759 && all has_interface scc
762 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
763 else preUpsweep valid_lis hit all_home_mods stable sccs
766 -- Helper for preUpsweep. Assuming that new_summary's imports are all
767 -- stable (in the sense of preUpsweep), determine if new_summary is itself
768 -- stable, and, if so, in batch mode, return its linkable.
769 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
770 findInSummaries old_summaries mod_name
771 = [s | s <- old_summaries, name_of_summary s == mod_name]
773 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
774 findModInSummaries old_summaries mod
775 = case [s | s <- old_summaries, ms_mod s == mod] of
779 -- Return (names of) all those in modsDone who are part of a cycle
780 -- as defined by theGraph.
781 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
782 findPartiallyCompletedCycles modsDone theGraph
786 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
787 chew ((CyclicSCC vs):rest)
788 = let names_in_this_cycle = nub (map name_of_summary vs)
790 = nub ([done | done <- modsDone,
791 done `elem` names_in_this_cycle])
792 chewed_rest = chew rest
794 if not (null mods_in_this_cycle)
795 && length mods_in_this_cycle < length names_in_this_cycle
796 then mods_in_this_cycle ++ chewed_rest
800 -- Add the given (LM-form) Linkables to the UI, overwriting previous
801 -- versions if they exist.
802 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
804 = filter (not_in lis) ui ++ lis
806 not_in :: [Linkable] -> Linkable -> Bool
808 = all (\l -> linkableModName l /= mod) lis
809 where mod = linkableModName li
812 data CmThreaded -- stuff threaded through individual module compilations
813 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
816 -- Compile multiple modules, stopping as soon as an error appears.
817 -- There better had not be any cyclic groups here -- we check for them.
818 upsweep_mods :: GhciMode
820 -> UnlinkedImage -- valid linkables
821 -> (ModuleName -> [ModuleName]) -- to construct downward closures
822 -> CmThreaded -- PCS & HST & HIT
823 -> IO () -- how to clean up unwanted tmp files
824 -> [SCC ModSummary] -- mods to do (the worklist)
825 -- ...... RETURNING ......
826 -> IO (Bool{-complete success?-},
828 [ModSummary], -- mods which succeeded
829 [Linkable]) -- new linkables
831 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
833 = return (True, threaded, [], [])
835 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
837 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
838 unwords (map (moduleNameUserString.name_of_summary) ms))
839 return (False, threaded, [], [])
841 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
842 ((AcyclicSCC mod):mods)
843 = do --case threaded of
844 -- CmThreaded pcsz hstz hitz
845 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
847 (threaded1, maybe_linkable)
848 <- upsweep_mod ghci_mode dflags oldUI threaded mod
849 (reachable_from (name_of_summary mod))
851 -- remove unwanted tmp files between compilations
854 case maybe_linkable of
856 -> -- No errors; do the rest
857 do (restOK, threaded2, modOKs, linkables)
858 <- upsweep_mods ghci_mode dflags oldUI reachable_from
859 threaded1 cleanup mods
860 return (restOK, threaded2, mod:modOKs, linkable:linkables)
861 Nothing -- we got a compilation error; give up now
862 -> return (False, threaded1, [], [])
865 -- Compile a single module. Always produce a Linkable for it if
866 -- successful. If no compilation happened, return the old Linkable.
867 upsweep_mod :: GhciMode
873 -> IO (CmThreaded, Maybe Linkable)
875 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
877 let mod_name = name_of_summary summary1
878 let verb = verbosity dflags
880 let (CmThreaded pcs1 hst1 hit1) = threaded1
881 let old_iface = lookupUFM hit1 mod_name
883 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
885 source_unchanged = isJust maybe_old_linkable
887 reachable_only = filter (/= (name_of_summary summary1))
890 -- in interactive mode, all home modules below us *must* have an
891 -- interface in the HIT. We never demand-load home interfaces in
893 (hst1_strictDC, hit1_strictDC, [])
894 = ASSERT(ghci_mode == Batch ||
895 all (`elemUFM` hit1) reachable_only)
896 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
899 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
902 | Just l <- maybe_old_linkable, isObjectLinkable l = True
905 compresult <- compile ghci_mode summary1 source_unchanged
906 have_object old_iface hst1_strictDC hit1_strictDC pcs1
910 -- Compilation "succeeded", and may or may not have returned a new
911 -- linkable (depending on whether compilation was actually performed
913 CompOK pcs2 new_details new_iface maybe_new_linkable
914 -> do let hst2 = addToUFM hst1 mod_name new_details
915 hit2 = addToUFM hit1 mod_name new_iface
916 threaded2 = CmThreaded pcs2 hst2 hit2
918 return (threaded2, if isJust maybe_new_linkable
919 then maybe_new_linkable
920 else Just old_linkable)
922 -- Compilation failed. compile may still have updated
925 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
926 return (threaded2, Nothing)
928 -- Filter modules in the top level envs (HST, HIT, UI).
929 retainInTopLevelEnvs :: [ModuleName]
930 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
931 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
932 retainInTopLevelEnvs keep_these (hst, hit, ui)
933 = (retainInUFM hst keep_these,
934 retainInUFM hit keep_these,
935 filterModuleLinkables (`elem` keep_these) ui
938 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
939 retainInUFM ufm keys_to_keep
940 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
942 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
944 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
945 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
946 downwards_closure_of_module summaries root
947 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
948 toEdge summ = (name_of_summary summ,
949 filter (`elem` all_mods) (ms_allimps summ))
951 all_mods = map name_of_summary summaries
953 res = simple_transitive_closure (map toEdge summaries) [root]
955 -- trace (showSDoc (text "DC of mod" <+> ppr root
956 -- <+> text "=" <+> ppr res)) $
959 -- Calculate transitive closures from a set of roots given an adjacency list
960 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
961 simple_transitive_closure graph set
962 = let set2 = nub (concatMap dsts set ++ set)
963 dsts node = fromMaybe [] (lookup node graph)
965 if length set == length set2
967 else simple_transitive_closure graph set2
970 -- Calculate SCCs of the module graph, with or without taking into
971 -- account source imports.
972 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
973 topological_sort include_source_imports summaries
975 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
977 = (summ, name_of_summary summ,
978 (if include_source_imports
979 then ms_srcimps summ else []) ++ ms_imps summ)
981 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
982 mash_edge (summ, m, m_imports)
983 = case lookup m key_map of
984 Nothing -> panic "reverse_topological_sort"
985 Just mk -> (summ, mk,
986 -- ignore imports not from the home package
987 catMaybes (map (flip lookup key_map) m_imports))
989 edges = map toEdge summaries
990 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
991 scc_input = map mash_edge edges
992 sccs = stronglyConnComp scc_input
997 -- Chase downwards from the specified root set, returning summaries
998 -- for all home modules encountered. Only follow source-import
999 -- links. Also returns a Bool to indicate whether any of the roots
1001 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
1002 downsweep rootNm old_summaries
1003 = do rootSummaries <- mapM getRootSummary rootNm
1005 = any ((=="Main").moduleNameUserString.name_of_summary)
1008 <- loop (concat (map ms_imps rootSummaries))
1009 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1010 let mod = ms_mod s, isHomeModule mod
1012 return (all_summaries, a_root_is_Main)
1014 getRootSummary :: FilePath -> IO ModSummary
1016 | haskellish_src_file file
1017 = do exists <- doesFileExist file
1018 if exists then summariseFile file else do
1019 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1021 = do exists <- doesFileExist hs_file
1022 if exists then summariseFile hs_file else do
1023 exists <- doesFileExist lhs_file
1024 if exists then summariseFile lhs_file else do
1025 let mod_name = mkModuleName file
1026 maybe_summary <- getSummary mod_name
1027 case maybe_summary of
1028 Nothing -> packageModErr mod_name
1031 hs_file = file ++ ".hs"
1032 lhs_file = file ++ ".lhs"
1034 getSummary :: ModuleName -> IO (Maybe ModSummary)
1036 = do found <- findModule nm
1038 Just (mod, location) -> do
1039 let old_summary = findModInSummaries old_summaries mod
1040 summarise mod location old_summary
1042 Nothing -> throwDyn (CmdLineError
1043 ("can't find module `"
1044 ++ showSDoc (ppr nm) ++ "'"))
1046 -- loop invariant: env doesn't contain package modules
1047 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1048 loop [] env = return (moduleEnvElts env)
1050 = do -- imports for modules we don't already have
1051 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1054 needed_summaries <- mapM getSummary needed_imps
1056 -- get just the "home" modules
1057 let new_home_summaries = [ s | Just s <- needed_summaries ]
1059 -- loop, checking the new imports
1060 let new_imps = concat (map ms_imps new_home_summaries)
1061 loop new_imps (extendModuleEnvList env
1062 [ (ms_mod s, s) | s <- new_home_summaries ])
1064 -----------------------------------------------------------------------------
1065 -- Summarising modules
1067 -- We have two types of summarisation:
1069 -- * Summarise a file. This is used for the root module passed to
1070 -- cmLoadModule. The file is read, and used to determine the root
1071 -- module name. The module name may differ from the filename.
1073 -- * Summarise a module. We are given a module name, and must provide
1074 -- a summary. The finder is used to locate the file in which the module
1077 summariseFile :: FilePath -> IO ModSummary
1079 = do hspp_fn <- preprocess file
1080 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1082 let (path, basename, ext) = splitFilename3 file
1085 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1088 <- case ml_hs_file location of
1089 Nothing -> noHsFileErr mod_name
1090 Just src_fn -> getModificationTime src_fn
1092 return (ModSummary mod
1093 location{ml_hspp_file=Just hspp_fn}
1094 srcimps imps src_timestamp)
1096 -- Summarise a module, and pick up source and timestamp.
1097 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1098 -> IO (Maybe ModSummary)
1099 summarise mod location old_summary
1100 | not (isHomeModule mod) = return Nothing
1102 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1104 case ml_hs_file location of {
1105 Nothing -> noHsFileErr mod;
1108 src_timestamp <- getModificationTime src_fn
1110 -- return the cached summary if the source didn't change
1111 case old_summary of {
1112 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1115 hspp_fn <- preprocess hs_fn
1116 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1118 when (mod_name /= moduleName mod) $
1119 throwDyn (ProgramError
1120 (showSDoc (text hs_fn
1121 <> text ": file name does not match module name"
1122 <+> quotes (ppr (moduleName mod)))))
1124 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1125 srcimps imps src_timestamp))
1131 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1134 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1135 quotes (ppr mod) <+>
1136 text "is a package module")))