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 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"
37 import CmStaticInfo ( GhciMode(..) )
39 import DriverFlags ( getDynFlags )
43 import HscMain ( initPersistentCompilerState )
45 import RnEnv ( unQualInScope )
46 import Id ( idType, idName )
47 import Name ( Name, NamedThing(..), nameRdrName )
49 import RdrName ( lookupRdrEnv, emptyRdrEnv )
52 import Type ( tidyType )
53 import VarEnv ( emptyTidyEnv )
55 import Unique ( Uniquable )
56 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
57 import ErrUtils ( showPass )
62 import CmdLineOpts ( DynFlags(..) )
66 import Interpreter ( HValue )
67 import HscMain ( hscStmt )
68 import PrelGHC ( unsafeCoerce# )
72 import Exception ( throwDyn )
75 import Directory ( getModificationTime, doesFileExist )
84 -- Persistent state for the entire system
87 hst :: HomeSymbolTable, -- home symbol table
88 hit :: HomeIfaceTable, -- home interface table
89 ui :: UnlinkedImage, -- the unlinked images
90 mg :: ModuleGraph, -- the module graph
91 gmode :: GhciMode, -- NEVER CHANGES
92 ic :: InteractiveContext, -- command-line binding info
94 pcs :: PersistentCompilerState, -- compile's persistent state
95 pls :: PersistentLinkerState -- link's persistent state
98 emptyCmState :: GhciMode -> Module -> IO CmState
99 emptyCmState gmode mod
100 = do pcs <- initPersistentCompilerState
102 return (CmState { hst = emptySymbolTable,
103 hit = emptyIfaceTable,
107 ic = emptyInteractiveContext mod,
111 emptyInteractiveContext mod
112 = InteractiveContext { ic_module = mod,
113 ic_rn_env = emptyRdrEnv,
114 ic_type_env = emptyTypeEnv }
116 defaultCurrentModuleName = mkModuleName "Prelude"
117 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
120 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
121 emptyUI :: UnlinkedImage
124 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
125 emptyMG :: ModuleGraph
128 -----------------------------------------------------------------------------
129 -- Produce an initial CmState.
131 cmInit :: GhciMode -> IO CmState
133 prel <- moduleNameToModule defaultCurrentModuleName
134 writeIORef defaultCurrentModule prel
135 emptyCmState mode prel
137 -----------------------------------------------------------------------------
138 -- Setting the context doesn't throw away any bindings; the bindings
139 -- we've built up in the InteractiveContext simply move to the new
140 -- module. They always shadow anything in scope in the current context.
142 cmSetContext :: CmState -> String -> IO CmState
143 cmSetContext cmstate str
144 = do let mn = mkModuleName str
145 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
147 m <- case lookup mn modules_loaded of
150 mod <- moduleNameToModule mn
152 then throwDyn (CmdLineError (showSDoc
153 (quotes (ppr (moduleName mod))
154 <+> text "is not currently loaded")))
157 return cmstate{ ic = (ic cmstate){ic_module=m} }
159 cmGetContext :: CmState -> IO String
160 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
162 moduleNameToModule :: ModuleName -> IO Module
163 moduleNameToModule mn
164 = do maybe_stuff <- findModule mn
166 Nothing -> throwDyn (CmdLineError ("can't find module `"
167 ++ moduleNameUserString mn ++ "'"))
168 Just (m,_) -> return m
170 -----------------------------------------------------------------------------
171 -- cmRunStmt: Run a statement/expr.
174 cmRunStmt :: CmState -> DynFlags -> String
175 -> IO (CmState, -- new state
176 [Name]) -- names bound by this evaluation
177 cmRunStmt cmstate dflags expr
179 let InteractiveContext {
181 ic_type_env = type_env,
182 ic_module = this_mod } = icontext
184 (new_pcs, maybe_stuff)
185 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
188 Nothing -> return (cmstate{ pcs=new_pcs }, [])
189 Just (ids, _, bcos) -> do
191 -- update the interactive context
193 names = map idName ids
195 -- these names have just been shadowed
196 shadowed = [ n | r <- map nameRdrName names,
197 Just n <- [lookupRdrEnv rn_env r] ]
199 new_rn_env = extendLocalRdrEnv rn_env names
201 -- remove any shadowed bindings from the type_env
202 filtered_type_env = delListFromNameEnv type_env shadowed
204 new_type_env = extendNameEnvList filtered_type_env
205 [ (getName id, AnId id) | id <- ids]
207 new_ic = icontext { ic_rn_env = new_rn_env,
208 ic_type_env = new_type_env }
211 hval <- linkExpr pls bcos
214 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
215 hvals <- thing_to_run
217 -- Get the newly bound things, and bind them. Don't forget
218 -- to delete any shadowed bindings from the closure_env, lest
219 -- we end up with a space leak.
220 pls <- delListFromClosureEnv pls shadowed
221 new_pls <- addListToClosureEnv pls (zip names hvals)
223 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic }, names)
225 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
228 -----------------------------------------------------------------------------
229 -- cmTypeOfExpr: returns a string representing the type of an expression
232 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
233 cmTypeOfExpr cmstate dflags expr
234 = do (new_pcs, maybe_stuff)
235 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
237 let new_cmstate = cmstate{pcs = new_pcs}
240 Nothing -> return (new_cmstate, Nothing)
242 let pit = pcs_PIT pcs
243 modname = moduleName (ic_module ic)
244 tidy_ty = tidyType emptyTidyEnv ty
245 str = case lookupIfaceByModName hit pit modname of
246 Nothing -> showSDoc (ppr tidy_ty)
247 Just iface -> showSDocForUser unqual (ppr tidy_ty)
248 where unqual = unQualInScope (mi_globals iface)
249 in return (new_cmstate, Just str)
251 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
254 -----------------------------------------------------------------------------
255 -- cmTypeOfName: returns a string representing the type of a name.
258 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
259 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
260 = case lookupNameEnv (ic_type_env ic) name of
261 Nothing -> return Nothing
263 let pit = pcs_PIT pcs
264 modname = moduleName (ic_module ic)
265 ty = tidyType emptyTidyEnv (idType id)
266 str = case lookupIfaceByModName hit pit modname of
267 Nothing -> showSDoc (ppr ty)
268 Just iface -> showSDocForUser unqual (ppr ty)
269 where unqual = unQualInScope (mi_globals iface)
272 _ -> panic "cmTypeOfName"
275 -----------------------------------------------------------------------------
276 -- cmCompileExpr: compile an expression and deliver an HValue
279 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
280 cmCompileExpr cmstate dflags expr
282 let InteractiveContext {
284 ic_type_env = type_env,
285 ic_module = this_mod } = icontext
287 (new_pcs, maybe_stuff)
288 <- hscStmt dflags hst hit pcs icontext
289 ("let __cmCompileExpr = "++expr) False{-stmt-}
292 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
293 Just (ids, _, bcos) -> do
296 hval <- linkExpr pls bcos
299 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
300 hvals <- thing_to_run
303 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
304 _ -> panic "cmCompileExpr"
307 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
310 -----------------------------------------------------------------------------
311 -- cmInfo: return "info" about an expression. The info might be:
313 -- * its type, for an expression,
314 -- * the class definition, for a class
315 -- * the datatype definition, for a tycon (or synonym)
316 -- * the export list, for a module
318 -- Can be used to find the type of the last expression compiled, by looking
321 cmInfo :: CmState -> String -> IO (Maybe String)
323 = do error "cmInfo not implemented yet"
325 -----------------------------------------------------------------------------
326 -- Unload the compilation manager's state: everything it knows about the
327 -- current collection of modules in the Home package.
329 cmUnload :: CmState -> DynFlags -> IO CmState
330 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
331 = do -- Throw away the old home dir cache
334 -- Unload everything the linker knows about
335 new_pls <- CmLink.unload mode dflags [] pls
337 -- Start with a fresh CmState, but keep the PersistentCompilerState
338 new_state <- cmInit mode
339 return new_state{ pcs=pcs, pls=new_pls }
341 -----------------------------------------------------------------------------
342 -- The real business of the compilation manager: given a system state and
343 -- a module name, try and bring the module up to date, probably changing
344 -- the system state at the same time.
346 cmLoadModule :: CmState
348 -> IO (CmState, -- new state
349 Bool, -- was successful
350 [String]) -- list of modules loaded
352 cmLoadModule cmstate1 rootname
353 = do -- version 1's are the original, before downsweep
354 let pls1 = pls cmstate1
355 let pcs1 = pcs cmstate1
356 let hst1 = hst cmstate1
357 let hit1 = hit cmstate1
358 -- similarly, ui1 is the (complete) set of linkables from
359 -- the previous pass, if any.
360 let ui1 = ui cmstate1
361 let mg1 = mg cmstate1
362 let ic1 = ic cmstate1
364 let ghci_mode = gmode cmstate1 -- this never changes
366 -- Do the downsweep to reestablish the module graph
367 dflags <- getDynFlags
368 let verb = verbosity dflags
370 showPass dflags "Chasing dependencies"
371 when (verb >= 1 && ghci_mode == Batch) $
372 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
374 (mg2unsorted, a_root_is_Main) <- downsweep [rootname] mg1
375 let mg2unsorted_names = map name_of_summary mg2unsorted
377 -- reachable_from follows source as well as normal imports
378 let reachable_from :: ModuleName -> [ModuleName]
379 reachable_from = downwards_closure_of_module mg2unsorted
381 -- should be cycle free; ignores 'import source's
382 let mg2 = topological_sort False mg2unsorted
383 -- ... whereas this takes them into account. Used for
384 -- backing out partially complete cycles following a failed
385 -- upsweep, and for removing from hst/hit all the modules
386 -- not in strict downwards closure, during calls to compile.
387 let mg2_with_srcimps = topological_sort True mg2unsorted
389 -- Sort out which linkables we wish to keep in the unlinked image.
390 -- See getValidLinkables below for details.
391 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
394 -- Figure out a stable set of modules which can be retained
395 -- the top level envs, to avoid upsweeping them. Goes to a
396 -- bit of trouble to avoid upsweeping module cycles.
398 -- Construct a set S of stable modules like this:
399 -- Travel upwards, over the sccified graph. For each scc
400 -- of modules ms, add ms to S only if:
401 -- 1. All home imports of ms are either in ms or S
402 -- 2. A valid linkable exists for each module in ms
404 stable_mods <- preUpsweep valid_linkables hit1
405 mg2unsorted_names [] mg2_with_srcimps
408 = concatMap (findInSummaries mg2unsorted) stable_mods
411 = filter (\m -> linkableModName m `elem` stable_mods)
415 putStrLn (showSDoc (text "Stable modules:"
416 <+> sep (map (text.moduleNameUserString) stable_mods)))
418 -- unload any modules which aren't going to be re-linked this
420 pls2 <- unload ghci_mode dflags stable_linkables pls1
422 -- We could at this point detect cycles which aren't broken by
423 -- a source-import, and complain immediately, but it seems better
424 -- to let upsweep_mods do this, so at least some useful work gets
425 -- done before the upsweep is abandoned.
427 = filter (\scc -> any (`notElem` stable_mods)
428 (map name_of_summary (flattenSCC scc)))
431 --hPutStrLn stderr "after tsort:\n"
432 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
434 -- Because we don't take into account source imports when doing
435 -- the topological sort, there shouldn't be any cycles in mg2.
436 -- If there is, we complain and give up -- the user needs to
437 -- break the cycle using a boot file.
439 -- Now do the upsweep, calling compile for each module in
440 -- turn. Final result is version 3 of everything.
442 let threaded2 = CmThreaded pcs1 hst1 hit1
444 (upsweep_complete_success, threaded3, modsUpswept, newLis)
445 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
446 threaded2 upsweep_these
448 let ui3 = add_to_ui valid_linkables newLis
449 let (CmThreaded pcs3 hst3 hit3) = threaded3
451 -- At this point, modsUpswept and newLis should have the same
452 -- length, so there is one new (or old) linkable for each
453 -- mod which was processed (passed to compile).
455 -- Make modsDone be the summaries for each home module now
456 -- available; this should equal the domains of hst3 and hit3.
457 -- (NOT STRICTLY TRUE if an interactive session was started
458 -- with some object on disk ???)
459 -- Get in in a roughly top .. bottom order (hence reverse).
461 let modsDone = reverse modsUpswept ++ stable_summaries
463 -- Try and do linking in some form, depending on whether the
464 -- upsweep was completely or only partially successful.
466 if upsweep_complete_success
469 -- Easy; just relink it all.
470 do when (verb >= 2) $
471 hPutStrLn stderr "Upsweep completely successful."
473 -- clean up after ourselves
474 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
476 -- link everything together
477 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
479 cmLoadFinish True linkresult
480 hst3 hit3 ui3 modsDone ghci_mode pcs3
483 -- Tricky. We need to back out the effects of compiling any
484 -- half-done cycles, both so as to clean up the top level envs
485 -- and to avoid telling the interactive linker to link them.
486 do when (verb >= 2) $
487 hPutStrLn stderr "Upsweep partially successful."
490 = map name_of_summary modsDone
491 let mods_to_zap_names
492 = findPartiallyCompletedCycles modsDone_names
494 let (hst4, hit4, ui4)
495 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
498 = filter ((`notElem` mods_to_zap_names).name_of_summary)
501 -- clean up after ourselves
502 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
504 -- link everything together
505 linkresult <- link ghci_mode dflags False ui4 pls2
507 cmLoadFinish False linkresult
508 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
511 -- Finish up after a cmLoad.
513 -- Empty the interactive context and set the module context to the topmost
514 -- newly loaded module, or the Prelude if none were loaded.
515 cmLoadFinish ok linkresult hst hit ui mods ghci_mode pcs
516 = do case linkresult of {
517 LinkErrs _ _ -> panic "cmLoadModule: link failed (2)";
520 def_mod <- readIORef defaultCurrentModule
521 let current_mod = case mods of
525 new_ic = emptyInteractiveContext current_mod
527 new_cmstate = CmState{ hst=hst, hit=hit,
529 gmode=ghci_mode, pcs=pcs,
532 mods_loaded = map (moduleNameUserString.name_of_summary) mods
534 return (new_cmstate, ok, mods_loaded)
537 ppFilesFromSummaries summaries
538 = [ fn | Just fn <- map (ml_hspp_file . ms_location) summaries ]
540 -----------------------------------------------------------------------------
543 -- For each module (or SCC of modules), we take:
545 -- - an on-disk linkable, if this is the first time around and one
548 -- - the old linkable, otherwise (and if one is available).
550 -- and we throw away the linkable if it is older than the source
551 -- file. We ignore the on-disk linkables unless all of the dependents
552 -- of this SCC also have on-disk linkables.
554 -- If a module has a valid linkable, then it may be STABLE (see below),
555 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
558 -- ToDo: this pass could be merged with the preUpsweep.
561 :: [Linkable] -- old linkables
562 -> [ModuleName] -- all home modules
563 -> [SCC ModSummary] -- all modules in the program, dependency order
564 -> IO [Linkable] -- still-valid linkables
566 getValidLinkables old_linkables all_home_mods module_graph
567 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
569 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
571 scc = flattenSCC scc0
572 scc_names = map name_of_summary scc
573 home_module m = m `elem` all_home_mods && m `notElem` scc_names
574 scc_allhomeimps = nub (filter home_module (concatMap ms_allimps scc))
576 has_object m = case findModuleLinkable_maybe new_linkables m of
578 Just l -> isObjectLinkable l
580 objects_allowed = all has_object scc_allhomeimps
584 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
586 -- since an scc can contain only all objects or no objects at all,
587 -- we have to check whether we got all objects or not, and re-do
588 -- the linkable check if not.
590 <- if objects_allowed && not (all isObjectLinkable these_linkables)
591 then foldM (getValidLinkable old_linkables False) [] scc
592 else return these_linkables
594 return (adjusted_linkables ++ new_linkables)
597 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
599 getValidLinkable old_linkables objects_allowed new_linkables summary
600 = do let mod_name = name_of_summary summary
603 <- if (not objects_allowed)
605 else case ml_obj_file (ms_location summary) of
606 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
607 Nothing -> return Nothing
609 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
612 Just l | not (isObjectLinkable l) || stillThere l
614 -- ToDo: emit a warning if not (stillThere l)
617 -- make sure that if we had an old disk linkable around, that it's
618 -- still there on the disk (in case we need to re-link it).
620 case maybe_disk_linkable of
622 Just l_disk -> linkableTime l == linkableTime l_disk
624 -- we only look for objects on disk the first time around;
625 -- if the user compiles a module on the side during a GHCi session,
626 -- it won't be picked up until the next ":load". This is what the
627 -- "null old_linkables" test below is.
628 linkable | null old_linkables = maybeToList maybe_disk_linkable
629 | otherwise = maybeToList maybe_old_linkable
631 -- only linkables newer than the source code are valid
632 src_date = ms_hs_date summary
635 = filter (\l -> linkableTime l > src_date) linkable
637 return (valid_linkable ++ new_linkables)
641 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
642 maybe_getFileLinkable mod_name obj_fn
643 = do obj_exist <- doesFileExist obj_fn
647 do let stub_fn = case splitFilename3 obj_fn of
648 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
649 stub_exist <- doesFileExist stub_fn
650 obj_time <- getModificationTime obj_fn
652 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
653 else return (Just (LM obj_time mod_name [DotO obj_fn]))
656 -----------------------------------------------------------------------------
657 -- Do a pre-upsweep without use of "compile", to establish a
658 -- (downward-closed) set of stable modules for which we won't call compile.
661 -- * has a valid linkable (see getValidLinkables above)
662 -- * depends only on stable modules
663 -- * has an interface in the HIT (interactive mode only)
665 preUpsweep :: [Linkable] -- new valid linkables
667 -> [ModuleName] -- names of all mods encountered in downsweep
668 -> [ModuleName] -- accumulating stable modules
669 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
670 -> IO [ModuleName] -- stable modules
672 preUpsweep valid_lis hit all_home_mods stable [] = return stable
673 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
674 = do let scc = flattenSCC scc0
675 scc_allhomeimps :: [ModuleName]
677 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
678 all_imports_in_scc_or_stable
679 = all in_stable_or_scc scc_allhomeimps
681 = map name_of_summary scc
683 = m `elem` scc_names || m `elem` stable
685 -- now we check for valid linkables: each module in the SCC must
686 -- have a valid linkable (see getValidLinkables above).
687 has_valid_linkable new_summary
688 = isJust (findModuleLinkable_maybe valid_lis modname)
689 where modname = name_of_summary new_summary
691 has_interface summary = ms_mod summary `elemUFM` hit
693 scc_is_stable = all_imports_in_scc_or_stable
694 && all has_valid_linkable scc
695 && all has_interface scc
698 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
699 else preUpsweep valid_lis hit all_home_mods stable sccs
702 -- Helper for preUpsweep. Assuming that new_summary's imports are all
703 -- stable (in the sense of preUpsweep), determine if new_summary is itself
704 -- stable, and, if so, in batch mode, return its linkable.
705 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
706 findInSummaries old_summaries mod_name
707 = [s | s <- old_summaries, name_of_summary s == mod_name]
709 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
710 findModInSummaries old_summaries mod
711 = case [s | s <- old_summaries, ms_mod s == mod] of
715 -- Return (names of) all those in modsDone who are part of a cycle
716 -- as defined by theGraph.
717 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
718 findPartiallyCompletedCycles modsDone theGraph
722 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
723 chew ((CyclicSCC vs):rest)
724 = let names_in_this_cycle = nub (map name_of_summary vs)
726 = nub ([done | done <- modsDone,
727 done `elem` names_in_this_cycle])
728 chewed_rest = chew rest
730 if not (null mods_in_this_cycle)
731 && length mods_in_this_cycle < length names_in_this_cycle
732 then mods_in_this_cycle ++ chewed_rest
736 -- Add the given (LM-form) Linkables to the UI, overwriting previous
737 -- versions if they exist.
738 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
740 = filter (not_in lis) ui ++ lis
742 not_in :: [Linkable] -> Linkable -> Bool
744 = all (\l -> linkableModName l /= mod) lis
745 where mod = linkableModName li
748 data CmThreaded -- stuff threaded through individual module compilations
749 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
752 -- Compile multiple modules, stopping as soon as an error appears.
753 -- There better had not be any cyclic groups here -- we check for them.
754 upsweep_mods :: GhciMode
756 -> UnlinkedImage -- valid linkables
757 -> (ModuleName -> [ModuleName]) -- to construct downward closures
758 -> CmThreaded -- PCS & HST & HIT
759 -> [SCC ModSummary] -- mods to do (the worklist)
760 -- ...... RETURNING ......
761 -> IO (Bool{-complete success?-},
763 [ModSummary], -- mods which succeeded
764 [Linkable]) -- new linkables
766 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
768 = return (True, threaded, [], [])
770 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
772 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
773 unwords (map (moduleNameUserString.name_of_summary) ms))
774 return (False, threaded, [], [])
776 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
777 ((AcyclicSCC mod):mods)
778 = do --case threaded of
779 -- CmThreaded pcsz hstz hitz
780 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
782 (threaded1, maybe_linkable)
783 <- upsweep_mod ghci_mode dflags oldUI threaded mod
784 (reachable_from (name_of_summary mod))
785 case maybe_linkable of
787 -> -- No errors; do the rest
788 do (restOK, threaded2, modOKs, linkables)
789 <- upsweep_mods ghci_mode dflags oldUI reachable_from
791 return (restOK, threaded2, mod:modOKs, linkable:linkables)
792 Nothing -- we got a compilation error; give up now
793 -> return (False, threaded1, [], [])
796 -- Compile a single module. Always produce a Linkable for it if
797 -- successful. If no compilation happened, return the old Linkable.
798 upsweep_mod :: GhciMode
804 -> IO (CmThreaded, Maybe Linkable)
806 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
808 let mod_name = name_of_summary summary1
809 let verb = verbosity dflags
811 let (CmThreaded pcs1 hst1 hit1) = threaded1
812 let old_iface = lookupUFM hit1 mod_name
814 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
816 source_unchanged = isJust maybe_old_linkable
818 reachable_only = filter (/= (name_of_summary summary1))
821 -- in interactive mode, all home modules below us *must* have an
822 -- interface in the HIT. We never demand-load home interfaces in
824 (hst1_strictDC, hit1_strictDC)
825 = ASSERT(ghci_mode == Batch ||
826 all (`elemUFM` hit1) reachable_only)
827 retainInTopLevelEnvs reachable_only (hst1,hit1)
830 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
833 | Just l <- maybe_old_linkable, isObjectLinkable l = True
836 compresult <- compile ghci_mode summary1 source_unchanged
837 have_object old_iface hst1_strictDC hit1_strictDC pcs1
841 -- Compilation "succeeded", and may or may not have returned a new
842 -- linkable (depending on whether compilation was actually performed
844 CompOK pcs2 new_details new_iface maybe_new_linkable
845 -> do let hst2 = addToUFM hst1 mod_name new_details
846 hit2 = addToUFM hit1 mod_name new_iface
847 threaded2 = CmThreaded pcs2 hst2 hit2
849 return (threaded2, if isJust maybe_new_linkable
850 then maybe_new_linkable
851 else Just old_linkable)
853 -- Compilation failed. compile may still have updated
856 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
857 return (threaded2, Nothing)
859 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
860 removeFromTopLevelEnvs :: [ModuleName]
861 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
862 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
863 removeFromTopLevelEnvs zap_these (hst, hit, ui)
864 = (delListFromUFM hst zap_these,
865 delListFromUFM hit zap_these,
866 filterModuleLinkables (`notElem` zap_these) ui
869 retainInTopLevelEnvs :: [ModuleName]
870 -> (HomeSymbolTable, HomeIfaceTable)
871 -> (HomeSymbolTable, HomeIfaceTable)
872 retainInTopLevelEnvs keep_these (hst, hit)
873 = (retainInUFM hst keep_these,
874 retainInUFM hit keep_these
877 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
878 retainInUFM ufm keys_to_keep
879 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
881 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
883 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
884 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
885 downwards_closure_of_module summaries root
886 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
887 toEdge summ = (name_of_summary summ,
888 filter (`elem` all_mods) (ms_allimps summ))
890 all_mods = map name_of_summary summaries
892 res = simple_transitive_closure (map toEdge summaries) [root]
894 --trace (showSDoc (text "DC of mod" <+> ppr root
895 -- <+> text "=" <+> ppr res)) (
899 -- Calculate transitive closures from a set of roots given an adjacency list
900 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
901 simple_transitive_closure graph set
902 = let set2 = nub (concatMap dsts set ++ set)
903 dsts node = fromMaybe [] (lookup node graph)
905 if length set == length set2
907 else simple_transitive_closure graph set2
910 -- Calculate SCCs of the module graph, with or without taking into
911 -- account source imports.
912 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
913 topological_sort include_source_imports summaries
915 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
917 = (summ, name_of_summary summ,
918 (if include_source_imports
919 then ms_srcimps summ else []) ++ ms_imps summ)
921 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
922 mash_edge (summ, m, m_imports)
923 = case lookup m key_map of
924 Nothing -> panic "reverse_topological_sort"
925 Just mk -> (summ, mk,
926 -- ignore imports not from the home package
927 catMaybes (map (flip lookup key_map) m_imports))
929 edges = map toEdge summaries
930 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
931 scc_input = map mash_edge edges
932 sccs = stronglyConnComp scc_input
937 -- Chase downwards from the specified root set, returning summaries
938 -- for all home modules encountered. Only follow source-import
939 -- links. Also returns a Bool to indicate whether any of the roots
941 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
942 downsweep rootNm old_summaries
943 = do rootSummaries <- mapM getRootSummary rootNm
945 = any ((=="Main").moduleNameUserString.name_of_summary)
948 <- loop (concat (map ms_imps rootSummaries))
949 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
950 let mod = ms_mod s, isHomeModule mod
952 return (all_summaries, a_root_is_Main)
954 getRootSummary :: FilePath -> IO ModSummary
956 | haskellish_src_file file
957 = do exists <- doesFileExist file
958 if exists then summariseFile file else do
959 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
961 = do exists <- doesFileExist hs_file
962 if exists then summariseFile hs_file else do
963 exists <- doesFileExist lhs_file
964 if exists then summariseFile lhs_file else do
965 let mod_name = mkModuleName file
966 maybe_summary <- getSummary mod_name
967 case maybe_summary of
968 Nothing -> packageModErr mod_name
971 hs_file = file ++ ".hs"
972 lhs_file = file ++ ".lhs"
974 getSummary :: ModuleName -> IO (Maybe ModSummary)
976 = do found <- findModule nm
978 Just (mod, location) -> do
979 let old_summary = findModInSummaries old_summaries mod
980 summarise mod location old_summary
982 Nothing -> throwDyn (CmdLineError
983 ("can't find module `"
984 ++ showSDoc (ppr nm) ++ "'"))
986 -- loop invariant: env doesn't contain package modules
987 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
988 loop [] env = return (moduleEnvElts env)
990 = do -- imports for modules we don't already have
991 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
994 needed_summaries <- mapM getSummary needed_imps
996 -- get just the "home" modules
997 let new_home_summaries = [ s | Just s <- needed_summaries ]
999 -- loop, checking the new imports
1000 let new_imps = concat (map ms_imps new_home_summaries)
1001 loop new_imps (extendModuleEnvList env
1002 [ (ms_mod s, s) | s <- new_home_summaries ])
1004 -----------------------------------------------------------------------------
1005 -- Summarising modules
1007 -- We have two types of summarisation:
1009 -- * Summarise a file. This is used for the root module passed to
1010 -- cmLoadModule. The file is read, and used to determine the root
1011 -- module name. The module name may differ from the filename.
1013 -- * Summarise a module. We are given a module name, and must provide
1014 -- a summary. The finder is used to locate the file in which the module
1017 summariseFile :: FilePath -> IO ModSummary
1019 = do hspp_fn <- preprocess file
1020 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1022 let (path, basename, ext) = splitFilename3 file
1024 Just (mod, location)
1025 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1028 <- case ml_hs_file location of
1029 Nothing -> noHsFileErr mod_name
1030 Just src_fn -> getModificationTime src_fn
1032 return (ModSummary mod
1033 location{ml_hspp_file=Just hspp_fn}
1034 srcimps imps src_timestamp)
1036 -- Summarise a module, and pick up source and timestamp.
1037 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1038 -> IO (Maybe ModSummary)
1039 summarise mod location old_summary
1041 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1044 <- case ml_hs_file location of
1045 Nothing -> noHsFileErr mod
1046 Just src_fn -> getModificationTime src_fn
1048 -- return the cached summary if the source didn't change
1049 case old_summary of {
1050 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1053 hspp_fn <- preprocess hs_fn
1054 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1056 when (mod_name /= moduleName mod) $
1057 throwDyn (ProgramError
1058 (showSDoc (text hs_fn
1059 <> text ": file name does not match module name"
1060 <+> quotes (ppr (moduleName mod)))))
1062 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1063 srcimps imps src_timestamp))
1066 | otherwise = return Nothing
1069 = panic (showSDoc (text "no source file for module" <+> quotes (ppr mod)))
1072 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1073 quotes (ppr mod) <+>
1074 text "is a package module")))