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 )
54 import RdrName ( lookupRdrEnv, emptyRdrEnv )
57 import Type ( tidyType )
58 import VarEnv ( emptyTidyEnv )
60 import Unique ( Uniquable )
61 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
62 import ErrUtils ( showPass )
63 import SysTools ( cleanTempFilesExcept )
67 import CmdLineOpts ( DynFlags(..) )
71 import Interpreter ( HValue )
72 import HscMain ( hscStmt )
73 import PrelGHC ( unsafeCoerce# )
77 import Exception ( throwDyn )
80 import Directory ( getModificationTime, doesFileExist )
89 -- Persistent state for the entire system
92 hst :: HomeSymbolTable, -- home symbol table
93 hit :: HomeIfaceTable, -- home interface table
94 ui :: UnlinkedImage, -- the unlinked images
95 mg :: ModuleGraph, -- the module graph
96 gmode :: GhciMode, -- NEVER CHANGES
97 ic :: InteractiveContext, -- command-line binding info
99 pcs :: PersistentCompilerState, -- compile's persistent state
100 pls :: PersistentLinkerState -- link's persistent state
103 emptyCmState :: GhciMode -> Module -> IO CmState
104 emptyCmState gmode mod
105 = do pcs <- initPersistentCompilerState
107 return (CmState { hst = emptySymbolTable,
108 hit = emptyIfaceTable,
112 ic = emptyInteractiveContext mod,
116 emptyInteractiveContext mod
117 = InteractiveContext { ic_module = mod,
118 ic_rn_env = emptyRdrEnv,
119 ic_type_env = emptyTypeEnv }
121 defaultCurrentModuleName = mkModuleName "Prelude"
122 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
125 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
126 emptyUI :: UnlinkedImage
129 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
130 emptyMG :: ModuleGraph
133 -----------------------------------------------------------------------------
134 -- Produce an initial CmState.
136 cmInit :: GhciMode -> IO CmState
138 prel <- moduleNameToModule defaultCurrentModuleName
139 writeIORef defaultCurrentModule prel
140 emptyCmState mode prel
142 -----------------------------------------------------------------------------
143 -- Setting the context doesn't throw away any bindings; the bindings
144 -- we've built up in the InteractiveContext simply move to the new
145 -- module. They always shadow anything in scope in the current context.
147 cmSetContext :: CmState -> String -> IO CmState
148 cmSetContext cmstate str
149 = do let mn = mkModuleName str
150 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
152 m <- case lookup mn modules_loaded of
155 mod <- moduleNameToModule mn
157 then throwDyn (CmdLineError (showSDoc
158 (quotes (ppr (moduleName mod))
159 <+> text "is not currently loaded")))
162 return cmstate{ ic = (ic cmstate){ic_module=m} }
164 cmGetContext :: CmState -> IO String
165 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
167 moduleNameToModule :: ModuleName -> IO Module
168 moduleNameToModule mn
169 = do maybe_stuff <- findModule mn
171 Nothing -> throwDyn (CmdLineError ("can't find module `"
172 ++ moduleNameUserString mn ++ "'"))
173 Just (m,_) -> return m
175 -----------------------------------------------------------------------------
176 -- cmRunStmt: Run a statement/expr.
179 cmInfoThing :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
180 cmInfoThing CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } dflags id
181 = do (pcs, thing) <- hscThing dflags hst hit pcs icontext id
184 cmRunStmt :: CmState -> DynFlags -> String
185 -> IO (CmState, -- new state
186 [Name]) -- names bound by this evaluation
187 cmRunStmt cmstate dflags expr
189 let InteractiveContext {
191 ic_type_env = type_env,
192 ic_module = this_mod } = icontext
194 (new_pcs, maybe_stuff)
195 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
198 Nothing -> return (cmstate{ pcs=new_pcs }, [])
199 Just (ids, _, bcos) -> do
201 -- update the interactive context
203 names = map idName ids
205 -- these names have just been shadowed
206 shadowed = [ n | r <- map nameRdrName names,
207 Just n <- [lookupRdrEnv rn_env r] ]
209 new_rn_env = extendLocalRdrEnv rn_env names
211 -- remove any shadowed bindings from the type_env
212 filtered_type_env = delListFromNameEnv type_env shadowed
214 new_type_env = extendNameEnvList filtered_type_env
215 [ (getName id, AnId id) | id <- ids]
217 new_ic = icontext { ic_rn_env = new_rn_env,
218 ic_type_env = new_type_env }
221 hval <- linkExpr pls bcos
224 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
225 hvals <- thing_to_run
227 -- Get the newly bound things, and bind them. Don't forget
228 -- to delete any shadowed bindings from the closure_env, lest
229 -- we end up with a space leak.
230 pls <- delListFromClosureEnv pls shadowed
231 new_pls <- addListToClosureEnv pls (zip names hvals)
233 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
235 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
238 -----------------------------------------------------------------------------
239 -- cmTypeOfExpr: returns a string representing the type of an expression
242 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
243 cmTypeOfExpr cmstate dflags expr
244 = do (new_pcs, maybe_stuff)
245 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
247 let new_cmstate = cmstate{pcs = new_pcs}
250 Nothing -> return (new_cmstate, Nothing)
252 let pit = pcs_PIT pcs
253 modname = moduleName (ic_module ic)
254 tidy_ty = tidyType emptyTidyEnv ty
255 str = case lookupIfaceByModName hit pit modname of
256 Nothing -> showSDoc (ppr tidy_ty)
257 Just iface -> showSDocForUser unqual (ppr tidy_ty)
258 where unqual = unQualInScope (mi_globals iface)
259 in return (new_cmstate, Just str)
261 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
264 -----------------------------------------------------------------------------
265 -- cmTypeOfName: returns a string representing the type of a name.
268 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
269 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
270 = case lookupNameEnv (ic_type_env ic) name of
271 Nothing -> return Nothing
273 let pit = pcs_PIT pcs
274 modname = moduleName (ic_module ic)
275 ty = tidyType emptyTidyEnv (idType id)
276 str = case lookupIfaceByModName hit pit modname of
277 Nothing -> showSDoc (ppr ty)
278 Just iface -> showSDocForUser unqual (ppr ty)
279 where unqual = unQualInScope (mi_globals iface)
282 _ -> panic "cmTypeOfName"
285 -----------------------------------------------------------------------------
286 -- cmCompileExpr: compile an expression and deliver an HValue
289 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
290 cmCompileExpr cmstate dflags expr
292 let InteractiveContext {
294 ic_type_env = type_env,
295 ic_module = this_mod } = icontext
297 (new_pcs, maybe_stuff)
298 <- hscStmt dflags hst hit pcs icontext
299 ("let __cmCompileExpr = "++expr) False{-stmt-}
302 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
303 Just (ids, _, bcos) -> do
306 hval <- linkExpr pls bcos
309 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
310 hvals <- thing_to_run
313 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
314 _ -> panic "cmCompileExpr"
317 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
320 -----------------------------------------------------------------------------
321 -- cmInfo: return "info" about an expression. The info might be:
323 -- * its type, for an expression,
324 -- * the class definition, for a class
325 -- * the datatype definition, for a tycon (or synonym)
326 -- * the export list, for a module
328 -- Can be used to find the type of the last expression compiled, by looking
331 cmInfo :: CmState -> String -> IO (Maybe String)
333 = do error "cmInfo not implemented yet"
335 -----------------------------------------------------------------------------
336 -- Unload the compilation manager's state: everything it knows about the
337 -- current collection of modules in the Home package.
339 cmUnload :: CmState -> DynFlags -> IO CmState
340 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
341 = do -- Throw away the old home dir cache
344 -- Unload everything the linker knows about
345 new_pls <- CmLink.unload mode dflags [] pls
347 -- Start with a fresh CmState, but keep the PersistentCompilerState
348 new_state <- cmInit mode
349 return new_state{ pcs=pcs, pls=new_pls }
351 -----------------------------------------------------------------------------
352 -- The real business of the compilation manager: given a system state and
353 -- a module name, try and bring the module up to date, probably changing
354 -- the system state at the same time.
356 cmLoadModule :: CmState
358 -> IO (CmState, -- new state
359 Bool, -- was successful
360 [String]) -- list of modules loaded
362 cmLoadModule cmstate1 rootnames
363 = do -- version 1's are the original, before downsweep
364 let pls1 = pls cmstate1
365 let pcs1 = pcs cmstate1
366 let hst1 = hst cmstate1
367 let hit1 = hit cmstate1
368 -- similarly, ui1 is the (complete) set of linkables from
369 -- the previous pass, if any.
370 let ui1 = ui cmstate1
371 let mg1 = mg cmstate1
372 let ic1 = ic cmstate1
374 let ghci_mode = gmode cmstate1 -- this never changes
376 -- Do the downsweep to reestablish the module graph
377 dflags <- getDynFlags
378 let verb = verbosity dflags
380 showPass dflags "Chasing dependencies"
381 when (verb >= 1 && ghci_mode == Batch) $
382 hPutStrLn stderr (showSDoc (hcat [
383 text progName, text ": chasing modules from: ",
384 hcat (punctuate comma (map text rootnames))]))
386 (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
387 let mg2unsorted_names = map name_of_summary mg2unsorted
389 -- reachable_from follows source as well as normal imports
390 let reachable_from :: ModuleName -> [ModuleName]
391 reachable_from = downwards_closure_of_module mg2unsorted
393 -- should be cycle free; ignores 'import source's
394 let mg2 = topological_sort False mg2unsorted
395 -- ... whereas this takes them into account. Used for
396 -- backing out partially complete cycles following a failed
397 -- upsweep, and for removing from hst/hit all the modules
398 -- not in strict downwards closure, during calls to compile.
399 let mg2_with_srcimps = topological_sort True mg2unsorted
401 -- Sort out which linkables we wish to keep in the unlinked image.
402 -- See getValidLinkables below for details.
403 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
405 -- when (verb >= 2) $
406 -- putStrLn (showSDoc (text "Valid linkables:"
407 -- <+> ppr valid_linkables))
409 -- Figure out a stable set of modules which can be retained
410 -- the top level envs, to avoid upsweeping them. Goes to a
411 -- bit of trouble to avoid upsweeping module cycles.
413 -- Construct a set S of stable modules like this:
414 -- Travel upwards, over the sccified graph. For each scc
415 -- of modules ms, add ms to S only if:
416 -- 1. All home imports of ms are either in ms or S
417 -- 2. A valid linkable exists for each module in ms
419 stable_mods <- preUpsweep valid_linkables hit1
420 mg2unsorted_names [] mg2_with_srcimps
423 = concatMap (findInSummaries mg2unsorted) stable_mods
426 = filter (\m -> linkableModName m `elem` stable_mods)
430 putStrLn (showSDoc (text "Stable modules:"
431 <+> sep (map (text.moduleNameUserString) stable_mods)))
433 -- unload any modules which aren't going to be re-linked this
435 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
437 -- We could at this point detect cycles which aren't broken by
438 -- a source-import, and complain immediately, but it seems better
439 -- to let upsweep_mods do this, so at least some useful work gets
440 -- done before the upsweep is abandoned.
442 = filter (\scc -> any (`notElem` stable_mods)
443 (map name_of_summary (flattenSCC scc)))
446 --hPutStrLn stderr "after tsort:\n"
447 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
449 -- Because we don't take into account source imports when doing
450 -- the topological sort, there shouldn't be any cycles in mg2.
451 -- If there is, we complain and give up -- the user needs to
452 -- break the cycle using a boot file.
454 -- Now do the upsweep, calling compile for each module in
455 -- turn. Final result is version 3 of everything.
457 let threaded2 = CmThreaded pcs1 hst1 hit1
459 (upsweep_complete_success, threaded3, modsUpswept, newLis)
460 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
461 threaded2 upsweep_these
463 let ui3 = add_to_ui valid_linkables newLis
464 let (CmThreaded pcs3 hst3 hit3) = threaded3
466 -- At this point, modsUpswept and newLis should have the same
467 -- length, so there is one new (or old) linkable for each
468 -- mod which was processed (passed to compile).
470 -- Make modsDone be the summaries for each home module now
471 -- available; this should equal the domains of hst3 and hit3.
472 -- (NOT STRICTLY TRUE if an interactive session was started
473 -- with some object on disk ???)
474 -- Get in in a roughly top .. bottom order (hence reverse).
476 let modsDone = reverse modsUpswept ++ stable_summaries
478 -- Try and do linking in some form, depending on whether the
479 -- upsweep was completely or only partially successful.
481 if upsweep_complete_success
484 -- Easy; just relink it all.
485 do when (verb >= 2) $
486 hPutStrLn stderr "Upsweep completely successful."
488 -- clean up after ourselves
489 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
491 -- link everything together
492 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
494 cmLoadFinish True linkresult
495 hst3 hit3 ui3 modsDone ghci_mode pcs3
498 -- Tricky. We need to back out the effects of compiling any
499 -- half-done cycles, both so as to clean up the top level envs
500 -- and to avoid telling the interactive linker to link them.
501 do when (verb >= 2) $
502 hPutStrLn stderr "Upsweep partially successful."
505 = map name_of_summary modsDone
506 let mods_to_zap_names
507 = findPartiallyCompletedCycles modsDone_names
510 = filter ((`notElem` mods_to_zap_names).name_of_summary)
513 let (hst4, hit4, ui4)
514 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
517 -- clean up after ourselves
518 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
520 -- link everything together
521 linkresult <- link ghci_mode dflags False ui4 pls2
523 cmLoadFinish False linkresult
524 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
527 -- Finish up after a cmLoad.
529 -- If the link failed, unload everything and return.
530 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
531 dflags <- getDynFlags
532 new_pls <- CmLink.unload ghci_mode dflags [] pls
533 new_state <- cmInit ghci_mode
534 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
536 -- Empty the interactive context and set the module context to the topmost
537 -- newly loaded module, or the Prelude if none were loaded.
538 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
539 = do def_mod <- readIORef defaultCurrentModule
540 let current_mod = case mods of
544 new_ic = emptyInteractiveContext current_mod
546 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
547 gmode=ghci_mode, pcs=pcs, pls=pls,
549 mods_loaded = map (moduleNameUserString.name_of_summary) mods
551 return (new_cmstate, ok, mods_loaded)
553 -- used to fish out the preprocess output files for the purposes
555 ppFilesFromSummaries summaries
556 = [ fn | Just fn <- map toPpFile summaries ]
559 | hspp /= ml_hs_file loc = hspp
560 | otherwise = Nothing
562 loc = ms_location sum
563 hspp = ml_hspp_file loc
566 -----------------------------------------------------------------------------
569 -- For each module (or SCC of modules), we take:
571 -- - an on-disk linkable, if this is the first time around and one
574 -- - the old linkable, otherwise (and if one is available).
576 -- and we throw away the linkable if it is older than the source
577 -- file. We ignore the on-disk linkables unless all of the dependents
578 -- of this SCC also have on-disk linkables.
580 -- If a module has a valid linkable, then it may be STABLE (see below),
581 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
584 -- ToDo: this pass could be merged with the preUpsweep.
587 :: [Linkable] -- old linkables
588 -> [ModuleName] -- all home modules
589 -> [SCC ModSummary] -- all modules in the program, dependency order
590 -> IO [Linkable] -- still-valid linkables
592 getValidLinkables old_linkables all_home_mods module_graph
593 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
595 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
597 scc = flattenSCC scc0
598 scc_names = map name_of_summary scc
599 home_module m = m `elem` all_home_mods && m `notElem` scc_names
600 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
601 -- NOTE: ms_imps, not ms_allimps above. We don't want to
602 -- force a module's SOURCE imports to be already compiled for
603 -- its object linkable to be valid.
605 has_object m = case findModuleLinkable_maybe new_linkables m of
607 Just l -> isObjectLinkable l
609 objects_allowed = all has_object scc_allhomeimps
613 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
615 -- since an scc can contain only all objects or no objects at all,
616 -- we have to check whether we got all objects or not, and re-do
617 -- the linkable check if not.
619 <- if objects_allowed && not (all isObjectLinkable these_linkables)
620 then foldM (getValidLinkable old_linkables False) [] scc
621 else return these_linkables
623 return (adjusted_linkables ++ new_linkables)
626 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
628 getValidLinkable old_linkables objects_allowed new_linkables summary
629 = do let mod_name = name_of_summary summary
632 <- if (not objects_allowed)
634 else case ml_obj_file (ms_location summary) of
635 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
636 Nothing -> return Nothing
638 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
641 Just l | not (isObjectLinkable l) || stillThere l
643 -- ToDo: emit a warning if not (stillThere l)
646 -- make sure that if we had an old disk linkable around, that it's
647 -- still there on the disk (in case we need to re-link it).
649 case maybe_disk_linkable of
651 Just l_disk -> linkableTime l == linkableTime l_disk
653 -- we only look for objects on disk the first time around;
654 -- if the user compiles a module on the side during a GHCi session,
655 -- it won't be picked up until the next ":load". This is what the
656 -- "null old_linkables" test below is.
657 linkable | null old_linkables = maybeToList maybe_disk_linkable
658 | otherwise = maybeToList maybe_old_linkable
660 -- only linkables newer than the source code are valid
661 src_date = ms_hs_date summary
664 = filter (\l -> linkableTime l >= src_date) linkable
665 -- why '>=' rather than '>' above? If the filesystem stores
666 -- times to the nearset second, we may occasionally find that
667 -- the object & source have the same modification time,
668 -- especially if the source was automatically generated
669 -- and compiled. Using >= is slightly unsafe, but it matches
672 return (valid_linkable ++ new_linkables)
675 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
676 maybe_getFileLinkable mod_name obj_fn
677 = do obj_exist <- doesFileExist obj_fn
681 do let stub_fn = case splitFilename3 obj_fn of
682 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
683 stub_exist <- doesFileExist stub_fn
684 obj_time <- getModificationTime obj_fn
686 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
687 else return (Just (LM obj_time mod_name [DotO obj_fn]))
690 -----------------------------------------------------------------------------
691 -- Do a pre-upsweep without use of "compile", to establish a
692 -- (downward-closed) set of stable modules for which we won't call compile.
695 -- * has a valid linkable (see getValidLinkables above)
696 -- * depends only on stable modules
697 -- * has an interface in the HIT (interactive mode only)
699 preUpsweep :: [Linkable] -- new valid linkables
701 -> [ModuleName] -- names of all mods encountered in downsweep
702 -> [ModuleName] -- accumulating stable modules
703 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
704 -> IO [ModuleName] -- stable modules
706 preUpsweep valid_lis hit all_home_mods stable [] = return stable
707 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
708 = do let scc = flattenSCC scc0
709 scc_allhomeimps :: [ModuleName]
711 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
712 all_imports_in_scc_or_stable
713 = all in_stable_or_scc scc_allhomeimps
715 = map name_of_summary scc
717 = m `elem` scc_names || m `elem` stable
719 -- now we check for valid linkables: each module in the SCC must
720 -- have a valid linkable (see getValidLinkables above).
721 has_valid_linkable new_summary
722 = isJust (findModuleLinkable_maybe valid_lis modname)
723 where modname = name_of_summary new_summary
725 has_interface summary = ms_mod summary `elemUFM` hit
727 scc_is_stable = all_imports_in_scc_or_stable
728 && all has_valid_linkable scc
729 && all has_interface scc
732 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
733 else preUpsweep valid_lis hit all_home_mods stable sccs
736 -- Helper for preUpsweep. Assuming that new_summary's imports are all
737 -- stable (in the sense of preUpsweep), determine if new_summary is itself
738 -- stable, and, if so, in batch mode, return its linkable.
739 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
740 findInSummaries old_summaries mod_name
741 = [s | s <- old_summaries, name_of_summary s == mod_name]
743 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
744 findModInSummaries old_summaries mod
745 = case [s | s <- old_summaries, ms_mod s == mod] of
749 -- Return (names of) all those in modsDone who are part of a cycle
750 -- as defined by theGraph.
751 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
752 findPartiallyCompletedCycles modsDone theGraph
756 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
757 chew ((CyclicSCC vs):rest)
758 = let names_in_this_cycle = nub (map name_of_summary vs)
760 = nub ([done | done <- modsDone,
761 done `elem` names_in_this_cycle])
762 chewed_rest = chew rest
764 if not (null mods_in_this_cycle)
765 && length mods_in_this_cycle < length names_in_this_cycle
766 then mods_in_this_cycle ++ chewed_rest
770 -- Add the given (LM-form) Linkables to the UI, overwriting previous
771 -- versions if they exist.
772 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
774 = filter (not_in lis) ui ++ lis
776 not_in :: [Linkable] -> Linkable -> Bool
778 = all (\l -> linkableModName l /= mod) lis
779 where mod = linkableModName li
782 data CmThreaded -- stuff threaded through individual module compilations
783 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
786 -- Compile multiple modules, stopping as soon as an error appears.
787 -- There better had not be any cyclic groups here -- we check for them.
788 upsweep_mods :: GhciMode
790 -> UnlinkedImage -- valid linkables
791 -> (ModuleName -> [ModuleName]) -- to construct downward closures
792 -> CmThreaded -- PCS & HST & HIT
793 -> [SCC ModSummary] -- mods to do (the worklist)
794 -- ...... RETURNING ......
795 -> IO (Bool{-complete success?-},
797 [ModSummary], -- mods which succeeded
798 [Linkable]) -- new linkables
800 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
802 = return (True, threaded, [], [])
804 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
806 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
807 unwords (map (moduleNameUserString.name_of_summary) ms))
808 return (False, threaded, [], [])
810 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
811 ((AcyclicSCC mod):mods)
812 = do --case threaded of
813 -- CmThreaded pcsz hstz hitz
814 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
816 (threaded1, maybe_linkable)
817 <- upsweep_mod ghci_mode dflags oldUI threaded mod
818 (reachable_from (name_of_summary mod))
819 case maybe_linkable of
821 -> -- No errors; do the rest
822 do (restOK, threaded2, modOKs, linkables)
823 <- upsweep_mods ghci_mode dflags oldUI reachable_from
825 return (restOK, threaded2, mod:modOKs, linkable:linkables)
826 Nothing -- we got a compilation error; give up now
827 -> return (False, threaded1, [], [])
830 -- Compile a single module. Always produce a Linkable for it if
831 -- successful. If no compilation happened, return the old Linkable.
832 upsweep_mod :: GhciMode
838 -> IO (CmThreaded, Maybe Linkable)
840 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
842 let mod_name = name_of_summary summary1
843 let verb = verbosity dflags
845 let (CmThreaded pcs1 hst1 hit1) = threaded1
846 let old_iface = lookupUFM hit1 mod_name
848 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
850 source_unchanged = isJust maybe_old_linkable
852 reachable_only = filter (/= (name_of_summary summary1))
855 -- in interactive mode, all home modules below us *must* have an
856 -- interface in the HIT. We never demand-load home interfaces in
858 (hst1_strictDC, hit1_strictDC, [])
859 = ASSERT(ghci_mode == Batch ||
860 all (`elemUFM` hit1) reachable_only)
861 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
864 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
867 | Just l <- maybe_old_linkable, isObjectLinkable l = True
870 compresult <- compile ghci_mode summary1 source_unchanged
871 have_object old_iface hst1_strictDC hit1_strictDC pcs1
875 -- Compilation "succeeded", and may or may not have returned a new
876 -- linkable (depending on whether compilation was actually performed
878 CompOK pcs2 new_details new_iface maybe_new_linkable
879 -> do let hst2 = addToUFM hst1 mod_name new_details
880 hit2 = addToUFM hit1 mod_name new_iface
881 threaded2 = CmThreaded pcs2 hst2 hit2
883 return (threaded2, if isJust maybe_new_linkable
884 then maybe_new_linkable
885 else Just old_linkable)
887 -- Compilation failed. compile may still have updated
890 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
891 return (threaded2, Nothing)
893 -- Filter modules in the top level envs (HST, HIT, UI).
894 retainInTopLevelEnvs :: [ModuleName]
895 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
896 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
897 retainInTopLevelEnvs keep_these (hst, hit, ui)
898 = (retainInUFM hst keep_these,
899 retainInUFM hit keep_these,
900 filterModuleLinkables (`elem` keep_these) ui
903 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
904 retainInUFM ufm keys_to_keep
905 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
907 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
909 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
910 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
911 downwards_closure_of_module summaries root
912 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
913 toEdge summ = (name_of_summary summ,
914 filter (`elem` all_mods) (ms_allimps summ))
916 all_mods = map name_of_summary summaries
918 res = simple_transitive_closure (map toEdge summaries) [root]
920 -- trace (showSDoc (text "DC of mod" <+> ppr root
921 -- <+> text "=" <+> ppr res)) $
924 -- Calculate transitive closures from a set of roots given an adjacency list
925 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
926 simple_transitive_closure graph set
927 = let set2 = nub (concatMap dsts set ++ set)
928 dsts node = fromMaybe [] (lookup node graph)
930 if length set == length set2
932 else simple_transitive_closure graph set2
935 -- Calculate SCCs of the module graph, with or without taking into
936 -- account source imports.
937 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
938 topological_sort include_source_imports summaries
940 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
942 = (summ, name_of_summary summ,
943 (if include_source_imports
944 then ms_srcimps summ else []) ++ ms_imps summ)
946 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
947 mash_edge (summ, m, m_imports)
948 = case lookup m key_map of
949 Nothing -> panic "reverse_topological_sort"
950 Just mk -> (summ, mk,
951 -- ignore imports not from the home package
952 catMaybes (map (flip lookup key_map) m_imports))
954 edges = map toEdge summaries
955 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
956 scc_input = map mash_edge edges
957 sccs = stronglyConnComp scc_input
962 -- Chase downwards from the specified root set, returning summaries
963 -- for all home modules encountered. Only follow source-import
964 -- links. Also returns a Bool to indicate whether any of the roots
966 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
967 downsweep rootNm old_summaries
968 = do rootSummaries <- mapM getRootSummary rootNm
970 = any ((=="Main").moduleNameUserString.name_of_summary)
973 <- loop (concat (map ms_imps rootSummaries))
974 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
975 let mod = ms_mod s, isHomeModule mod
977 return (all_summaries, a_root_is_Main)
979 getRootSummary :: FilePath -> IO ModSummary
981 | haskellish_src_file file
982 = do exists <- doesFileExist file
983 if exists then summariseFile file else do
984 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
986 = do exists <- doesFileExist hs_file
987 if exists then summariseFile hs_file else do
988 exists <- doesFileExist lhs_file
989 if exists then summariseFile lhs_file else do
990 let mod_name = mkModuleName file
991 maybe_summary <- getSummary mod_name
992 case maybe_summary of
993 Nothing -> packageModErr mod_name
996 hs_file = file ++ ".hs"
997 lhs_file = file ++ ".lhs"
999 getSummary :: ModuleName -> IO (Maybe ModSummary)
1001 = do found <- findModule nm
1003 Just (mod, location) -> do
1004 let old_summary = findModInSummaries old_summaries mod
1005 summarise mod location old_summary
1007 Nothing -> throwDyn (CmdLineError
1008 ("can't find module `"
1009 ++ showSDoc (ppr nm) ++ "'"))
1011 -- loop invariant: env doesn't contain package modules
1012 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1013 loop [] env = return (moduleEnvElts env)
1015 = do -- imports for modules we don't already have
1016 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1019 needed_summaries <- mapM getSummary needed_imps
1021 -- get just the "home" modules
1022 let new_home_summaries = [ s | Just s <- needed_summaries ]
1024 -- loop, checking the new imports
1025 let new_imps = concat (map ms_imps new_home_summaries)
1026 loop new_imps (extendModuleEnvList env
1027 [ (ms_mod s, s) | s <- new_home_summaries ])
1029 -----------------------------------------------------------------------------
1030 -- Summarising modules
1032 -- We have two types of summarisation:
1034 -- * Summarise a file. This is used for the root module passed to
1035 -- cmLoadModule. The file is read, and used to determine the root
1036 -- module name. The module name may differ from the filename.
1038 -- * Summarise a module. We are given a module name, and must provide
1039 -- a summary. The finder is used to locate the file in which the module
1042 summariseFile :: FilePath -> IO ModSummary
1044 = do hspp_fn <- preprocess file
1045 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1047 let (path, basename, ext) = splitFilename3 file
1050 <- mkHomeModuleLocn mod_name (path ++ '/':basename) (Just file)
1053 <- case ml_hs_file location of
1054 Nothing -> noHsFileErr mod_name
1055 Just src_fn -> getModificationTime src_fn
1057 return (ModSummary mod
1058 location{ml_hspp_file=Just hspp_fn}
1059 srcimps imps src_timestamp)
1061 -- Summarise a module, and pick up source and timestamp.
1062 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1063 -> IO (Maybe ModSummary)
1064 summarise mod location old_summary
1065 | not (isHomeModule mod) = return Nothing
1067 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1069 case ml_hs_file location of {
1071 dflags <- getDynFlags;
1072 when (verbosity dflags >= 1) $
1073 hPutStrLn stderr ("WARNING: module `" ++
1074 moduleUserString mod ++ "' has no source file.");
1080 src_timestamp <- getModificationTime src_fn
1082 -- return the cached summary if the source didn't change
1083 case old_summary of {
1084 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1087 hspp_fn <- preprocess hs_fn
1088 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1090 when (mod_name /= moduleName mod) $
1091 throwDyn (ProgramError
1092 (showSDoc (text hs_fn
1093 <> text ": file name does not match module name"
1094 <+> quotes (ppr (moduleName mod)))))
1096 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1097 srcimps imps src_timestamp))
1103 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1106 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1107 quotes (ppr mod) <+>
1108 text "is a package module")))