2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 module CompManager ( cmInit, cmLoadModule,
9 CmState, emptyCmState -- abstract
13 #include "HsVersions.h"
16 import Maybe ( catMaybes, maybeToList, fromMaybe )
17 import Maybes ( maybeToBool )
19 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM )
20 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
22 import CmLink ( PersistentLinkerState, emptyPLS, Linkable(..),
24 filterModuleLinkables, modname_of_linkable,
25 is_package_linkable, findModuleLinkable )
28 import Interpreter ( HValue )
29 import Module ( ModuleName, moduleName, packageOfModule,
30 isModuleInThisPackage, PackageName, moduleEnvElts,
31 moduleNameUserString )
32 import CmStaticInfo ( Package(..), PackageConfigInfo, GhciMode )
35 import HscTypes ( HomeSymbolTable, HomeIfaceTable,
36 PersistentCompilerState, ModDetails(..) )
37 import Name ( lookupNameEnv )
39 import PrelNames ( mainName )
40 import HscMain ( initPersistentCompilerState )
41 import Finder ( findModule, emptyHomeDirCache )
42 import DriverUtil ( BarfKind(..) )
44 import Panic ( panic )
46 import Exception ( throwDyn )
48 import Time ( ClockTime )
49 import Directory ( getModificationTime )
56 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
57 cmInit raw_package_info gmode
58 = emptyCmState raw_package_info gmode
63 -> IO (CmState, Either [SDoc] HValue)
64 cmGetExpr cmstate modhdl expr
65 = return (panic "cmGetExpr:unimp")
67 cmRunExpr :: HValue -> IO ()
69 = return (panic "cmRunExpr:unimp")
72 -- Persistent state just for CM, excluding link & compile subsystems
73 data PersistentCMState
75 hst :: HomeSymbolTable, -- home symbol table
76 hit :: HomeIfaceTable, -- home interface table
77 ui :: UnlinkedImage, -- the unlinked images
78 mg :: ModuleGraph, -- the module graph
79 pci :: PackageConfigInfo, -- NEVER CHANGES
80 gmode :: GhciMode -- NEVER CHANGES
83 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
85 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
86 ui = emptyUI, mg = emptyMG,
87 pci = pci, gmode = gmode }
89 emptyHIT :: HomeIfaceTable
91 emptyHST :: HomeSymbolTable
96 -- Persistent state for the entire system
99 pcms :: PersistentCMState, -- CM's persistent state
100 pcs :: PersistentCompilerState, -- compile's persistent state
101 pls :: PersistentLinkerState -- link's persistent state
104 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
105 emptyCmState pci gmode
106 = do let pcms = emptyPCMS pci gmode
107 pcs <- initPersistentCompilerState
109 return (CmState { pcms = pcms,
114 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
115 emptyUI :: UnlinkedImage
118 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
119 emptyMG :: ModuleGraph
124 The real business of the compilation manager: given a system state and
125 a module name, try and bring the module up to date, probably changing
126 the system state at the same time.
129 cmLoadModule :: CmState
131 -> IO (CmState, Maybe ModuleName)
133 cmLoadModule cmstate1 rootname
134 = do -- version 1's are the original, before downsweep
135 let pcms1 = pcms cmstate1
136 let pls1 = pls cmstate1
137 let pcs1 = pcs cmstate1
143 let pcii = pci pcms1 -- this never changes
144 let ghci_mode = gmode pcms1 -- ToDo: fix!
146 -- During upsweep, look at new summaries to see if source has
147 -- changed. Here's a function to pass down; it takes a new
149 let source_changed :: ModSummary -> Bool
150 source_changed = summary_indicates_source_changed mg1
152 -- Do the downsweep to reestablish the module graph
153 -- then generate version 2's by removing from HIT,HST,UI any
154 -- modules in the old MG which are not in the new one.
156 -- Throw away the old home dir cache
159 hPutStr stderr "cmLoadModule: downsweep begins\n"
160 mg2unsorted <- downsweep [rootname]
162 let modnames1 = map name_of_summary mg1
163 let modnames2 = map name_of_summary mg2unsorted
164 let mods_to_zap = filter (`notElem` modnames2) modnames1
166 let (hst2, hit2, ui2)
167 = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
168 -- should be cycle free; ignores 'import source's
169 let mg2 = topological_sort False mg2unsorted
170 -- ... whereas this takes them into account. Only used for
171 -- backing out partially complete cycles following a failed
173 let mg2_with_srcimps = topological_sort True mg2unsorted
175 hPutStrLn stderr "after tsort:\n"
176 hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
178 -- Because we don't take into account source imports when doing
179 -- the topological sort, there shouldn't be any cycles in mg2.
180 -- If there is, we complain and give up -- the user needs to
181 -- break the cycle using a boot file.
183 -- Now do the upsweep, calling compile for each module in
184 -- turn. Final result is version 3 of everything.
186 let threaded2 = CmThreaded pcs1 hst2 hit2
188 (upsweep_complete_success, threaded3, modsDone, newLis)
189 <- upsweep_mods ghci_mode ui2 source_changed threaded2 mg2
191 let ui3 = add_to_ui ui2 newLis
192 let (CmThreaded pcs3 hst3 hit3) = threaded3
194 -- At this point, modsDone and newLis should have the same
195 -- length, so there is one new (or old) linkable for each
196 -- mod which was processed (passed to compile).
198 -- Try and do linking in some form, depending on whether the
199 -- upsweep was completely or only partially successful.
201 if upsweep_complete_success
204 -- Easy; just relink it all.
205 do hPutStrLn stderr "UPSWEEP COMPLETELY SUCCESSFUL"
207 <- link ghci_mode (any exports_main (moduleEnvElts hst3))
211 -> panic "cmLoadModule: link failed (1)"
213 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
215 pci=pcii, gmode=ghci_mode }
217 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
218 return (cmstate3, Just rootname)
221 -- Tricky. We need to back out the effects of compiling any
222 -- half-done cycles, both so as to clean up the top level envs
223 -- and to avoid telling the interactive linker to link them.
224 do hPutStrLn stderr "UPSWEEP PARTIALLY SUCCESSFUL"
227 = map name_of_summary modsDone
228 let mods_to_zap_names
229 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
230 let (hst4, hit4, ui4)
231 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
233 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
234 let mods_to_keep_names
235 = map name_of_summary mods_to_keep
236 -- we could get the relevant linkables by filtering newLis, but
237 -- it seems easier to drag them out of the updated, cleaned-up UI
238 let linkables_to_link
239 = map (findModuleLinkable ui4) mods_to_keep_names
241 linkresult <- link ghci_mode False linkables_to_link pls1
244 -> panic "cmLoadModule: link failed (2)"
246 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
247 ui=ui4, mg=mods_to_keep,
248 pci=pcii, gmode=ghci_mode }
250 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
252 -- choose rather arbitrarily who to return
253 if null mods_to_keep then Nothing
254 else Just (last mods_to_keep_names))
257 -- Given a bunch of old summaries and a new summary, try and
258 -- find the corresponding old summary, and, if found, compare
259 -- its source timestamp with that of the new summary. If in
261 summary_indicates_source_changed :: [ModSummary] -> ModSummary -> Bool
262 summary_indicates_source_changed old_summaries new_summary
263 = case [old | old <- old_summaries,
264 name_of_summary old == name_of_summary new_summary] of
266 (_:_:_) -> panic "summary_indicates_newer_source"
268 [] -> -- can't find a corresponding old summary, so
269 -- compare source and iface dates in the new summary.
270 trace (showSDoc (text "SISC: no old summary, new ="
271 <+> pprSummaryTimes new_summary)) (
272 case (ms_hs_date new_summary, ms_hi_date new_summary) of
273 (Just hs_t, Just hi_t) -> hs_t > hi_t
277 [old] -> -- found old summary; compare source timestamps
278 trace (showSDoc (text "SISC: old ="
279 <+> pprSummaryTimes old
280 <+> pprSummaryTimes new_summary)) (
281 case (ms_hs_date old, ms_hs_date new_summary) of
282 (Just old_t, Just new_t) -> new_t > old_t
286 -- Return (names of) all those in modsDone who are part of a cycle
287 -- as defined by theGraph.
288 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
289 findPartiallyCompletedCycles modsDone theGraph
293 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
294 chew ((CyclicSCC vs):rest)
295 = let names_in_this_cycle = nub (map name_of_summary vs)
297 = nub ([done | done <- modsDone,
298 done `elem` names_in_this_cycle])
299 chewed_rest = chew rest
301 if not (null mods_in_this_cycle)
302 && length mods_in_this_cycle < length names_in_this_cycle
303 then mods_in_this_cycle ++ chewed_rest
307 -- Does this ModDetails export Main.main?
308 exports_main :: ModDetails -> Bool
310 = maybeToBool (lookupNameEnv (md_types md) mainName)
313 -- Add the given (LM-form) Linkables to the UI, overwriting previous
314 -- versions if they exist.
315 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
319 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
321 = li : filter (\li2 -> not (for_same_module li li2)) ui
323 for_same_module :: Linkable -> Linkable -> Bool
324 for_same_module li1 li2
325 = not (is_package_linkable li1)
326 && not (is_package_linkable li2)
327 && modname_of_linkable li1 == modname_of_linkable li2
330 data CmThreaded -- stuff threaded through individual module compilations
331 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
334 -- Compile multiple modules, stopping as soon as an error appears.
335 -- There better had not be any cyclic groups here -- we check for them.
336 upsweep_mods :: GhciMode
337 -> UnlinkedImage -- old linkables
338 -> (ModSummary -> Bool) -- has source changed?
339 -> CmThreaded -- PCS & HST & HIT
340 -> [SCC ModSummary] -- mods to do (the worklist)
341 -- ...... RETURNING ......
342 -> IO (Bool{-complete success?-},
344 [ModSummary], -- mods which succeeded
345 [Linkable]) -- new linkables
347 upsweep_mods ghci_mode oldUI source_changed threaded []
348 = return (True, threaded, [], [])
350 upsweep_mods ghci_mode oldUI source_changed threaded ((CyclicSCC ms):_)
351 = do hPutStrLn stderr ("ghc: module imports form a cycle for modules:\n\t" ++
352 unwords (map (moduleNameUserString.name_of_summary) ms))
353 return (False, threaded, [], [])
355 upsweep_mods ghci_mode oldUI source_changed threaded ((AcyclicSCC mod):mods)
356 = do (threaded1, maybe_linkable)
357 <- upsweep_mod ghci_mode oldUI threaded mod (source_changed mod)
358 case maybe_linkable of
360 -> -- No errors; do the rest
361 do (restOK, threaded2, modOKs, linkables)
362 <- upsweep_mods ghci_mode oldUI source_changed threaded1 mods
363 return (restOK, threaded2, mod:modOKs, linkable:linkables)
364 Nothing -- we got a compilation error; give up now
365 -> return (False, threaded1, [], [])
368 -- Compile a single module. Always produce a Linkable for it if
369 -- successful. If no compilation happened, return the old Linkable.
370 upsweep_mod :: GhciMode
375 -> IO (CmThreaded, Maybe Linkable)
377 upsweep_mod ghci_mode oldUI threaded1 summary1 source_might_have_changed
378 = do let mod_name = name_of_summary summary1
379 let (CmThreaded pcs1 hst1 hit1) = threaded1
380 let old_iface = lookupUFM hit1 (name_of_summary summary1)
381 compresult <- compile ghci_mode summary1 (not source_might_have_changed)
382 old_iface hst1 hit1 pcs1
386 -- Compilation "succeeded", but didn't return a new iface or
387 -- linkable, meaning that compilation wasn't needed, and the
388 -- new details were manufactured from the old iface.
389 CompOK details Nothing pcs2
390 -> let hst2 = addToUFM hst1 mod_name details
392 threaded2 = CmThreaded pcs2 hst2 hit2
393 old_linkable = findModuleLinkable oldUI mod_name
394 in return (threaded2, Just old_linkable)
396 -- Compilation really did happen, and succeeded. A new
397 -- details, iface and linkable are returned.
398 CompOK details (Just (new_iface, new_linkable)) pcs2
399 -> let hst2 = addToUFM hst1 mod_name details
400 hit2 = addToUFM hit1 mod_name new_iface
401 threaded2 = CmThreaded pcs2 hst2 hit2
402 in return (threaded2, Just new_linkable)
404 -- Compilation failed. compile may still have updated
407 -> let threaded2 = CmThreaded pcs2 hst1 hit1
408 in return (threaded2, Nothing)
411 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
412 removeFromTopLevelEnvs :: [ModuleName]
413 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
414 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
415 removeFromTopLevelEnvs zap_these (hst, hit, ui)
416 = (delListFromUFM hst zap_these,
417 delListFromUFM hit zap_these,
418 filterModuleLinkables (`notElem` zap_these) ui
422 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
423 topological_sort include_source_imports summaries
425 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
427 = (summ, name_of_summary summ,
428 (if include_source_imports
429 then ms_srcimps summ else []) ++ ms_imps summ)
431 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
432 mash_edge (summ, m, m_imports)
433 = case lookup m key_map of
434 Nothing -> panic "reverse_topological_sort"
435 Just mk -> (summ, mk,
436 -- ignore imports not from the home package
437 catMaybes (map (flip lookup key_map) m_imports))
439 edges = map toEdge summaries
440 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
441 scc_input = map mash_edge edges
442 sccs = stronglyConnComp scc_input
447 -- Chase downwards from the specified root set, returning summaries
448 -- for all home modules encountered. Only follow source-import
450 downsweep :: [ModuleName] -> IO [ModSummary]
452 = do rootSummaries <- mapM getSummary rootNm
453 loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
455 getSummary :: ModuleName -> IO ModSummary
457 | trace ("getSummary: "++ showSDoc (ppr nm)) True
458 = do found <- findModule nm
460 Just (mod, location) -> summarise mod location
461 Nothing -> throwDyn (OtherError
462 ("no signs of life for module `"
463 ++ showSDoc (ppr nm) ++ "'"))
465 -- loop invariant: homeSummaries doesn't contain package modules
466 loop :: [ModSummary] -> IO [ModSummary]
468 = do let allImps :: [ModuleName]
469 allImps = (nub . concatMap ms_imps) homeSummaries
470 let allHome -- all modules currently in homeSummaries
471 = map (moduleName.ms_mod) homeSummaries
473 = filter (`notElem` allHome) allImps
475 <- mapM getSummary neededImps
477 = filter (isModuleInThisPackage.ms_mod) neededSummaries
478 if null newHomeSummaries
479 then return homeSummaries
480 else loop (newHomeSummaries ++ homeSummaries)
483 -- Summarise a module, and pick and source and interface timestamps.
484 summarise :: Module -> ModuleLocation -> IO ModSummary
485 summarise mod location
486 | isModuleInThisPackage mod
487 = do let hs_fn = unJust (ml_hs_file location) "summarise"
488 hspp_fn <- preprocess hs_fn
489 modsrc <- readFile hspp_fn
490 let (srcimps,imps) = getImports modsrc
493 <- case ml_hs_file location of
494 Nothing -> return Nothing
495 Just src_fn -> maybe_getModificationTime src_fn
496 maybe_iface_timestamp
497 <- case ml_hi_file location of
498 Nothing -> return Nothing
499 Just if_fn -> maybe_getModificationTime if_fn
501 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
503 maybe_src_timestamp maybe_iface_timestamp)
505 = return (ModSummary mod location [] [] Nothing Nothing)
508 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
509 maybe_getModificationTime fn
510 = (do time <- getModificationTime fn
513 (\err -> return Nothing)