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.
181 cmInfoThing :: CmState -> DynFlags -> String
182 -> IO (CmState, PrintUnqualified, [TyThing])
183 cmInfoThing cmstate dflags id
184 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
185 return (cmstate{ pcs=new_pcs }, unqual, things)
187 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
188 unqual = getUnqual pcs hit icontext
190 -----------------------------------------------------------------------------
191 -- cmRunStmt: Run a statement/expr.
194 cmRunStmt :: CmState -> DynFlags -> String
195 -> IO (CmState, -- new state
196 [Name]) -- names bound by this evaluation
197 cmRunStmt cmstate dflags expr
199 let InteractiveContext {
201 ic_type_env = type_env,
202 ic_module = this_mod } = icontext
204 (new_pcs, maybe_stuff)
205 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
208 Nothing -> return (cmstate{ pcs=new_pcs }, [])
209 Just (ids, _, bcos) -> do
211 -- update the interactive context
213 names = map idName ids
215 -- these names have just been shadowed
216 shadowed = [ n | r <- map nameRdrName names,
217 Just n <- [lookupRdrEnv rn_env r] ]
219 new_rn_env = extendLocalRdrEnv rn_env names
221 -- remove any shadowed bindings from the type_env
222 filtered_type_env = delListFromNameEnv type_env shadowed
224 new_type_env = extendNameEnvList filtered_type_env
225 [ (getName id, AnId id) | id <- ids]
227 new_ic = icontext { ic_rn_env = new_rn_env,
228 ic_type_env = new_type_env }
231 hval <- linkExpr pls bcos
234 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
235 hvals <- thing_to_run
237 -- Get the newly bound things, and bind them. Don't forget
238 -- to delete any shadowed bindings from the closure_env, lest
239 -- we end up with a space leak.
240 pls <- delListFromClosureEnv pls shadowed
241 new_pls <- addListToClosureEnv pls (zip names hvals)
243 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
245 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
248 -----------------------------------------------------------------------------
249 -- cmTypeOfExpr: returns a string representing the type of an expression
252 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
253 cmTypeOfExpr cmstate dflags expr
254 = do (new_pcs, maybe_stuff)
255 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
257 let new_cmstate = cmstate{pcs = new_pcs}
260 Nothing -> return (new_cmstate, Nothing)
261 Just (_, ty, _) -> return (new_cmstate, Just str)
263 str = showSDocForUser unqual (ppr tidy_ty)
264 unqual = getUnqual pcs hit ic
265 tidy_ty = tidyType emptyTidyEnv ty
267 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
271 = case lookupIfaceByModName hit pit modname of
272 Nothing -> alwaysQualify
273 Just iface -> unQualInScope (mi_globals iface)
276 modname = moduleName (ic_module ic)
278 -----------------------------------------------------------------------------
279 -- cmTypeOfName: returns a string representing the type of a name.
282 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
283 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
284 = case lookupNameEnv (ic_type_env ic) name of
285 Nothing -> return Nothing
286 Just (AnId id) -> return (Just str)
288 unqual = getUnqual pcs hit ic
289 ty = tidyType emptyTidyEnv (idType id)
290 str = showSDocForUser unqual (ppr ty)
292 _ -> panic "cmTypeOfName"
295 -----------------------------------------------------------------------------
296 -- cmCompileExpr: compile an expression and deliver an HValue
299 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
300 cmCompileExpr cmstate dflags expr
302 let InteractiveContext {
304 ic_type_env = type_env,
305 ic_module = this_mod } = icontext
307 (new_pcs, maybe_stuff)
308 <- hscStmt dflags hst hit pcs icontext
309 ("let __cmCompileExpr = "++expr) False{-stmt-}
312 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
313 Just (ids, _, bcos) -> do
316 hval <- linkExpr pls bcos
319 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
320 hvals <- thing_to_run
323 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
324 _ -> panic "cmCompileExpr"
327 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
330 -----------------------------------------------------------------------------
331 -- cmInfo: return "info" about an expression. The info might be:
333 -- * its type, for an expression,
334 -- * the class definition, for a class
335 -- * the datatype definition, for a tycon (or synonym)
336 -- * the export list, for a module
338 -- Can be used to find the type of the last expression compiled, by looking
341 cmInfo :: CmState -> String -> IO (Maybe String)
343 = do error "cmInfo not implemented yet"
345 -----------------------------------------------------------------------------
346 -- Unload the compilation manager's state: everything it knows about the
347 -- current collection of modules in the Home package.
349 cmUnload :: CmState -> DynFlags -> IO CmState
350 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
351 = do -- Throw away the old home dir cache
354 -- Unload everything the linker knows about
355 new_pls <- CmLink.unload mode dflags [] pls
357 -- Start with a fresh CmState, but keep the PersistentCompilerState
358 new_state <- cmInit mode
359 return new_state{ pcs=pcs, pls=new_pls }
361 -----------------------------------------------------------------------------
362 -- The real business of the compilation manager: given a system state and
363 -- a module name, try and bring the module up to date, probably changing
364 -- the system state at the same time.
366 cmLoadModule :: CmState
368 -> IO (CmState, -- new state
369 Bool, -- was successful
370 [String]) -- list of modules loaded
372 cmLoadModule cmstate1 rootnames
373 = do -- version 1's are the original, before downsweep
374 let pls1 = pls cmstate1
375 let pcs1 = pcs cmstate1
376 let hst1 = hst cmstate1
377 let hit1 = hit cmstate1
378 -- similarly, ui1 is the (complete) set of linkables from
379 -- the previous pass, if any.
380 let ui1 = ui cmstate1
381 let mg1 = mg cmstate1
382 let ic1 = ic cmstate1
384 let ghci_mode = gmode cmstate1 -- this never changes
386 -- Do the downsweep to reestablish the module graph
387 dflags <- getDynFlags
388 let verb = verbosity dflags
390 showPass dflags "Chasing dependencies"
391 when (verb >= 1 && ghci_mode == Batch) $
392 hPutStrLn stderr (showSDoc (hcat [
393 text progName, text ": chasing modules from: ",
394 hcat (punctuate comma (map text rootnames))]))
396 (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
397 let mg2unsorted_names = map name_of_summary mg2unsorted
399 -- reachable_from follows source as well as normal imports
400 let reachable_from :: ModuleName -> [ModuleName]
401 reachable_from = downwards_closure_of_module mg2unsorted
403 -- should be cycle free; ignores 'import source's
404 let mg2 = topological_sort False mg2unsorted
405 -- ... whereas this takes them into account. Used for
406 -- backing out partially complete cycles following a failed
407 -- upsweep, and for removing from hst/hit all the modules
408 -- not in strict downwards closure, during calls to compile.
409 let mg2_with_srcimps = topological_sort True mg2unsorted
411 -- Sort out which linkables we wish to keep in the unlinked image.
412 -- See getValidLinkables below for details.
413 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
415 -- when (verb >= 2) $
416 -- putStrLn (showSDoc (text "Valid linkables:"
417 -- <+> ppr valid_linkables))
419 -- Figure out a stable set of modules which can be retained
420 -- the top level envs, to avoid upsweeping them. Goes to a
421 -- bit of trouble to avoid upsweeping module cycles.
423 -- Construct a set S of stable modules like this:
424 -- Travel upwards, over the sccified graph. For each scc
425 -- of modules ms, add ms to S only if:
426 -- 1. All home imports of ms are either in ms or S
427 -- 2. A valid linkable exists for each module in ms
429 stable_mods <- preUpsweep valid_linkables hit1
430 mg2unsorted_names [] mg2_with_srcimps
433 = concatMap (findInSummaries mg2unsorted) stable_mods
436 = filter (\m -> linkableModName m `elem` stable_mods)
440 putStrLn (showSDoc (text "Stable modules:"
441 <+> sep (map (text.moduleNameUserString) stable_mods)))
443 -- unload any modules which aren't going to be re-linked this
445 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
447 -- We could at this point detect cycles which aren't broken by
448 -- a source-import, and complain immediately, but it seems better
449 -- to let upsweep_mods do this, so at least some useful work gets
450 -- done before the upsweep is abandoned.
452 = filter (\scc -> any (`notElem` stable_mods)
453 (map name_of_summary (flattenSCC scc)))
456 --hPutStrLn stderr "after tsort:\n"
457 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
459 -- Because we don't take into account source imports when doing
460 -- the topological sort, there shouldn't be any cycles in mg2.
461 -- If there is, we complain and give up -- the user needs to
462 -- break the cycle using a boot file.
464 -- Now do the upsweep, calling compile for each module in
465 -- turn. Final result is version 3 of everything.
467 let threaded2 = CmThreaded pcs1 hst1 hit1
469 (upsweep_complete_success, threaded3, modsUpswept, newLis)
470 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
471 threaded2 upsweep_these
473 let ui3 = add_to_ui valid_linkables newLis
474 let (CmThreaded pcs3 hst3 hit3) = threaded3
476 -- At this point, modsUpswept and newLis should have the same
477 -- length, so there is one new (or old) linkable for each
478 -- mod which was processed (passed to compile).
480 -- Make modsDone be the summaries for each home module now
481 -- available; this should equal the domains of hst3 and hit3.
482 -- (NOT STRICTLY TRUE if an interactive session was started
483 -- with some object on disk ???)
484 -- Get in in a roughly top .. bottom order (hence reverse).
486 let modsDone = reverse modsUpswept ++ stable_summaries
488 -- Try and do linking in some form, depending on whether the
489 -- upsweep was completely or only partially successful.
491 if upsweep_complete_success
494 -- Easy; just relink it all.
495 do when (verb >= 2) $
496 hPutStrLn stderr "Upsweep completely successful."
498 -- clean up after ourselves
499 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
501 -- link everything together
502 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
504 cmLoadFinish True linkresult
505 hst3 hit3 ui3 modsDone ghci_mode pcs3
508 -- Tricky. We need to back out the effects of compiling any
509 -- half-done cycles, both so as to clean up the top level envs
510 -- and to avoid telling the interactive linker to link them.
511 do when (verb >= 2) $
512 hPutStrLn stderr "Upsweep partially successful."
515 = map name_of_summary modsDone
516 let mods_to_zap_names
517 = findPartiallyCompletedCycles modsDone_names
520 = filter ((`notElem` mods_to_zap_names).name_of_summary)
523 let (hst4, hit4, ui4)
524 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
527 -- clean up after ourselves
528 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
530 -- link everything together
531 linkresult <- link ghci_mode dflags False ui4 pls2
533 cmLoadFinish False linkresult
534 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
537 -- Finish up after a cmLoad.
539 -- If the link failed, unload everything and return.
540 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
541 dflags <- getDynFlags
542 new_pls <- CmLink.unload ghci_mode dflags [] pls
543 new_state <- cmInit ghci_mode
544 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
546 -- Empty the interactive context and set the module context to the topmost
547 -- newly loaded module, or the Prelude if none were loaded.
548 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
549 = do def_mod <- readIORef defaultCurrentModule
550 let current_mod = case mods of
554 new_ic = emptyInteractiveContext current_mod
556 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
557 gmode=ghci_mode, pcs=pcs, pls=pls,
559 mods_loaded = map (moduleNameUserString.name_of_summary) mods
561 return (new_cmstate, ok, mods_loaded)
563 -- used to fish out the preprocess output files for the purposes
565 ppFilesFromSummaries summaries
566 = [ fn | Just fn <- map toPpFile summaries ]
569 | hspp /= ml_hs_file loc = hspp
570 | otherwise = Nothing
572 loc = ms_location sum
573 hspp = ml_hspp_file loc
576 -----------------------------------------------------------------------------
579 -- For each module (or SCC of modules), we take:
581 -- - an on-disk linkable, if this is the first time around and one
584 -- - the old linkable, otherwise (and if one is available).
586 -- and we throw away the linkable if it is older than the source
587 -- file. We ignore the on-disk linkables unless all of the dependents
588 -- of this SCC also have on-disk linkables.
590 -- If a module has a valid linkable, then it may be STABLE (see below),
591 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
594 -- ToDo: this pass could be merged with the preUpsweep.
597 :: [Linkable] -- old linkables
598 -> [ModuleName] -- all home modules
599 -> [SCC ModSummary] -- all modules in the program, dependency order
600 -> IO [Linkable] -- still-valid linkables
602 getValidLinkables old_linkables all_home_mods module_graph
603 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
605 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
607 scc = flattenSCC scc0
608 scc_names = map name_of_summary scc
609 home_module m = m `elem` all_home_mods && m `notElem` scc_names
610 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
611 -- NOTE: ms_imps, not ms_allimps above. We don't want to
612 -- force a module's SOURCE imports to be already compiled for
613 -- its object linkable to be valid.
615 has_object m = case findModuleLinkable_maybe new_linkables m of
617 Just l -> isObjectLinkable l
619 objects_allowed = all has_object scc_allhomeimps
623 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
625 -- since an scc can contain only all objects or no objects at all,
626 -- we have to check whether we got all objects or not, and re-do
627 -- the linkable check if not.
629 <- if objects_allowed && not (all isObjectLinkable these_linkables)
630 then foldM (getValidLinkable old_linkables False) [] scc
631 else return these_linkables
633 return (adjusted_linkables ++ new_linkables)
636 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
638 getValidLinkable old_linkables objects_allowed new_linkables summary
639 = do let mod_name = name_of_summary summary
642 <- if (not objects_allowed)
644 else case ml_obj_file (ms_location summary) of
645 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
646 Nothing -> return Nothing
648 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
651 Just l | not (isObjectLinkable l) || stillThere l
653 -- ToDo: emit a warning if not (stillThere l)
656 -- make sure that if we had an old disk linkable around, that it's
657 -- still there on the disk (in case we need to re-link it).
659 case maybe_disk_linkable of
661 Just l_disk -> linkableTime l == linkableTime l_disk
663 -- we only look for objects on disk the first time around;
664 -- if the user compiles a module on the side during a GHCi session,
665 -- it won't be picked up until the next ":load". This is what the
666 -- "null old_linkables" test below is.
667 linkable | null old_linkables = maybeToList maybe_disk_linkable
668 | otherwise = maybeToList maybe_old_linkable
670 -- only linkables newer than the source code are valid
671 src_date = ms_hs_date summary
674 = filter (\l -> linkableTime l >= src_date) linkable
675 -- why '>=' rather than '>' above? If the filesystem stores
676 -- times to the nearset second, we may occasionally find that
677 -- the object & source have the same modification time,
678 -- especially if the source was automatically generated
679 -- and compiled. Using >= is slightly unsafe, but it matches
682 return (valid_linkable ++ new_linkables)
685 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
686 maybe_getFileLinkable mod_name obj_fn
687 = do obj_exist <- doesFileExist obj_fn
691 do let stub_fn = case splitFilename3 obj_fn of
692 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
693 stub_exist <- doesFileExist stub_fn
694 obj_time <- getModificationTime obj_fn
696 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
697 else return (Just (LM obj_time mod_name [DotO obj_fn]))
700 -----------------------------------------------------------------------------
701 -- Do a pre-upsweep without use of "compile", to establish a
702 -- (downward-closed) set of stable modules for which we won't call compile.
705 -- * has a valid linkable (see getValidLinkables above)
706 -- * depends only on stable modules
707 -- * has an interface in the HIT (interactive mode only)
709 preUpsweep :: [Linkable] -- new valid linkables
711 -> [ModuleName] -- names of all mods encountered in downsweep
712 -> [ModuleName] -- accumulating stable modules
713 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
714 -> IO [ModuleName] -- stable modules
716 preUpsweep valid_lis hit all_home_mods stable [] = return stable
717 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
718 = do let scc = flattenSCC scc0
719 scc_allhomeimps :: [ModuleName]
721 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
722 all_imports_in_scc_or_stable
723 = all in_stable_or_scc scc_allhomeimps
725 = map name_of_summary scc
727 = m `elem` scc_names || m `elem` stable
729 -- now we check for valid linkables: each module in the SCC must
730 -- have a valid linkable (see getValidLinkables above).
731 has_valid_linkable new_summary
732 = isJust (findModuleLinkable_maybe valid_lis modname)
733 where modname = name_of_summary new_summary
735 has_interface summary = ms_mod summary `elemUFM` hit
737 scc_is_stable = all_imports_in_scc_or_stable
738 && all has_valid_linkable scc
739 && all has_interface scc
742 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
743 else preUpsweep valid_lis hit all_home_mods stable sccs
746 -- Helper for preUpsweep. Assuming that new_summary's imports are all
747 -- stable (in the sense of preUpsweep), determine if new_summary is itself
748 -- stable, and, if so, in batch mode, return its linkable.
749 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
750 findInSummaries old_summaries mod_name
751 = [s | s <- old_summaries, name_of_summary s == mod_name]
753 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
754 findModInSummaries old_summaries mod
755 = case [s | s <- old_summaries, ms_mod s == mod] of
759 -- Return (names of) all those in modsDone who are part of a cycle
760 -- as defined by theGraph.
761 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
762 findPartiallyCompletedCycles modsDone theGraph
766 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
767 chew ((CyclicSCC vs):rest)
768 = let names_in_this_cycle = nub (map name_of_summary vs)
770 = nub ([done | done <- modsDone,
771 done `elem` names_in_this_cycle])
772 chewed_rest = chew rest
774 if not (null mods_in_this_cycle)
775 && length mods_in_this_cycle < length names_in_this_cycle
776 then mods_in_this_cycle ++ chewed_rest
780 -- Add the given (LM-form) Linkables to the UI, overwriting previous
781 -- versions if they exist.
782 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
784 = filter (not_in lis) ui ++ lis
786 not_in :: [Linkable] -> Linkable -> Bool
788 = all (\l -> linkableModName l /= mod) lis
789 where mod = linkableModName li
792 data CmThreaded -- stuff threaded through individual module compilations
793 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
796 -- Compile multiple modules, stopping as soon as an error appears.
797 -- There better had not be any cyclic groups here -- we check for them.
798 upsweep_mods :: GhciMode
800 -> UnlinkedImage -- valid linkables
801 -> (ModuleName -> [ModuleName]) -- to construct downward closures
802 -> CmThreaded -- PCS & HST & HIT
803 -> [SCC ModSummary] -- mods to do (the worklist)
804 -- ...... RETURNING ......
805 -> IO (Bool{-complete success?-},
807 [ModSummary], -- mods which succeeded
808 [Linkable]) -- new linkables
810 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
812 = return (True, threaded, [], [])
814 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
816 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
817 unwords (map (moduleNameUserString.name_of_summary) ms))
818 return (False, threaded, [], [])
820 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
821 ((AcyclicSCC mod):mods)
822 = do --case threaded of
823 -- CmThreaded pcsz hstz hitz
824 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
826 (threaded1, maybe_linkable)
827 <- upsweep_mod ghci_mode dflags oldUI threaded mod
828 (reachable_from (name_of_summary mod))
829 case maybe_linkable of
831 -> -- No errors; do the rest
832 do (restOK, threaded2, modOKs, linkables)
833 <- upsweep_mods ghci_mode dflags oldUI reachable_from
835 return (restOK, threaded2, mod:modOKs, linkable:linkables)
836 Nothing -- we got a compilation error; give up now
837 -> return (False, threaded1, [], [])
840 -- Compile a single module. Always produce a Linkable for it if
841 -- successful. If no compilation happened, return the old Linkable.
842 upsweep_mod :: GhciMode
848 -> IO (CmThreaded, Maybe Linkable)
850 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
852 let mod_name = name_of_summary summary1
853 let verb = verbosity dflags
855 let (CmThreaded pcs1 hst1 hit1) = threaded1
856 let old_iface = lookupUFM hit1 mod_name
858 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
860 source_unchanged = isJust maybe_old_linkable
862 reachable_only = filter (/= (name_of_summary summary1))
865 -- in interactive mode, all home modules below us *must* have an
866 -- interface in the HIT. We never demand-load home interfaces in
868 (hst1_strictDC, hit1_strictDC, [])
869 = ASSERT(ghci_mode == Batch ||
870 all (`elemUFM` hit1) reachable_only)
871 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
874 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
877 | Just l <- maybe_old_linkable, isObjectLinkable l = True
880 compresult <- compile ghci_mode summary1 source_unchanged
881 have_object old_iface hst1_strictDC hit1_strictDC pcs1
885 -- Compilation "succeeded", and may or may not have returned a new
886 -- linkable (depending on whether compilation was actually performed
888 CompOK pcs2 new_details new_iface maybe_new_linkable
889 -> do let hst2 = addToUFM hst1 mod_name new_details
890 hit2 = addToUFM hit1 mod_name new_iface
891 threaded2 = CmThreaded pcs2 hst2 hit2
893 return (threaded2, if isJust maybe_new_linkable
894 then maybe_new_linkable
895 else Just old_linkable)
897 -- Compilation failed. compile may still have updated
900 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
901 return (threaded2, Nothing)
903 -- Filter modules in the top level envs (HST, HIT, UI).
904 retainInTopLevelEnvs :: [ModuleName]
905 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
906 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
907 retainInTopLevelEnvs keep_these (hst, hit, ui)
908 = (retainInUFM hst keep_these,
909 retainInUFM hit keep_these,
910 filterModuleLinkables (`elem` keep_these) ui
913 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
914 retainInUFM ufm keys_to_keep
915 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
917 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
919 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
920 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
921 downwards_closure_of_module summaries root
922 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
923 toEdge summ = (name_of_summary summ,
924 filter (`elem` all_mods) (ms_allimps summ))
926 all_mods = map name_of_summary summaries
928 res = simple_transitive_closure (map toEdge summaries) [root]
930 -- trace (showSDoc (text "DC of mod" <+> ppr root
931 -- <+> text "=" <+> ppr res)) $
934 -- Calculate transitive closures from a set of roots given an adjacency list
935 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
936 simple_transitive_closure graph set
937 = let set2 = nub (concatMap dsts set ++ set)
938 dsts node = fromMaybe [] (lookup node graph)
940 if length set == length set2
942 else simple_transitive_closure graph set2
945 -- Calculate SCCs of the module graph, with or without taking into
946 -- account source imports.
947 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
948 topological_sort include_source_imports summaries
950 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
952 = (summ, name_of_summary summ,
953 (if include_source_imports
954 then ms_srcimps summ else []) ++ ms_imps summ)
956 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
957 mash_edge (summ, m, m_imports)
958 = case lookup m key_map of
959 Nothing -> panic "reverse_topological_sort"
960 Just mk -> (summ, mk,
961 -- ignore imports not from the home package
962 catMaybes (map (flip lookup key_map) m_imports))
964 edges = map toEdge summaries
965 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
966 scc_input = map mash_edge edges
967 sccs = stronglyConnComp scc_input
972 -- Chase downwards from the specified root set, returning summaries
973 -- for all home modules encountered. Only follow source-import
974 -- links. Also returns a Bool to indicate whether any of the roots
976 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
977 downsweep rootNm old_summaries
978 = do rootSummaries <- mapM getRootSummary rootNm
980 = any ((=="Main").moduleNameUserString.name_of_summary)
983 <- loop (concat (map ms_imps rootSummaries))
984 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
985 let mod = ms_mod s, isHomeModule mod
987 return (all_summaries, a_root_is_Main)
989 getRootSummary :: FilePath -> IO ModSummary
991 | haskellish_src_file file
992 = do exists <- doesFileExist file
993 if exists then summariseFile file else do
994 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
996 = do exists <- doesFileExist hs_file
997 if exists then summariseFile hs_file else do
998 exists <- doesFileExist lhs_file
999 if exists then summariseFile lhs_file else do
1000 let mod_name = mkModuleName file
1001 maybe_summary <- getSummary mod_name
1002 case maybe_summary of
1003 Nothing -> packageModErr mod_name
1006 hs_file = file ++ ".hs"
1007 lhs_file = file ++ ".lhs"
1009 getSummary :: ModuleName -> IO (Maybe ModSummary)
1011 = do found <- findModule nm
1013 Just (mod, location) -> do
1014 let old_summary = findModInSummaries old_summaries mod
1015 summarise mod location old_summary
1017 Nothing -> throwDyn (CmdLineError
1018 ("can't find module `"
1019 ++ showSDoc (ppr nm) ++ "'"))
1021 -- loop invariant: env doesn't contain package modules
1022 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1023 loop [] env = return (moduleEnvElts env)
1025 = do -- imports for modules we don't already have
1026 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1029 needed_summaries <- mapM getSummary needed_imps
1031 -- get just the "home" modules
1032 let new_home_summaries = [ s | Just s <- needed_summaries ]
1034 -- loop, checking the new imports
1035 let new_imps = concat (map ms_imps new_home_summaries)
1036 loop new_imps (extendModuleEnvList env
1037 [ (ms_mod s, s) | s <- new_home_summaries ])
1039 -----------------------------------------------------------------------------
1040 -- Summarising modules
1042 -- We have two types of summarisation:
1044 -- * Summarise a file. This is used for the root module passed to
1045 -- cmLoadModule. The file is read, and used to determine the root
1046 -- module name. The module name may differ from the filename.
1048 -- * Summarise a module. We are given a module name, and must provide
1049 -- a summary. The finder is used to locate the file in which the module
1052 summariseFile :: FilePath -> IO ModSummary
1054 = do hspp_fn <- preprocess file
1055 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1057 let (path, basename, ext) = splitFilename3 file
1060 <- mkHomeModuleLocn mod_name (path ++ '/':basename) (Just file)
1063 <- case ml_hs_file location of
1064 Nothing -> noHsFileErr mod_name
1065 Just src_fn -> getModificationTime src_fn
1067 return (ModSummary mod
1068 location{ml_hspp_file=Just hspp_fn}
1069 srcimps imps src_timestamp)
1071 -- Summarise a module, and pick up source and timestamp.
1072 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1073 -> IO (Maybe ModSummary)
1074 summarise mod location old_summary
1075 | not (isHomeModule mod) = return Nothing
1077 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1079 case ml_hs_file location of {
1081 dflags <- getDynFlags;
1082 when (verbosity dflags >= 1) $
1083 hPutStrLn stderr ("WARNING: module `" ++
1084 moduleUserString mod ++ "' has no source file.");
1090 src_timestamp <- getModificationTime src_fn
1092 -- return the cached summary if the source didn't change
1093 case old_summary of {
1094 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1097 hspp_fn <- preprocess hs_fn
1098 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1100 when (mod_name /= moduleName mod) $
1101 throwDyn (ProgramError
1102 (showSDoc (text hs_fn
1103 <> text ": file name does not match module name"
1104 <+> quotes (ppr (moduleName mod)))))
1106 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1107 srcimps imps src_timestamp))
1113 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1116 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1117 quotes (ppr mod) <+>
1118 text "is a package module")))