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 -- cmInfoThing: convert a String to a TyThing
178 -- A string may refer to more than one TyThing (eg. a constructor,
179 -- and type constructor), so we return a list of all the possible TyThings.
182 cmInfoThing :: CmState -> DynFlags -> String
183 -> IO (CmState, PrintUnqualified, [TyThing])
184 cmInfoThing cmstate dflags id
185 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
186 return (cmstate{ pcs=new_pcs }, unqual, things)
188 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
189 unqual = getUnqual pcs hit icontext
192 -----------------------------------------------------------------------------
193 -- cmRunStmt: Run a statement/expr.
196 cmRunStmt :: CmState -> DynFlags -> String
197 -> IO (CmState, -- new state
198 [Name]) -- names bound by this evaluation
199 cmRunStmt cmstate dflags expr
201 let InteractiveContext {
203 ic_type_env = type_env,
204 ic_module = this_mod } = icontext
206 (new_pcs, maybe_stuff)
207 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
210 Nothing -> return (cmstate{ pcs=new_pcs }, [])
211 Just (ids, _, bcos) -> do
213 -- update the interactive context
215 names = map idName ids
217 -- these names have just been shadowed
218 shadowed = [ n | r <- map nameRdrName names,
219 Just n <- [lookupRdrEnv rn_env r] ]
221 new_rn_env = extendLocalRdrEnv rn_env names
223 -- remove any shadowed bindings from the type_env
224 filtered_type_env = delListFromNameEnv type_env shadowed
226 new_type_env = extendNameEnvList filtered_type_env
227 [ (getName id, AnId id) | id <- ids]
229 new_ic = icontext { ic_rn_env = new_rn_env,
230 ic_type_env = new_type_env }
233 hval <- linkExpr pls bcos
236 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
237 hvals <- thing_to_run
239 -- Get the newly bound things, and bind them. Don't forget
240 -- to delete any shadowed bindings from the closure_env, lest
241 -- we end up with a space leak.
242 pls <- delListFromClosureEnv pls shadowed
243 new_pls <- addListToClosureEnv pls (zip names hvals)
245 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
247 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
250 -----------------------------------------------------------------------------
251 -- cmTypeOfExpr: returns a string representing the type of an expression
254 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
255 cmTypeOfExpr cmstate dflags expr
256 = do (new_pcs, maybe_stuff)
257 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
259 let new_cmstate = cmstate{pcs = new_pcs}
262 Nothing -> return (new_cmstate, Nothing)
263 Just (_, ty, _) -> return (new_cmstate, Just str)
265 str = showSDocForUser unqual (ppr tidy_ty)
266 unqual = getUnqual pcs hit ic
267 tidy_ty = tidyType emptyTidyEnv ty
269 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
273 = case lookupIfaceByModName hit pit modname of
274 Nothing -> alwaysQualify
275 Just iface -> unQualInScope (mi_globals iface)
278 modname = moduleName (ic_module ic)
280 -----------------------------------------------------------------------------
281 -- cmTypeOfName: returns a string representing the type of a name.
284 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
285 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
286 = case lookupNameEnv (ic_type_env ic) name of
287 Nothing -> return Nothing
288 Just (AnId id) -> return (Just str)
290 unqual = getUnqual pcs hit ic
291 ty = tidyType emptyTidyEnv (idType id)
292 str = showSDocForUser unqual (ppr ty)
294 _ -> panic "cmTypeOfName"
297 -----------------------------------------------------------------------------
298 -- cmCompileExpr: compile an expression and deliver an HValue
301 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
302 cmCompileExpr cmstate dflags expr
304 let InteractiveContext {
306 ic_type_env = type_env,
307 ic_module = this_mod } = icontext
309 (new_pcs, maybe_stuff)
310 <- hscStmt dflags hst hit pcs icontext
311 ("let __cmCompileExpr = "++expr) False{-stmt-}
314 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
315 Just (ids, _, bcos) -> do
318 hval <- linkExpr pls bcos
321 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
322 hvals <- thing_to_run
325 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
326 _ -> panic "cmCompileExpr"
329 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
332 -----------------------------------------------------------------------------
333 -- cmInfo: return "info" about an expression. The info might be:
335 -- * its type, for an expression,
336 -- * the class definition, for a class
337 -- * the datatype definition, for a tycon (or synonym)
338 -- * the export list, for a module
340 -- Can be used to find the type of the last expression compiled, by looking
343 cmInfo :: CmState -> String -> IO (Maybe String)
345 = do error "cmInfo not implemented yet"
347 -----------------------------------------------------------------------------
348 -- Unload the compilation manager's state: everything it knows about the
349 -- current collection of modules in the Home package.
351 cmUnload :: CmState -> DynFlags -> IO CmState
352 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
353 = do -- Throw away the old home dir cache
356 -- Unload everything the linker knows about
357 new_pls <- CmLink.unload mode dflags [] pls
359 -- Start with a fresh CmState, but keep the PersistentCompilerState
360 new_state <- cmInit mode
361 return new_state{ pcs=pcs, pls=new_pls }
363 -----------------------------------------------------------------------------
364 -- The real business of the compilation manager: given a system state and
365 -- a module name, try and bring the module up to date, probably changing
366 -- the system state at the same time.
368 cmLoadModule :: CmState
370 -> IO (CmState, -- new state
371 Bool, -- was successful
372 [String]) -- list of modules loaded
374 cmLoadModule cmstate1 rootnames
375 = do -- version 1's are the original, before downsweep
376 let pls1 = pls cmstate1
377 let pcs1 = pcs cmstate1
378 let hst1 = hst cmstate1
379 let hit1 = hit cmstate1
380 -- similarly, ui1 is the (complete) set of linkables from
381 -- the previous pass, if any.
382 let ui1 = ui cmstate1
383 let mg1 = mg cmstate1
384 let ic1 = ic cmstate1
386 let ghci_mode = gmode cmstate1 -- this never changes
388 -- Do the downsweep to reestablish the module graph
389 dflags <- getDynFlags
390 let verb = verbosity dflags
392 showPass dflags "Chasing dependencies"
393 when (verb >= 1 && ghci_mode == Batch) $
394 hPutStrLn stderr (showSDoc (hcat [
395 text progName, text ": chasing modules from: ",
396 hcat (punctuate comma (map text rootnames))]))
398 (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
399 let mg2unsorted_names = map name_of_summary mg2unsorted
401 -- reachable_from follows source as well as normal imports
402 let reachable_from :: ModuleName -> [ModuleName]
403 reachable_from = downwards_closure_of_module mg2unsorted
405 -- should be cycle free; ignores 'import source's
406 let mg2 = topological_sort False mg2unsorted
407 -- ... whereas this takes them into account. Used for
408 -- backing out partially complete cycles following a failed
409 -- upsweep, and for removing from hst/hit all the modules
410 -- not in strict downwards closure, during calls to compile.
411 let mg2_with_srcimps = topological_sort True mg2unsorted
413 -- Sort out which linkables we wish to keep in the unlinked image.
414 -- See getValidLinkables below for details.
415 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
417 -- when (verb >= 2) $
418 -- putStrLn (showSDoc (text "Valid linkables:"
419 -- <+> ppr valid_linkables))
421 -- Figure out a stable set of modules which can be retained
422 -- the top level envs, to avoid upsweeping them. Goes to a
423 -- bit of trouble to avoid upsweeping module cycles.
425 -- Construct a set S of stable modules like this:
426 -- Travel upwards, over the sccified graph. For each scc
427 -- of modules ms, add ms to S only if:
428 -- 1. All home imports of ms are either in ms or S
429 -- 2. A valid linkable exists for each module in ms
431 stable_mods <- preUpsweep valid_linkables hit1
432 mg2unsorted_names [] mg2_with_srcimps
435 = concatMap (findInSummaries mg2unsorted) stable_mods
438 = filter (\m -> linkableModName m `elem` stable_mods)
442 putStrLn (showSDoc (text "Stable modules:"
443 <+> sep (map (text.moduleNameUserString) stable_mods)))
445 -- unload any modules which aren't going to be re-linked this
447 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
449 -- We could at this point detect cycles which aren't broken by
450 -- a source-import, and complain immediately, but it seems better
451 -- to let upsweep_mods do this, so at least some useful work gets
452 -- done before the upsweep is abandoned.
454 = filter (\scc -> any (`notElem` stable_mods)
455 (map name_of_summary (flattenSCC scc)))
458 --hPutStrLn stderr "after tsort:\n"
459 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
461 -- Because we don't take into account source imports when doing
462 -- the topological sort, there shouldn't be any cycles in mg2.
463 -- If there is, we complain and give up -- the user needs to
464 -- break the cycle using a boot file.
466 -- Now do the upsweep, calling compile for each module in
467 -- turn. Final result is version 3 of everything.
469 let threaded2 = CmThreaded pcs1 hst1 hit1
471 (upsweep_complete_success, threaded3, modsUpswept, newLis)
472 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
473 threaded2 upsweep_these
475 let ui3 = add_to_ui valid_linkables newLis
476 let (CmThreaded pcs3 hst3 hit3) = threaded3
478 -- At this point, modsUpswept and newLis should have the same
479 -- length, so there is one new (or old) linkable for each
480 -- mod which was processed (passed to compile).
482 -- Make modsDone be the summaries for each home module now
483 -- available; this should equal the domains of hst3 and hit3.
484 -- (NOT STRICTLY TRUE if an interactive session was started
485 -- with some object on disk ???)
486 -- Get in in a roughly top .. bottom order (hence reverse).
488 let modsDone = reverse modsUpswept ++ stable_summaries
490 -- Try and do linking in some form, depending on whether the
491 -- upsweep was completely or only partially successful.
493 if upsweep_complete_success
496 -- Easy; just relink it all.
497 do when (verb >= 2) $
498 hPutStrLn stderr "Upsweep completely successful."
500 -- clean up after ourselves
501 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
503 -- link everything together
504 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
506 cmLoadFinish True linkresult
507 hst3 hit3 ui3 modsDone ghci_mode pcs3
510 -- Tricky. We need to back out the effects of compiling any
511 -- half-done cycles, both so as to clean up the top level envs
512 -- and to avoid telling the interactive linker to link them.
513 do when (verb >= 2) $
514 hPutStrLn stderr "Upsweep partially successful."
517 = map name_of_summary modsDone
518 let mods_to_zap_names
519 = findPartiallyCompletedCycles modsDone_names
522 = filter ((`notElem` mods_to_zap_names).name_of_summary)
525 let (hst4, hit4, ui4)
526 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
529 -- clean up after ourselves
530 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
532 -- link everything together
533 linkresult <- link ghci_mode dflags False ui4 pls2
535 cmLoadFinish False linkresult
536 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
539 -- Finish up after a cmLoad.
541 -- If the link failed, unload everything and return.
542 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
543 dflags <- getDynFlags
544 new_pls <- CmLink.unload ghci_mode dflags [] pls
545 new_state <- cmInit ghci_mode
546 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
548 -- Empty the interactive context and set the module context to the topmost
549 -- newly loaded module, or the Prelude if none were loaded.
550 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
551 = do def_mod <- readIORef defaultCurrentModule
552 let current_mod = case mods of
556 new_ic = emptyInteractiveContext current_mod
558 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
559 gmode=ghci_mode, pcs=pcs, pls=pls,
561 mods_loaded = map (moduleNameUserString.name_of_summary) mods
563 return (new_cmstate, ok, mods_loaded)
565 -- used to fish out the preprocess output files for the purposes
567 ppFilesFromSummaries summaries
568 = [ fn | Just fn <- map toPpFile summaries ]
571 | hspp /= ml_hs_file loc = hspp
572 | otherwise = Nothing
574 loc = ms_location sum
575 hspp = ml_hspp_file loc
578 -----------------------------------------------------------------------------
581 -- For each module (or SCC of modules), we take:
583 -- - an on-disk linkable, if this is the first time around and one
586 -- - the old linkable, otherwise (and if one is available).
588 -- and we throw away the linkable if it is older than the source
589 -- file. We ignore the on-disk linkables unless all of the dependents
590 -- of this SCC also have on-disk linkables.
592 -- If a module has a valid linkable, then it may be STABLE (see below),
593 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
596 -- ToDo: this pass could be merged with the preUpsweep.
599 :: [Linkable] -- old linkables
600 -> [ModuleName] -- all home modules
601 -> [SCC ModSummary] -- all modules in the program, dependency order
602 -> IO [Linkable] -- still-valid linkables
604 getValidLinkables old_linkables all_home_mods module_graph
605 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
607 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
609 scc = flattenSCC scc0
610 scc_names = map name_of_summary scc
611 home_module m = m `elem` all_home_mods && m `notElem` scc_names
612 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
613 -- NOTE: ms_imps, not ms_allimps above. We don't want to
614 -- force a module's SOURCE imports to be already compiled for
615 -- its object linkable to be valid.
617 has_object m = case findModuleLinkable_maybe new_linkables m of
619 Just l -> isObjectLinkable l
621 objects_allowed = all has_object scc_allhomeimps
625 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
627 -- since an scc can contain only all objects or no objects at all,
628 -- we have to check whether we got all objects or not, and re-do
629 -- the linkable check if not.
631 <- if objects_allowed && not (all isObjectLinkable these_linkables)
632 then foldM (getValidLinkable old_linkables False) [] scc
633 else return these_linkables
635 return (adjusted_linkables ++ new_linkables)
638 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
640 getValidLinkable old_linkables objects_allowed new_linkables summary
641 = do let mod_name = name_of_summary summary
644 <- if (not objects_allowed)
646 else case ml_obj_file (ms_location summary) of
647 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
648 Nothing -> return Nothing
650 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
653 Just l | not (isObjectLinkable l) || stillThere l
655 -- ToDo: emit a warning if not (stillThere l)
658 -- make sure that if we had an old disk linkable around, that it's
659 -- still there on the disk (in case we need to re-link it).
661 case maybe_disk_linkable of
663 Just l_disk -> linkableTime l == linkableTime l_disk
665 -- we only look for objects on disk the first time around;
666 -- if the user compiles a module on the side during a GHCi session,
667 -- it won't be picked up until the next ":load". This is what the
668 -- "null old_linkables" test below is.
669 linkable | null old_linkables = maybeToList maybe_disk_linkable
670 | otherwise = maybeToList maybe_old_linkable
672 -- only linkables newer than the source code are valid
673 src_date = ms_hs_date summary
676 = filter (\l -> linkableTime l >= src_date) linkable
677 -- why '>=' rather than '>' above? If the filesystem stores
678 -- times to the nearset second, we may occasionally find that
679 -- the object & source have the same modification time,
680 -- especially if the source was automatically generated
681 -- and compiled. Using >= is slightly unsafe, but it matches
684 return (valid_linkable ++ new_linkables)
687 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
688 maybe_getFileLinkable mod_name obj_fn
689 = do obj_exist <- doesFileExist obj_fn
693 do let stub_fn = case splitFilename3 obj_fn of
694 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
695 stub_exist <- doesFileExist stub_fn
696 obj_time <- getModificationTime obj_fn
698 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
699 else return (Just (LM obj_time mod_name [DotO obj_fn]))
702 -----------------------------------------------------------------------------
703 -- Do a pre-upsweep without use of "compile", to establish a
704 -- (downward-closed) set of stable modules for which we won't call compile.
707 -- * has a valid linkable (see getValidLinkables above)
708 -- * depends only on stable modules
709 -- * has an interface in the HIT (interactive mode only)
711 preUpsweep :: [Linkable] -- new valid linkables
713 -> [ModuleName] -- names of all mods encountered in downsweep
714 -> [ModuleName] -- accumulating stable modules
715 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
716 -> IO [ModuleName] -- stable modules
718 preUpsweep valid_lis hit all_home_mods stable [] = return stable
719 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
720 = do let scc = flattenSCC scc0
721 scc_allhomeimps :: [ModuleName]
723 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
724 all_imports_in_scc_or_stable
725 = all in_stable_or_scc scc_allhomeimps
727 = map name_of_summary scc
729 = m `elem` scc_names || m `elem` stable
731 -- now we check for valid linkables: each module in the SCC must
732 -- have a valid linkable (see getValidLinkables above).
733 has_valid_linkable new_summary
734 = isJust (findModuleLinkable_maybe valid_lis modname)
735 where modname = name_of_summary new_summary
737 has_interface summary = ms_mod summary `elemUFM` hit
739 scc_is_stable = all_imports_in_scc_or_stable
740 && all has_valid_linkable scc
741 && all has_interface scc
744 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
745 else preUpsweep valid_lis hit all_home_mods stable sccs
748 -- Helper for preUpsweep. Assuming that new_summary's imports are all
749 -- stable (in the sense of preUpsweep), determine if new_summary is itself
750 -- stable, and, if so, in batch mode, return its linkable.
751 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
752 findInSummaries old_summaries mod_name
753 = [s | s <- old_summaries, name_of_summary s == mod_name]
755 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
756 findModInSummaries old_summaries mod
757 = case [s | s <- old_summaries, ms_mod s == mod] of
761 -- Return (names of) all those in modsDone who are part of a cycle
762 -- as defined by theGraph.
763 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
764 findPartiallyCompletedCycles modsDone theGraph
768 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
769 chew ((CyclicSCC vs):rest)
770 = let names_in_this_cycle = nub (map name_of_summary vs)
772 = nub ([done | done <- modsDone,
773 done `elem` names_in_this_cycle])
774 chewed_rest = chew rest
776 if not (null mods_in_this_cycle)
777 && length mods_in_this_cycle < length names_in_this_cycle
778 then mods_in_this_cycle ++ chewed_rest
782 -- Add the given (LM-form) Linkables to the UI, overwriting previous
783 -- versions if they exist.
784 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
786 = filter (not_in lis) ui ++ lis
788 not_in :: [Linkable] -> Linkable -> Bool
790 = all (\l -> linkableModName l /= mod) lis
791 where mod = linkableModName li
794 data CmThreaded -- stuff threaded through individual module compilations
795 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
798 -- Compile multiple modules, stopping as soon as an error appears.
799 -- There better had not be any cyclic groups here -- we check for them.
800 upsweep_mods :: GhciMode
802 -> UnlinkedImage -- valid linkables
803 -> (ModuleName -> [ModuleName]) -- to construct downward closures
804 -> CmThreaded -- PCS & HST & HIT
805 -> [SCC ModSummary] -- mods to do (the worklist)
806 -- ...... RETURNING ......
807 -> IO (Bool{-complete success?-},
809 [ModSummary], -- mods which succeeded
810 [Linkable]) -- new linkables
812 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
814 = return (True, threaded, [], [])
816 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
818 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
819 unwords (map (moduleNameUserString.name_of_summary) ms))
820 return (False, threaded, [], [])
822 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
823 ((AcyclicSCC mod):mods)
824 = do --case threaded of
825 -- CmThreaded pcsz hstz hitz
826 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
828 (threaded1, maybe_linkable)
829 <- upsweep_mod ghci_mode dflags oldUI threaded mod
830 (reachable_from (name_of_summary mod))
831 case maybe_linkable of
833 -> -- No errors; do the rest
834 do (restOK, threaded2, modOKs, linkables)
835 <- upsweep_mods ghci_mode dflags oldUI reachable_from
837 return (restOK, threaded2, mod:modOKs, linkable:linkables)
838 Nothing -- we got a compilation error; give up now
839 -> return (False, threaded1, [], [])
842 -- Compile a single module. Always produce a Linkable for it if
843 -- successful. If no compilation happened, return the old Linkable.
844 upsweep_mod :: GhciMode
850 -> IO (CmThreaded, Maybe Linkable)
852 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
854 let mod_name = name_of_summary summary1
855 let verb = verbosity dflags
857 let (CmThreaded pcs1 hst1 hit1) = threaded1
858 let old_iface = lookupUFM hit1 mod_name
860 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
862 source_unchanged = isJust maybe_old_linkable
864 reachable_only = filter (/= (name_of_summary summary1))
867 -- in interactive mode, all home modules below us *must* have an
868 -- interface in the HIT. We never demand-load home interfaces in
870 (hst1_strictDC, hit1_strictDC, [])
871 = ASSERT(ghci_mode == Batch ||
872 all (`elemUFM` hit1) reachable_only)
873 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
876 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
879 | Just l <- maybe_old_linkable, isObjectLinkable l = True
882 compresult <- compile ghci_mode summary1 source_unchanged
883 have_object old_iface hst1_strictDC hit1_strictDC pcs1
887 -- Compilation "succeeded", and may or may not have returned a new
888 -- linkable (depending on whether compilation was actually performed
890 CompOK pcs2 new_details new_iface maybe_new_linkable
891 -> do let hst2 = addToUFM hst1 mod_name new_details
892 hit2 = addToUFM hit1 mod_name new_iface
893 threaded2 = CmThreaded pcs2 hst2 hit2
895 return (threaded2, if isJust maybe_new_linkable
896 then maybe_new_linkable
897 else Just old_linkable)
899 -- Compilation failed. compile may still have updated
902 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
903 return (threaded2, Nothing)
905 -- Filter modules in the top level envs (HST, HIT, UI).
906 retainInTopLevelEnvs :: [ModuleName]
907 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
908 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
909 retainInTopLevelEnvs keep_these (hst, hit, ui)
910 = (retainInUFM hst keep_these,
911 retainInUFM hit keep_these,
912 filterModuleLinkables (`elem` keep_these) ui
915 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
916 retainInUFM ufm keys_to_keep
917 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
919 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
921 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
922 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
923 downwards_closure_of_module summaries root
924 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
925 toEdge summ = (name_of_summary summ,
926 filter (`elem` all_mods) (ms_allimps summ))
928 all_mods = map name_of_summary summaries
930 res = simple_transitive_closure (map toEdge summaries) [root]
932 -- trace (showSDoc (text "DC of mod" <+> ppr root
933 -- <+> text "=" <+> ppr res)) $
936 -- Calculate transitive closures from a set of roots given an adjacency list
937 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
938 simple_transitive_closure graph set
939 = let set2 = nub (concatMap dsts set ++ set)
940 dsts node = fromMaybe [] (lookup node graph)
942 if length set == length set2
944 else simple_transitive_closure graph set2
947 -- Calculate SCCs of the module graph, with or without taking into
948 -- account source imports.
949 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
950 topological_sort include_source_imports summaries
952 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
954 = (summ, name_of_summary summ,
955 (if include_source_imports
956 then ms_srcimps summ else []) ++ ms_imps summ)
958 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
959 mash_edge (summ, m, m_imports)
960 = case lookup m key_map of
961 Nothing -> panic "reverse_topological_sort"
962 Just mk -> (summ, mk,
963 -- ignore imports not from the home package
964 catMaybes (map (flip lookup key_map) m_imports))
966 edges = map toEdge summaries
967 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
968 scc_input = map mash_edge edges
969 sccs = stronglyConnComp scc_input
974 -- Chase downwards from the specified root set, returning summaries
975 -- for all home modules encountered. Only follow source-import
976 -- links. Also returns a Bool to indicate whether any of the roots
978 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
979 downsweep rootNm old_summaries
980 = do rootSummaries <- mapM getRootSummary rootNm
982 = any ((=="Main").moduleNameUserString.name_of_summary)
985 <- loop (concat (map ms_imps rootSummaries))
986 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
987 let mod = ms_mod s, isHomeModule mod
989 return (all_summaries, a_root_is_Main)
991 getRootSummary :: FilePath -> IO ModSummary
993 | haskellish_src_file file
994 = do exists <- doesFileExist file
995 if exists then summariseFile file else do
996 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
998 = do exists <- doesFileExist hs_file
999 if exists then summariseFile hs_file else do
1000 exists <- doesFileExist lhs_file
1001 if exists then summariseFile lhs_file else do
1002 let mod_name = mkModuleName file
1003 maybe_summary <- getSummary mod_name
1004 case maybe_summary of
1005 Nothing -> packageModErr mod_name
1008 hs_file = file ++ ".hs"
1009 lhs_file = file ++ ".lhs"
1011 getSummary :: ModuleName -> IO (Maybe ModSummary)
1013 = do found <- findModule nm
1015 Just (mod, location) -> do
1016 let old_summary = findModInSummaries old_summaries mod
1017 summarise mod location old_summary
1019 Nothing -> throwDyn (CmdLineError
1020 ("can't find module `"
1021 ++ showSDoc (ppr nm) ++ "'"))
1023 -- loop invariant: env doesn't contain package modules
1024 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1025 loop [] env = return (moduleEnvElts env)
1027 = do -- imports for modules we don't already have
1028 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1031 needed_summaries <- mapM getSummary needed_imps
1033 -- get just the "home" modules
1034 let new_home_summaries = [ s | Just s <- needed_summaries ]
1036 -- loop, checking the new imports
1037 let new_imps = concat (map ms_imps new_home_summaries)
1038 loop new_imps (extendModuleEnvList env
1039 [ (ms_mod s, s) | s <- new_home_summaries ])
1041 -----------------------------------------------------------------------------
1042 -- Summarising modules
1044 -- We have two types of summarisation:
1046 -- * Summarise a file. This is used for the root module passed to
1047 -- cmLoadModule. The file is read, and used to determine the root
1048 -- module name. The module name may differ from the filename.
1050 -- * Summarise a module. We are given a module name, and must provide
1051 -- a summary. The finder is used to locate the file in which the module
1054 summariseFile :: FilePath -> IO ModSummary
1056 = do hspp_fn <- preprocess file
1057 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1059 let (path, basename, ext) = splitFilename3 file
1062 <- mkHomeModuleLocn mod_name (path ++ '/':basename) (Just file)
1065 <- case ml_hs_file location of
1066 Nothing -> noHsFileErr mod_name
1067 Just src_fn -> getModificationTime src_fn
1069 return (ModSummary mod
1070 location{ml_hspp_file=Just hspp_fn}
1071 srcimps imps src_timestamp)
1073 -- Summarise a module, and pick up source and timestamp.
1074 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1075 -> IO (Maybe ModSummary)
1076 summarise mod location old_summary
1077 | not (isHomeModule mod) = return Nothing
1079 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1081 case ml_hs_file location of {
1083 dflags <- getDynFlags;
1084 when (verbosity dflags >= 1) $
1085 hPutStrLn stderr ("WARNING: module `" ++
1086 moduleUserString mod ++ "' has no source file.");
1092 src_timestamp <- getModificationTime src_fn
1094 -- return the cached summary if the source didn't change
1095 case old_summary of {
1096 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1099 hspp_fn <- preprocess hs_fn
1100 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1102 when (mod_name /= moduleName mod) $
1103 throwDyn (ProgramError
1104 (showSDoc (text hs_fn
1105 <> text ": file name does not match module name"
1106 <+> quotes (ppr (moduleName mod)))))
1108 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1109 srcimps imps src_timestamp))
1115 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1118 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1119 quotes (ppr mod) <+>
1120 text "is a package module")))