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 )
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 (upsweep_complete_success, threaded3, modsUpswept, newLis)
486 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
487 threaded2 upsweep_these
489 let ui3 = add_to_ui valid_linkables newLis
490 let (CmThreaded pcs3 hst3 hit3) = threaded3
492 -- At this point, modsUpswept and newLis should have the same
493 -- length, so there is one new (or old) linkable for each
494 -- mod which was processed (passed to compile).
496 -- Make modsDone be the summaries for each home module now
497 -- available; this should equal the domains of hst3 and hit3.
498 -- (NOT STRICTLY TRUE if an interactive session was started
499 -- with some object on disk ???)
500 -- Get in in a roughly top .. bottom order (hence reverse).
502 let modsDone = reverse modsUpswept ++ stable_summaries
504 -- Try and do linking in some form, depending on whether the
505 -- upsweep was completely or only partially successful.
507 if upsweep_complete_success
510 -- Easy; just relink it all.
511 do when (verb >= 2) $
512 hPutStrLn stderr "Upsweep completely successful."
514 -- clean up after ourselves
515 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
517 -- link everything together
518 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
520 cmLoadFinish True linkresult
521 hst3 hit3 ui3 modsDone ghci_mode pcs3
524 -- Tricky. We need to back out the effects of compiling any
525 -- half-done cycles, both so as to clean up the top level envs
526 -- and to avoid telling the interactive linker to link them.
527 do when (verb >= 2) $
528 hPutStrLn stderr "Upsweep partially successful."
531 = map name_of_summary modsDone
532 let mods_to_zap_names
533 = findPartiallyCompletedCycles modsDone_names
536 = filter ((`notElem` mods_to_zap_names).name_of_summary)
539 let (hst4, hit4, ui4)
540 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
543 -- clean up after ourselves
544 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
546 -- link everything together
547 linkresult <- link ghci_mode dflags False ui4 pls2
549 cmLoadFinish False linkresult
550 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
553 -- Finish up after a cmLoad.
555 -- If the link failed, unload everything and return.
556 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
557 dflags <- getDynFlags
558 new_pls <- CmLink.unload ghci_mode dflags [] pls
559 new_state <- cmInit ghci_mode
560 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
562 -- Empty the interactive context and set the module context to the topmost
563 -- newly loaded module, or the Prelude if none were loaded.
564 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
565 = do def_mod <- readIORef defaultCurrentModule
566 let current_mod = case mods of
570 new_ic = emptyInteractiveContext current_mod
572 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
573 gmode=ghci_mode, pcs=pcs, pls=pls,
575 mods_loaded = map (moduleNameUserString.name_of_summary) mods
577 return (new_cmstate, ok, mods_loaded)
579 -- used to fish out the preprocess output files for the purposes
581 ppFilesFromSummaries summaries
582 = [ fn | Just fn <- map toPpFile summaries ]
585 | hspp /= ml_hs_file loc = hspp
586 | otherwise = Nothing
588 loc = ms_location sum
589 hspp = ml_hspp_file loc
592 -----------------------------------------------------------------------------
595 -- For each module (or SCC of modules), we take:
597 -- - an on-disk linkable, if this is the first time around and one
600 -- - the old linkable, otherwise (and if one is available).
602 -- and we throw away the linkable if it is older than the source
603 -- file. We ignore the on-disk linkables unless all of the dependents
604 -- of this SCC also have on-disk linkables.
606 -- If a module has a valid linkable, then it may be STABLE (see below),
607 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
610 -- ToDo: this pass could be merged with the preUpsweep.
613 :: [Linkable] -- old linkables
614 -> [ModuleName] -- all home modules
615 -> [SCC ModSummary] -- all modules in the program, dependency order
616 -> IO [Linkable] -- still-valid linkables
618 getValidLinkables old_linkables all_home_mods module_graph
619 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
621 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
623 scc = flattenSCC scc0
624 scc_names = map name_of_summary scc
625 home_module m = m `elem` all_home_mods && m `notElem` scc_names
626 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
627 -- NOTE: ms_imps, not ms_allimps above. We don't want to
628 -- force a module's SOURCE imports to be already compiled for
629 -- its object linkable to be valid.
631 has_object m = case findModuleLinkable_maybe new_linkables m of
633 Just l -> isObjectLinkable l
635 objects_allowed = all has_object scc_allhomeimps
639 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
641 -- since an scc can contain only all objects or no objects at all,
642 -- we have to check whether we got all objects or not, and re-do
643 -- the linkable check if not.
645 <- if objects_allowed && not (all isObjectLinkable these_linkables)
646 then foldM (getValidLinkable old_linkables False) [] scc
647 else return these_linkables
649 return (adjusted_linkables ++ new_linkables)
652 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
654 getValidLinkable old_linkables objects_allowed new_linkables summary
655 = do let mod_name = name_of_summary summary
658 <- if (not objects_allowed)
660 else case ml_obj_file (ms_location summary) of
661 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
662 Nothing -> return Nothing
664 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
667 Just l | not (isObjectLinkable l) || stillThere l
669 -- ToDo: emit a warning if not (stillThere l)
672 -- make sure that if we had an old disk linkable around, that it's
673 -- still there on the disk (in case we need to re-link it).
675 case maybe_disk_linkable of
677 Just l_disk -> linkableTime l == linkableTime l_disk
679 -- we only look for objects on disk the first time around;
680 -- if the user compiles a module on the side during a GHCi session,
681 -- it won't be picked up until the next ":load". This is what the
682 -- "null old_linkables" test below is.
683 linkable | null old_linkables = maybeToList maybe_disk_linkable
684 | otherwise = maybeToList maybe_old_linkable
686 -- only linkables newer than the source code are valid
687 src_date = ms_hs_date summary
690 = filter (\l -> linkableTime l >= src_date) linkable
691 -- why '>=' rather than '>' above? If the filesystem stores
692 -- times to the nearset second, we may occasionally find that
693 -- the object & source have the same modification time,
694 -- especially if the source was automatically generated
695 -- and compiled. Using >= is slightly unsafe, but it matches
698 return (valid_linkable ++ new_linkables)
701 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
702 maybe_getFileLinkable mod_name obj_fn
703 = do obj_exist <- doesFileExist obj_fn
707 do let stub_fn = case splitFilename3 obj_fn of
708 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
709 stub_exist <- doesFileExist stub_fn
710 obj_time <- getModificationTime obj_fn
712 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
713 else return (Just (LM obj_time mod_name [DotO obj_fn]))
716 -----------------------------------------------------------------------------
717 -- Do a pre-upsweep without use of "compile", to establish a
718 -- (downward-closed) set of stable modules for which we won't call compile.
721 -- * has a valid linkable (see getValidLinkables above)
722 -- * depends only on stable modules
723 -- * has an interface in the HIT (interactive mode only)
725 preUpsweep :: [Linkable] -- new valid linkables
727 -> [ModuleName] -- names of all mods encountered in downsweep
728 -> [ModuleName] -- accumulating stable modules
729 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
730 -> IO [ModuleName] -- stable modules
732 preUpsweep valid_lis hit all_home_mods stable [] = return stable
733 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
734 = do let scc = flattenSCC scc0
735 scc_allhomeimps :: [ModuleName]
737 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
738 all_imports_in_scc_or_stable
739 = all in_stable_or_scc scc_allhomeimps
741 = map name_of_summary scc
743 = m `elem` scc_names || m `elem` stable
745 -- now we check for valid linkables: each module in the SCC must
746 -- have a valid linkable (see getValidLinkables above).
747 has_valid_linkable new_summary
748 = isJust (findModuleLinkable_maybe valid_lis modname)
749 where modname = name_of_summary new_summary
751 has_interface summary = ms_mod summary `elemUFM` hit
753 scc_is_stable = all_imports_in_scc_or_stable
754 && all has_valid_linkable scc
755 && all has_interface scc
758 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
759 else preUpsweep valid_lis hit all_home_mods stable sccs
762 -- Helper for preUpsweep. Assuming that new_summary's imports are all
763 -- stable (in the sense of preUpsweep), determine if new_summary is itself
764 -- stable, and, if so, in batch mode, return its linkable.
765 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
766 findInSummaries old_summaries mod_name
767 = [s | s <- old_summaries, name_of_summary s == mod_name]
769 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
770 findModInSummaries old_summaries mod
771 = case [s | s <- old_summaries, ms_mod s == mod] of
775 -- Return (names of) all those in modsDone who are part of a cycle
776 -- as defined by theGraph.
777 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
778 findPartiallyCompletedCycles modsDone theGraph
782 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
783 chew ((CyclicSCC vs):rest)
784 = let names_in_this_cycle = nub (map name_of_summary vs)
786 = nub ([done | done <- modsDone,
787 done `elem` names_in_this_cycle])
788 chewed_rest = chew rest
790 if not (null mods_in_this_cycle)
791 && length mods_in_this_cycle < length names_in_this_cycle
792 then mods_in_this_cycle ++ chewed_rest
796 -- Add the given (LM-form) Linkables to the UI, overwriting previous
797 -- versions if they exist.
798 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
800 = filter (not_in lis) ui ++ lis
802 not_in :: [Linkable] -> Linkable -> Bool
804 = all (\l -> linkableModName l /= mod) lis
805 where mod = linkableModName li
808 data CmThreaded -- stuff threaded through individual module compilations
809 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
812 -- Compile multiple modules, stopping as soon as an error appears.
813 -- There better had not be any cyclic groups here -- we check for them.
814 upsweep_mods :: GhciMode
816 -> UnlinkedImage -- valid linkables
817 -> (ModuleName -> [ModuleName]) -- to construct downward closures
818 -> CmThreaded -- PCS & HST & HIT
819 -> [SCC ModSummary] -- mods to do (the worklist)
820 -- ...... RETURNING ......
821 -> IO (Bool{-complete success?-},
823 [ModSummary], -- mods which succeeded
824 [Linkable]) -- new linkables
826 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
828 = return (True, threaded, [], [])
830 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
832 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
833 unwords (map (moduleNameUserString.name_of_summary) ms))
834 return (False, threaded, [], [])
836 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
837 ((AcyclicSCC mod):mods)
838 = do --case threaded of
839 -- CmThreaded pcsz hstz hitz
840 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
842 (threaded1, maybe_linkable)
843 <- upsweep_mod ghci_mode dflags oldUI threaded mod
844 (reachable_from (name_of_summary mod))
845 case maybe_linkable of
847 -> -- No errors; do the rest
848 do (restOK, threaded2, modOKs, linkables)
849 <- upsweep_mods ghci_mode dflags oldUI reachable_from
851 return (restOK, threaded2, mod:modOKs, linkable:linkables)
852 Nothing -- we got a compilation error; give up now
853 -> return (False, threaded1, [], [])
856 -- Compile a single module. Always produce a Linkable for it if
857 -- successful. If no compilation happened, return the old Linkable.
858 upsweep_mod :: GhciMode
864 -> IO (CmThreaded, Maybe Linkable)
866 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
868 let mod_name = name_of_summary summary1
869 let verb = verbosity dflags
871 let (CmThreaded pcs1 hst1 hit1) = threaded1
872 let old_iface = lookupUFM hit1 mod_name
874 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
876 source_unchanged = isJust maybe_old_linkable
878 reachable_only = filter (/= (name_of_summary summary1))
881 -- in interactive mode, all home modules below us *must* have an
882 -- interface in the HIT. We never demand-load home interfaces in
884 (hst1_strictDC, hit1_strictDC, [])
885 = ASSERT(ghci_mode == Batch ||
886 all (`elemUFM` hit1) reachable_only)
887 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
890 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
893 | Just l <- maybe_old_linkable, isObjectLinkable l = True
896 compresult <- compile ghci_mode summary1 source_unchanged
897 have_object old_iface hst1_strictDC hit1_strictDC pcs1
901 -- Compilation "succeeded", and may or may not have returned a new
902 -- linkable (depending on whether compilation was actually performed
904 CompOK pcs2 new_details new_iface maybe_new_linkable
905 -> do let hst2 = addToUFM hst1 mod_name new_details
906 hit2 = addToUFM hit1 mod_name new_iface
907 threaded2 = CmThreaded pcs2 hst2 hit2
909 return (threaded2, if isJust maybe_new_linkable
910 then maybe_new_linkable
911 else Just old_linkable)
913 -- Compilation failed. compile may still have updated
916 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
917 return (threaded2, Nothing)
919 -- Filter modules in the top level envs (HST, HIT, UI).
920 retainInTopLevelEnvs :: [ModuleName]
921 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
922 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
923 retainInTopLevelEnvs keep_these (hst, hit, ui)
924 = (retainInUFM hst keep_these,
925 retainInUFM hit keep_these,
926 filterModuleLinkables (`elem` keep_these) ui
929 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
930 retainInUFM ufm keys_to_keep
931 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
933 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
935 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
936 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
937 downwards_closure_of_module summaries root
938 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
939 toEdge summ = (name_of_summary summ,
940 filter (`elem` all_mods) (ms_allimps summ))
942 all_mods = map name_of_summary summaries
944 res = simple_transitive_closure (map toEdge summaries) [root]
946 -- trace (showSDoc (text "DC of mod" <+> ppr root
947 -- <+> text "=" <+> ppr res)) $
950 -- Calculate transitive closures from a set of roots given an adjacency list
951 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
952 simple_transitive_closure graph set
953 = let set2 = nub (concatMap dsts set ++ set)
954 dsts node = fromMaybe [] (lookup node graph)
956 if length set == length set2
958 else simple_transitive_closure graph set2
961 -- Calculate SCCs of the module graph, with or without taking into
962 -- account source imports.
963 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
964 topological_sort include_source_imports summaries
966 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
968 = (summ, name_of_summary summ,
969 (if include_source_imports
970 then ms_srcimps summ else []) ++ ms_imps summ)
972 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
973 mash_edge (summ, m, m_imports)
974 = case lookup m key_map of
975 Nothing -> panic "reverse_topological_sort"
976 Just mk -> (summ, mk,
977 -- ignore imports not from the home package
978 catMaybes (map (flip lookup key_map) m_imports))
980 edges = map toEdge summaries
981 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
982 scc_input = map mash_edge edges
983 sccs = stronglyConnComp scc_input
988 -- Chase downwards from the specified root set, returning summaries
989 -- for all home modules encountered. Only follow source-import
990 -- links. Also returns a Bool to indicate whether any of the roots
992 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
993 downsweep rootNm old_summaries
994 = do rootSummaries <- mapM getRootSummary rootNm
996 = any ((=="Main").moduleNameUserString.name_of_summary)
999 <- loop (concat (map ms_imps rootSummaries))
1000 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1001 let mod = ms_mod s, isHomeModule mod
1003 return (all_summaries, a_root_is_Main)
1005 getRootSummary :: FilePath -> IO ModSummary
1007 | haskellish_src_file file
1008 = do exists <- doesFileExist file
1009 if exists then summariseFile file else do
1010 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1012 = do exists <- doesFileExist hs_file
1013 if exists then summariseFile hs_file else do
1014 exists <- doesFileExist lhs_file
1015 if exists then summariseFile lhs_file else do
1016 let mod_name = mkModuleName file
1017 maybe_summary <- getSummary mod_name
1018 case maybe_summary of
1019 Nothing -> packageModErr mod_name
1022 hs_file = file ++ ".hs"
1023 lhs_file = file ++ ".lhs"
1025 getSummary :: ModuleName -> IO (Maybe ModSummary)
1027 = do found <- findModule nm
1029 Just (mod, location) -> do
1030 let old_summary = findModInSummaries old_summaries mod
1031 summarise mod location old_summary
1033 Nothing -> throwDyn (CmdLineError
1034 ("can't find module `"
1035 ++ showSDoc (ppr nm) ++ "'"))
1037 -- loop invariant: env doesn't contain package modules
1038 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1039 loop [] env = return (moduleEnvElts env)
1041 = do -- imports for modules we don't already have
1042 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1045 needed_summaries <- mapM getSummary needed_imps
1047 -- get just the "home" modules
1048 let new_home_summaries = [ s | Just s <- needed_summaries ]
1050 -- loop, checking the new imports
1051 let new_imps = concat (map ms_imps new_home_summaries)
1052 loop new_imps (extendModuleEnvList env
1053 [ (ms_mod s, s) | s <- new_home_summaries ])
1055 -----------------------------------------------------------------------------
1056 -- Summarising modules
1058 -- We have two types of summarisation:
1060 -- * Summarise a file. This is used for the root module passed to
1061 -- cmLoadModule. The file is read, and used to determine the root
1062 -- module name. The module name may differ from the filename.
1064 -- * Summarise a module. We are given a module name, and must provide
1065 -- a summary. The finder is used to locate the file in which the module
1068 summariseFile :: FilePath -> IO ModSummary
1070 = do hspp_fn <- preprocess file
1071 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1073 let (path, basename, ext) = splitFilename3 file
1076 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1079 <- case ml_hs_file location of
1080 Nothing -> noHsFileErr mod_name
1081 Just src_fn -> getModificationTime src_fn
1083 return (ModSummary mod
1084 location{ml_hspp_file=Just hspp_fn}
1085 srcimps imps src_timestamp)
1087 -- Summarise a module, and pick up source and timestamp.
1088 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1089 -> IO (Maybe ModSummary)
1090 summarise mod location old_summary
1091 | not (isHomeModule mod) = return Nothing
1093 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1095 case ml_hs_file location of {
1096 Nothing -> noHsFileErr mod;
1099 src_timestamp <- getModificationTime src_fn
1101 -- return the cached summary if the source didn't change
1102 case old_summary of {
1103 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1106 hspp_fn <- preprocess hs_fn
1107 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1109 when (mod_name /= moduleName mod) $
1110 throwDyn (ProgramError
1111 (showSDoc (text hs_fn
1112 <> text ": file name does not match module name"
1113 <+> quotes (ppr (moduleName mod)))))
1115 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1116 srcimps imps src_timestamp))
1122 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1125 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1126 quotes (ppr mod) <+>
1127 text "is a package module")))