2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
8 cmInit, -- :: GhciMode -> IO CmState
10 cmLoadModule, -- :: CmState -> FilePath -> IO (CmState, [String])
12 cmUnload, -- :: CmState -> IO CmState
14 cmSetContext, -- :: CmState -> String -> IO CmState
16 cmGetContext, -- :: CmState -> IO String
19 cmRunStmt, -- :: CmState -> DynFlags -> String -> IO (CmState, [Name])
21 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
22 -- -> IO (CmState, Maybe String)
24 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
26 cmCompileExpr,-- :: CmState -> DynFlags -> String
27 -- -> IO (CmState, Maybe HValue)#endif
29 CmState, emptyCmState -- abstract
33 #include "HsVersions.h"
38 import RnEnv ( unQualInScope )
39 import Id ( idType, idName )
40 import Name ( Name, NamedThing(..) )
42 import RdrName ( emptyRdrEnv )
43 import Module ( Module, ModuleName, moduleName, isHomeModule,
44 mkModuleName, moduleNameUserString, moduleUserString )
45 import CmStaticInfo ( GhciMode(..) )
48 import Type ( tidyType )
49 import VarEnv ( emptyTidyEnv )
51 import HscMain ( initPersistentCompilerState )
54 import Unique ( Uniquable )
55 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
56 import DriverFlags ( getDynFlags )
58 import DriverUtil ( splitFilename3 )
59 import ErrUtils ( showPass )
65 import CmdLineOpts ( DynFlags(..) )
69 import Interpreter ( HValue )
70 import HscMain ( hscStmt )
71 import PrelGHC ( unsafeCoerce# )
75 import Exception ( throwDyn )
78 import Time ( ClockTime )
79 import Directory ( getModificationTime, doesFileExist )
88 -- Persistent state for the entire system
91 hst :: HomeSymbolTable, -- home symbol table
92 hit :: HomeIfaceTable, -- home interface table
93 ui :: UnlinkedImage, -- the unlinked images
94 mg :: ModuleGraph, -- the module graph
95 gmode :: GhciMode, -- NEVER CHANGES
96 ic :: InteractiveContext, -- command-line binding info
98 pcs :: PersistentCompilerState, -- compile's persistent state
99 pls :: PersistentLinkerState -- link's persistent state
102 emptyCmState :: GhciMode -> Module -> IO CmState
103 emptyCmState gmode mod
104 = do pcs <- initPersistentCompilerState
106 return (CmState { hst = emptySymbolTable,
107 hit = emptyIfaceTable,
111 ic = emptyInteractiveContext mod,
115 emptyInteractiveContext mod
116 = InteractiveContext { ic_module = mod,
117 ic_rn_env = emptyRdrEnv,
118 ic_type_env = emptyTypeEnv }
120 defaultCurrentModuleName = mkModuleName "Prelude"
121 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
124 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
125 emptyUI :: UnlinkedImage
128 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
129 emptyMG :: ModuleGraph
132 -----------------------------------------------------------------------------
133 -- Produce an initial CmState.
135 cmInit :: GhciMode -> IO CmState
137 prel <- moduleNameToModule defaultCurrentModuleName
138 writeIORef defaultCurrentModule prel
139 emptyCmState mode prel
141 -----------------------------------------------------------------------------
142 -- Setting the context doesn't throw away any bindings; the bindings
143 -- we've built up in the InteractiveContext simply move to the new
144 -- module. They always shadow anything in scope in the current context.
146 cmSetContext :: CmState -> String -> IO CmState
147 cmSetContext cmstate str
148 = do let mn = mkModuleName str
149 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
151 m <- case lookup mn modules_loaded of
154 mod <- moduleNameToModule mn
156 then throwDyn (OtherError (showSDoc
157 (quotes (ppr (moduleName mod))
158 <+> text "is not currently loaded")))
161 return cmstate{ ic = (ic cmstate){ic_module=m} }
163 cmGetContext :: CmState -> IO String
164 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
166 moduleNameToModule :: ModuleName -> IO Module
167 moduleNameToModule mn
168 = do maybe_stuff <- findModule mn
170 Nothing -> throwDyn (OtherError ("can't find module `"
171 ++ moduleNameUserString mn ++ "'"))
172 Just (m,_) -> return m
174 -----------------------------------------------------------------------------
175 -- cmRunStmt: Run a statement/expr.
178 cmRunStmt :: CmState -> DynFlags -> String
179 -> IO (CmState, -- new state
180 [Name]) -- names bound by this evaluation
181 cmRunStmt cmstate dflags expr
183 let InteractiveContext {
185 ic_type_env = type_env,
186 ic_module = this_mod } = icontext
188 (new_pcs, maybe_stuff)
189 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
192 Nothing -> return (cmstate{ pcs=new_pcs }, [])
193 Just (ids, _, bcos) -> do
195 -- update the interactive context
197 new_rn_env = extendLocalRdrEnv rn_env (map idName ids)
199 -- Extend the renamer-env from bound_ids, not
200 -- bound_names, because the latter may contain
201 -- [it] when the former is empty
202 new_type_env = extendNameEnvList type_env
203 [ (getName id, AnId id) | id <- ids]
205 new_ic = icontext { ic_rn_env = new_rn_env,
206 ic_type_env = new_type_env }
209 hval <- linkExpr pls bcos
212 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
213 hvals <- thing_to_run
215 -- get the newly bound things, and bind them
216 let names = map idName ids
217 new_pls <- updateClosureEnv pls (zip names hvals)
219 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
221 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
224 -----------------------------------------------------------------------------
225 -- cmTypeOfExpr: returns a string representing the type of an expression
228 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
229 cmTypeOfExpr cmstate dflags expr
230 = do (new_pcs, maybe_stuff)
231 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
233 let new_cmstate = cmstate{pcs = new_pcs}
236 Nothing -> return (new_cmstate, Nothing)
238 let pit = pcs_PIT pcs
239 modname = moduleName (ic_module ic)
240 tidy_ty = tidyType emptyTidyEnv ty
241 str = case lookupIfaceByModName hit pit modname of
242 Nothing -> showSDoc (ppr tidy_ty)
243 Just iface -> showSDocForUser unqual (ppr tidy_ty)
244 where unqual = unQualInScope (mi_globals iface)
245 in return (new_cmstate, Just str)
247 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
250 -----------------------------------------------------------------------------
251 -- cmTypeOfName: returns a string representing the type of a name.
254 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
255 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
256 = case lookupNameEnv (ic_type_env ic) name of
257 Nothing -> return Nothing
259 let pit = pcs_PIT pcs
260 modname = moduleName (ic_module ic)
261 ty = tidyType emptyTidyEnv (idType id)
262 str = case lookupIfaceByModName hit pit modname of
263 Nothing -> showSDoc (ppr ty)
264 Just iface -> showSDocForUser unqual (ppr ty)
265 where unqual = unQualInScope (mi_globals iface)
268 _ -> panic "cmTypeOfName"
271 -----------------------------------------------------------------------------
272 -- cmCompileExpr: compile an expression and deliver an HValue
275 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
276 cmCompileExpr cmstate dflags expr
278 let InteractiveContext {
280 ic_type_env = type_env,
281 ic_module = this_mod } = icontext
283 (new_pcs, maybe_stuff)
284 <- hscStmt dflags hst hit pcs icontext
285 ("let __cmCompileExpr = "++expr) False{-stmt-}
288 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
289 Just (ids, _, bcos) -> do
292 hval <- linkExpr pls bcos
295 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
296 hvals <- thing_to_run
299 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
300 _ -> panic "cmCompileExpr"
303 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
306 -----------------------------------------------------------------------------
307 -- cmInfo: return "info" about an expression. The info might be:
309 -- * its type, for an expression,
310 -- * the class definition, for a class
311 -- * the datatype definition, for a tycon (or synonym)
312 -- * the export list, for a module
314 -- Can be used to find the type of the last expression compiled, by looking
317 cmInfo :: CmState -> String -> IO (Maybe String)
319 = do error "cmInfo not implemented yet"
321 -----------------------------------------------------------------------------
322 -- Unload the compilation manager's state: everything it knows about the
323 -- current collection of modules in the Home package.
325 cmUnload :: CmState -> IO CmState
327 = do -- Throw away the old home dir cache
329 -- Throw away the HIT and the HST
330 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
332 CmState{ hst=hst, hit=hit } = state
333 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
335 -----------------------------------------------------------------------------
336 -- The real business of the compilation manager: given a system state and
337 -- a module name, try and bring the module up to date, probably changing
338 -- the system state at the same time.
340 cmLoadModule :: CmState
342 -> IO (CmState, -- new state
343 Bool, -- was successful
344 [String]) -- list of modules loaded
346 cmLoadModule cmstate1 rootname
347 = do -- version 1's are the original, before downsweep
348 let pls1 = pls cmstate1
349 let pcs1 = pcs cmstate1
350 let hst1 = hst cmstate1
351 let hit1 = hit cmstate1
352 -- similarly, ui1 is the (complete) set of linkables from
353 -- the previous pass, if any.
354 let ui1 = ui cmstate1
355 let mg1 = mg cmstate1
356 let ic1 = ic cmstate1
358 let ghci_mode = gmode cmstate1 -- this never changes
360 -- Do the downsweep to reestablish the module graph
361 dflags <- getDynFlags
362 let verb = verbosity dflags
364 showPass dflags "Chasing dependencies"
365 when (verb >= 1 && ghci_mode == Batch) $
366 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
368 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
369 let mg2unsorted_names = map name_of_summary mg2unsorted
371 -- reachable_from follows source as well as normal imports
372 let reachable_from :: ModuleName -> [ModuleName]
373 reachable_from = downwards_closure_of_module mg2unsorted
375 -- should be cycle free; ignores 'import source's
376 let mg2 = topological_sort False mg2unsorted
377 -- ... whereas this takes them into account. Used for
378 -- backing out partially complete cycles following a failed
379 -- upsweep, and for removing from hst/hit all the modules
380 -- not in strict downwards closure, during calls to compile.
381 let mg2_with_srcimps = topological_sort True mg2unsorted
383 -- Sort out which linkables we wish to keep in the unlinked image.
384 -- See getValidLinkables below for details.
385 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
388 -- Figure out a stable set of modules which can be retained
389 -- the top level envs, to avoid upsweeping them. Goes to a
390 -- bit of trouble to avoid upsweeping module cycles.
392 -- Construct a set S of stable modules like this:
393 -- Travel upwards, over the sccified graph. For each scc
394 -- of modules ms, add ms to S only if:
395 -- 1. All home imports of ms are either in ms or S
396 -- 2. A valid linkable exists for each module in ms
398 stable_mods <- preUpsweep valid_linkables hit1
399 mg2unsorted_names [] mg2_with_srcimps
402 = concatMap (findInSummaries mg2unsorted) stable_mods
405 = filter (\m -> linkableModName m `elem` stable_mods)
409 putStrLn (showSDoc (text "Stable modules:"
410 <+> sep (map (text.moduleNameUserString) stable_mods)))
412 -- unload any modules which aren't going to be re-linked this
414 pls2 <- unload ghci_mode dflags stable_linkables pls1
416 -- We could at this point detect cycles which aren't broken by
417 -- a source-import, and complain immediately, but it seems better
418 -- to let upsweep_mods do this, so at least some useful work gets
419 -- done before the upsweep is abandoned.
421 = filter (\scc -> any (`notElem` stable_mods)
422 (map name_of_summary (flattenSCC scc)))
425 --hPutStrLn stderr "after tsort:\n"
426 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
428 -- Because we don't take into account source imports when doing
429 -- the topological sort, there shouldn't be any cycles in mg2.
430 -- If there is, we complain and give up -- the user needs to
431 -- break the cycle using a boot file.
433 -- Now do the upsweep, calling compile for each module in
434 -- turn. Final result is version 3 of everything.
436 let threaded2 = CmThreaded pcs1 hst1 hit1
438 (upsweep_complete_success, threaded3, modsUpswept, newLis)
439 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
440 threaded2 upsweep_these
442 let ui3 = add_to_ui valid_linkables newLis
443 let (CmThreaded pcs3 hst3 hit3) = threaded3
445 -- At this point, modsUpswept and newLis should have the same
446 -- length, so there is one new (or old) linkable for each
447 -- mod which was processed (passed to compile).
449 -- Make modsDone be the summaries for each home module now
450 -- available; this should equal the domains of hst3 and hit3.
451 -- (NOT STRICTLY TRUE if an interactive session was started
452 -- with some object on disk ???)
453 -- Get in in a roughly top .. bottom order (hence reverse).
455 let modsDone = reverse modsUpswept ++ stable_summaries
457 -- Try and do linking in some form, depending on whether the
458 -- upsweep was completely or only partially successful.
460 if upsweep_complete_success
463 -- Easy; just relink it all.
464 do when (verb >= 2) $
465 hPutStrLn stderr "Upsweep completely successful."
467 -- clean up after ourselves
468 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
470 -- link everything together
471 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
473 cmLoadFinish True linkresult
474 hst3 hit3 ui3 modsDone ghci_mode pcs3
477 -- Tricky. We need to back out the effects of compiling any
478 -- half-done cycles, both so as to clean up the top level envs
479 -- and to avoid telling the interactive linker to link them.
480 do when (verb >= 2) $
481 hPutStrLn stderr "Upsweep partially successful."
484 = map name_of_summary modsDone
485 let mods_to_zap_names
486 = findPartiallyCompletedCycles modsDone_names
488 let (hst4, hit4, ui4)
489 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
492 = filter ((`notElem` mods_to_zap_names).name_of_summary)
495 -- clean up after ourselves
496 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
498 -- link everything together
499 linkresult <- link ghci_mode dflags False ui4 pls2
501 cmLoadFinish False linkresult
502 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
505 -- Finish up after a cmLoad.
507 -- Empty the interactive context and set the module context to the topmost
508 -- newly loaded module, or the Prelude if none were loaded.
509 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
510 = do case linkresult of {
511 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
514 def_mod <- readIORef defaultCurrentModule
515 let current_mod = case mods of
519 new_ic = emptyInteractiveContext current_mod
521 new_cmstate = CmState{ hst=hst, hit=hit,
523 gmode=ghci_mode, pcs=pcs,
526 mods_loaded = map (moduleNameUserString.name_of_summary) mods
528 return (new_cmstate, ok, mods_loaded)
531 ppFilesFromSummaries summaries
532 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
534 -----------------------------------------------------------------------------
537 -- For each module (or SCC of modules), we take:
539 -- - an on-disk linkable, if this is the first time around and one
542 -- - the old linkable, otherwise (and if one is available).
544 -- and we throw away the linkable if it is older than the source
545 -- file. We ignore the on-disk linkables unless all of the dependents
546 -- of this SCC also have on-disk linkables.
548 -- If a module has a valid linkable, then it may be STABLE (see below),
549 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
552 -- ToDo: this pass could be merged with the preUpsweep.
555 :: [Linkable] -- old linkables
556 -> [ModuleName] -- all home modules
557 -> [SCC ModSummary] -- all modules in the program, dependency order
558 -> IO [Linkable] -- still-valid linkables
560 getValidLinkables old_linkables all_home_mods module_graph
561 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
563 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
565 scc = flattenSCC scc0
566 scc_names = map name_of_summary scc
567 home_module m = m `elem` all_home_mods && m `notElem` scc_names
568 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
570 has_object m = case findModuleLinkable_maybe new_linkables m of
572 Just l -> isObjectLinkable l
574 objects_allowed = all has_object scc_allhomeimps
578 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
580 -- since an scc can contain only all objects or no objects at all,
581 -- we have to check whether we got all objects or not, and re-do
582 -- the linkable check if not.
584 <- if objects_allowed && not (all isObjectLinkable these_linkables)
585 then foldM (getValidLinkable old_linkables False) [] scc
586 else return these_linkables
588 return (adjusted_linkables ++ new_linkables)
591 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
593 getValidLinkable old_linkables objects_allowed new_linkables summary
594 = do let mod_name = name_of_summary summary
597 <- if (not objects_allowed)
599 else case ml_obj_file (ms_location summary) of
600 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
601 Nothing -> return Nothing
603 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
606 Just l | not (isObjectLinkable l) || stillThere l
608 -- ToDo: emit a warning if not (stillThere l)
612 -- make sure that if we had an old disk linkable around, that it's
613 -- still there on the disk (in case we need to re-link it).
615 case maybe_disk_linkable of
617 Just l_disk -> linkableTime l == linkableTime l_disk
619 -- we only look for objects on disk the first time around;
620 -- if the user compiles a module on the side during a GHCi session,
621 -- it won't be picked up until the next ":load". This is what the
622 -- "null old_linkables" test below is.
623 linkable | null old_linkables = maybeToList maybe_disk_linkable
624 | otherwise = maybeToList maybe_old_linkable
626 -- only linkables newer than the source code are valid
627 maybe_src_date = ms_hs_date summary
630 = case maybe_src_date of
631 Nothing -> panic "valid_linkable_list"
633 -> filter (\l -> linkableTime l > src_date) linkable
635 return (valid_linkable ++ new_linkables)
639 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
640 maybe_getFileLinkable mod_name obj_fn
641 = do obj_exist <- doesFileExist obj_fn
645 do let stub_fn = case splitFilename3 obj_fn of
646 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
647 stub_exist <- doesFileExist stub_fn
648 obj_time <- getModificationTime obj_fn
650 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
651 else return (Just (LM obj_time mod_name [DotO obj_fn]))
654 -----------------------------------------------------------------------------
655 -- Do a pre-upsweep without use of "compile", to establish a
656 -- (downward-closed) set of stable modules for which we won't call compile.
659 -- * has a valid linkable (see getValidLinkables above)
660 -- * depends only on stable modules
661 -- * has an interface in the HIT (interactive mode only)
663 preUpsweep :: [Linkable] -- new valid linkables
665 -> [ModuleName] -- names of all mods encountered in downsweep
666 -> [ModuleName] -- accumulating stable modules
667 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
668 -> IO [ModuleName] -- stable modules
670 preUpsweep valid_lis hit all_home_mods stable [] = return stable
671 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
672 = do let scc = flattenSCC scc0
673 scc_allhomeimps :: [ModuleName]
675 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
676 all_imports_in_scc_or_stable
677 = all in_stable_or_scc scc_allhomeimps
679 = map name_of_summary scc
681 = m `elem` scc_names || m `elem` stable
683 -- now we check for valid linkables: each module in the SCC must
684 -- have a valid linkable (see getValidLinkables above).
685 has_valid_linkable new_summary
686 = isJust (findModuleLinkable_maybe valid_lis modname)
687 where modname = name_of_summary new_summary
689 has_interface summary = ms_mod summary `elemUFM` hit
691 scc_is_stable = all_imports_in_scc_or_stable
692 && all has_valid_linkable scc
693 && all has_interface scc
696 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
697 else preUpsweep valid_lis hit all_home_mods stable sccs
700 -- Helper for preUpsweep. Assuming that new_summary's imports are all
701 -- stable (in the sense of preUpsweep), determine if new_summary is itself
702 -- stable, and, if so, in batch mode, return its linkable.
703 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
704 findInSummaries old_summaries mod_name
705 = [s | s <- old_summaries, name_of_summary s == mod_name]
707 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
708 findModInSummaries old_summaries mod
709 = case [s | s <- old_summaries, ms_mod s == mod] of
713 -- Return (names of) all those in modsDone who are part of a cycle
714 -- as defined by theGraph.
715 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
716 findPartiallyCompletedCycles modsDone theGraph
720 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
721 chew ((CyclicSCC vs):rest)
722 = let names_in_this_cycle = nub (map name_of_summary vs)
724 = nub ([done | done <- modsDone,
725 done `elem` names_in_this_cycle])
726 chewed_rest = chew rest
728 if not (null mods_in_this_cycle)
729 && length mods_in_this_cycle < length names_in_this_cycle
730 then mods_in_this_cycle ++ chewed_rest
734 -- Add the given (LM-form) Linkables to the UI, overwriting previous
735 -- versions if they exist.
736 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
738 = filter (not_in lis) ui ++ lis
740 not_in :: [Linkable] -> Linkable -> Bool
742 = all (\l -> linkableModName l /= mod) lis
743 where mod = linkableModName li
746 data CmThreaded -- stuff threaded through individual module compilations
747 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
750 -- Compile multiple modules, stopping as soon as an error appears.
751 -- There better had not be any cyclic groups here -- we check for them.
752 upsweep_mods :: GhciMode
754 -> UnlinkedImage -- valid linkables
755 -> (ModuleName -> [ModuleName]) -- to construct downward closures
756 -> CmThreaded -- PCS & HST & HIT
757 -> [SCC ModSummary] -- mods to do (the worklist)
758 -- ...... RETURNING ......
759 -> IO (Bool{-complete success?-},
761 [ModSummary], -- mods which succeeded
762 [Linkable]) -- new linkables
764 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
766 = return (True, threaded, [], [])
768 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
770 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
771 unwords (map (moduleNameUserString.name_of_summary) ms))
772 return (False, threaded, [], [])
774 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
775 ((AcyclicSCC mod):mods)
776 = do --case threaded of
777 -- CmThreaded pcsz hstz hitz
778 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
780 (threaded1, maybe_linkable)
781 <- upsweep_mod ghci_mode dflags oldUI threaded mod
782 (reachable_from (name_of_summary mod))
783 case maybe_linkable of
785 -> -- No errors; do the rest
786 do (restOK, threaded2, modOKs, linkables)
787 <- upsweep_mods ghci_mode dflags oldUI reachable_from
789 return (restOK, threaded2, mod:modOKs, linkable:linkables)
790 Nothing -- we got a compilation error; give up now
791 -> return (False, threaded1, [], [])
794 -- Compile a single module. Always produce a Linkable for it if
795 -- successful. If no compilation happened, return the old Linkable.
796 upsweep_mod :: GhciMode
802 -> IO (CmThreaded, Maybe Linkable)
804 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
806 let mod_name = name_of_summary summary1
807 let verb = verbosity dflags
809 let (CmThreaded pcs1 hst1 hit1) = threaded1
810 let old_iface = lookupUFM hit1 mod_name
812 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
814 source_unchanged = isJust maybe_old_linkable
816 -- in interactive mode, all home modules below us *must* have an
817 -- interface in the HIT. We never demand-load home interfaces in
819 (hst1_strictDC, hit1_strictDC)
820 = ASSERT(ghci_mode == Batch ||
821 all (`elemUFM` hit1) reachable_from_here)
823 (filter (/= (name_of_summary summary1)) reachable_from_here)
827 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
829 compresult <- compile ghci_mode summary1 source_unchanged
830 old_iface hst1_strictDC hit1_strictDC pcs1
834 -- Compilation "succeeded", but didn't return a new
835 -- linkable, meaning that compilation wasn't needed, and the
836 -- new details were manufactured from the old iface.
837 CompOK pcs2 new_details new_iface Nothing
838 -> do let hst2 = addToUFM hst1 mod_name new_details
839 hit2 = addToUFM hit1 mod_name new_iface
840 threaded2 = CmThreaded pcs2 hst2 hit2
842 if ghci_mode == Interactive && verb >= 1 then
843 -- if we're using an object file, tell the user
845 (LM _ _ objs@(DotO _:_))
846 -> do hPutStrLn stderr (showSDoc (space <>
847 parens (hsep (text "using":
849 [ text o | DotO o <- objs ]))))
854 return (threaded2, Just old_linkable)
856 -- Compilation really did happen, and succeeded. A new
857 -- details, iface and linkable are returned.
858 CompOK pcs2 new_details new_iface (Just new_linkable)
859 -> do let hst2 = addToUFM hst1 mod_name new_details
860 hit2 = addToUFM hit1 mod_name new_iface
861 threaded2 = CmThreaded pcs2 hst2 hit2
863 return (threaded2, Just new_linkable)
865 -- Compilation failed. compile may still have updated
868 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
869 return (threaded2, Nothing)
871 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
872 removeFromTopLevelEnvs :: [ModuleName]
873 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
874 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
875 removeFromTopLevelEnvs zap_these (hst, hit, ui)
876 = (delListFromUFM hst zap_these,
877 delListFromUFM hit zap_these,
878 filterModuleLinkables (`notElem` zap_these) ui
881 retainInTopLevelEnvs :: [ModuleName]
882 -> (HomeSymbolTable, HomeIfaceTable)
883 -> (HomeSymbolTable, HomeIfaceTable)
884 retainInTopLevelEnvs keep_these (hst, hit)
885 = (retainInUFM hst keep_these,
886 retainInUFM hit keep_these
889 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
890 retainInUFM ufm keys_to_keep
891 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
893 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
895 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
896 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
897 downwards_closure_of_module summaries root
898 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
899 toEdge summ = (name_of_summary summ, ms_allimps summ)
900 res = simple_transitive_closure (map toEdge summaries) [root]
902 --trace (showSDoc (text "DC of mod" <+> ppr root
903 -- <+> text "=" <+> ppr res)) (
907 -- Calculate transitive closures from a set of roots given an adjacency list
908 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
909 simple_transitive_closure graph set
910 = let set2 = nub (concatMap dsts set ++ set)
911 dsts node = fromMaybe [] (lookup node graph)
913 if length set == length set2
915 else simple_transitive_closure graph set2
918 -- Calculate SCCs of the module graph, with or without taking into
919 -- account source imports.
920 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
921 topological_sort include_source_imports summaries
923 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
925 = (summ, name_of_summary summ,
926 (if include_source_imports
927 then ms_srcimps summ else []) ++ ms_imps summ)
929 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
930 mash_edge (summ, m, m_imports)
931 = case lookup m key_map of
932 Nothing -> panic "reverse_topological_sort"
933 Just mk -> (summ, mk,
934 -- ignore imports not from the home package
935 catMaybes (map (flip lookup key_map) m_imports))
937 edges = map toEdge summaries
938 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
939 scc_input = map mash_edge edges
940 sccs = stronglyConnComp scc_input
945 -- Chase downwards from the specified root set, returning summaries
946 -- for all home modules encountered. Only follow source-import
947 -- links. Also returns a Bool to indicate whether any of the roots
949 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
950 downsweep rootNm old_summaries
951 = do rootSummaries <- mapM getRootSummary rootNm
953 = any ((=="Main").moduleNameUserString.name_of_summary)
956 <- loop (concat (map ms_imps rootSummaries))
957 (filter (isHomeModule.ms_mod) rootSummaries)
958 return (all_summaries, a_root_is_Main)
960 getRootSummary :: FilePath -> IO ModSummary
962 | haskellish_file file
963 = do exists <- doesFileExist file
964 if exists then summariseFile file else do
965 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
967 = do exists <- doesFileExist hs_file
968 if exists then summariseFile hs_file else do
969 exists <- doesFileExist lhs_file
970 if exists then summariseFile lhs_file else do
971 getSummary (mkModuleName file)
973 hs_file = file ++ ".hs"
974 lhs_file = file ++ ".lhs"
976 getSummary :: ModuleName -> IO ModSummary
978 = do found <- findModule nm
980 Just (mod, location) -> do
981 let old_summary = findModInSummaries old_summaries mod
982 new_summary <- summarise mod location old_summary
984 Nothing -> return (fromJust old_summary)
987 Nothing -> throwDyn (OtherError
988 ("can't find module `"
989 ++ showSDoc (ppr nm) ++ "'"))
991 -- loop invariant: home_summaries doesn't contain package modules
992 loop :: [ModuleName] -> [ModSummary] -> IO [ModSummary]
993 loop [] home_summaries = return home_summaries
994 loop imps home_summaries
995 = do -- all modules currently in homeSummaries
996 let all_home = map (moduleName.ms_mod) home_summaries
998 -- imports for modules we don't already have
999 let needed_imps = nub (filter (`notElem` all_home) imps)
1002 needed_summaries <- mapM getSummary needed_imps
1004 -- get just the "home" modules
1005 let new_home_summaries
1006 = filter (isHomeModule.ms_mod) needed_summaries
1008 -- loop, checking the new imports
1009 let new_imps = concat (map ms_imps new_home_summaries)
1010 loop new_imps (new_home_summaries ++ home_summaries)
1012 -----------------------------------------------------------------------------
1013 -- Summarising modules
1015 -- We have two types of summarisation:
1017 -- * Summarise a file. This is used for the root module passed to
1018 -- cmLoadModule. The file is read, and used to determine the root
1019 -- module name. The module name may differ from the filename.
1021 -- * Summarise a module. We are given a module name, and must provide
1022 -- a summary. The finder is used to locate the file in which the module
1025 summariseFile :: FilePath -> IO ModSummary
1027 = do hspp_fn <- preprocess file
1028 modsrc <- readFile hspp_fn
1030 let (srcimps,imps,mod_name) = getImports modsrc
1031 (path, basename, ext) = splitFilename3 file
1033 Just (mod, location)
1034 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1037 <- case ml_hs_file location of
1038 Nothing -> return Nothing
1039 Just src_fn -> maybe_getModificationTime src_fn
1041 return (ModSummary mod
1042 location{ml_hspp_file=Just hspp_fn}
1044 maybe_src_timestamp)
1046 -- Summarise a module, and pick up source and timestamp.
1047 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1048 -> IO (Maybe ModSummary)
1049 summarise mod location old_summary
1051 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1054 <- case ml_hs_file location of
1055 Nothing -> return Nothing
1056 Just src_fn -> maybe_getModificationTime src_fn
1058 -- return the cached summary if the source didn't change
1059 case old_summary of {
1060 Just s | ms_hs_date s == maybe_src_timestamp -> return Nothing;
1063 hspp_fn <- preprocess hs_fn
1064 modsrc <- readFile hspp_fn
1065 let (srcimps,imps,mod_name) = getImports modsrc
1068 <- case ml_hs_file location of
1069 Nothing -> return Nothing
1070 Just src_fn -> maybe_getModificationTime src_fn
1072 when (mod_name /= moduleName mod) $
1073 throwDyn (OtherError
1074 (showSDoc (text "file name does not match module name: "
1075 <+> ppr (moduleName mod) <+> text "vs"
1078 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1080 maybe_src_timestamp))
1084 = return (Just (ModSummary mod location [] [] Nothing))
1086 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
1087 maybe_getModificationTime fn
1088 = (do time <- getModificationTime fn
1091 (\err -> return Nothing)