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 )
21 import Panic ( panic )
23 import CmLink ( PersistentLinkerState, emptyPLS, Linkable(..),
25 filterModuleLinkables, modname_of_linkable,
26 is_package_linkable, findModuleLinkable )
27 import Interpreter ( HValue )
28 import CmSummarise ( summarise, ModSummary(..),
29 name_of_summary, {-, is_source_import-} )
30 import Module ( ModuleName, moduleName, packageOfModule,
31 isModuleInThisPackage, PackageName, moduleEnvElts,
32 moduleNameUserString )
33 import CmStaticInfo ( Package(..), PackageConfigInfo, GhciMode )
34 import DriverPipeline ( compile, preprocess, doLink, CompResult(..) )
35 import HscTypes ( HomeSymbolTable, HomeIfaceTable,
36 PersistentCompilerState, ModDetails(..) )
37 import Name ( lookupNameEnv )
38 import PrelNames ( mainName )
39 import HscMain ( initPersistentCompilerState )
40 import Finder ( findModule, emptyHomeDirCache )
41 import DriverUtil ( BarfKind(..) )
42 import Exception ( throwDyn )
43 import IO ( hPutStrLn, stderr )
49 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
50 cmInit raw_package_info gmode
51 = emptyCmState raw_package_info gmode
56 -> IO (CmState, Either [SDoc] HValue)
57 cmGetExpr cmstate modhdl expr
58 = return (panic "cmGetExpr:unimp")
60 cmRunExpr :: HValue -> IO ()
62 = return (panic "cmRunExpr:unimp")
65 -- Persistent state just for CM, excluding link & compile subsystems
66 data PersistentCMState
68 hst :: HomeSymbolTable, -- home symbol table
69 hit :: HomeIfaceTable, -- home interface table
70 ui :: UnlinkedImage, -- the unlinked images
71 mg :: ModuleGraph, -- the module graph
72 pci :: PackageConfigInfo, -- NEVER CHANGES
73 gmode :: GhciMode -- NEVER CHANGES
76 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
78 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
79 ui = emptyUI, mg = emptyMG,
80 pci = pci, gmode = gmode }
82 emptyHIT :: HomeIfaceTable
84 emptyHST :: HomeSymbolTable
89 -- Persistent state for the entire system
92 pcms :: PersistentCMState, -- CM's persistent state
93 pcs :: PersistentCompilerState, -- compile's persistent state
94 pls :: PersistentLinkerState -- link's persistent state
97 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
98 emptyCmState pci gmode
99 = do let pcms = emptyPCMS pci gmode
100 pcs <- initPersistentCompilerState
102 return (CmState { pcms = pcms,
107 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
108 emptyUI :: UnlinkedImage
111 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
112 emptyMG :: ModuleGraph
117 The real business of the compilation manager: given a system state and
118 a module name, try and bring the module up to date, probably changing
119 the system state at the same time.
122 cmLoadModule :: CmState
124 -> IO (CmState, Maybe ModuleName)
126 cmLoadModule cmstate1 rootname
127 = do -- version 1's are the original, before downsweep
128 let pcms1 = pcms cmstate1
129 let pls1 = pls cmstate1
130 let pcs1 = pcs cmstate1
136 let pcii = pci pcms1 -- this never changes
137 let ghci_mode = gmode pcms1 -- ToDo: fix!
139 -- Do the downsweep to reestablish the module graph
140 -- then generate version 2's by removing from HIT,HST,UI any
141 -- modules in the old MG which are not in the new one.
143 -- Throw away the old home dir cache
146 putStr "cmLoadModule: downsweep begins\n"
147 mg2unsorted <- downsweep [rootname]
149 let modnames1 = map name_of_summary mg1
150 let modnames2 = map name_of_summary mg2unsorted
151 let mods_to_zap = filter (`notElem` modnames2) modnames1
153 let (hst2, hit2, ui2)
154 = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
155 -- should be cycle free; ignores 'import source's
156 let mg2 = topological_sort False mg2unsorted
157 -- ... whereas this takes them into account. Only used for
158 -- backing out partially complete cycles following a failed
160 let mg2_with_srcimps = topological_sort True mg2unsorted
162 putStrLn "after tsort:\n"
163 putStrLn (showSDoc (vcat (map ppr mg2)))
165 -- Because we don't take into account source imports when doing
166 -- the topological sort, there shouldn't be any cycles in mg2.
167 -- If there is, we complain and give up -- the user needs to
168 -- break the cycle using a boot file.
170 -- Now do the upsweep, calling compile for each module in
171 -- turn. Final result is version 3 of everything.
173 let threaded2 = CmThreaded pcs1 hst2 hit2
175 (upsweep_complete_success, threaded3, modsDone, newLis)
176 <- upsweep_mods ui2 threaded2 mg2
178 let ui3 = add_to_ui ui2 newLis
179 let (CmThreaded pcs3 hst3 hit3) = threaded3
181 -- At this point, modsDone and newLis should have the same
182 -- length, so there is one new (or old) linkable for each
183 -- mod which was processed (passed to compile).
185 -- Try and do linking in some form, depending on whether the
186 -- upsweep was completely or only partially successful.
188 if upsweep_complete_success
191 -- Easy; just relink it all.
192 do putStrLn "UPSWEEP COMPLETELY SUCCESSFUL"
194 <- link doLink ghci_mode (any exports_main (moduleEnvElts hst3))
198 -> panic "cmLoadModule: link failed (1)"
200 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
202 pci=pcii, gmode=ghci_mode }
204 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
205 return (cmstate3, Just rootname)
208 -- Tricky. We need to back out the effects of compiling any
209 -- half-done cycles, both so as to clean up the top level envs
210 -- and to avoid telling the interactive linker to link them.
211 do putStrLn "UPSWEEP PARTIALLY SUCCESSFUL"
214 = map name_of_summary modsDone
215 let mods_to_zap_names
216 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
217 let (hst4, hit4, ui4)
218 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
220 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
221 let mods_to_keep_names
222 = map name_of_summary mods_to_keep
223 -- we could get the relevant linkables by filtering newLis, but
224 -- it seems easier to drag them out of the updated, cleaned-up UI
225 let linkables_to_link
226 = map (findModuleLinkable ui4) mods_to_keep_names
228 linkresult <- link doLink ghci_mode False linkables_to_link pls1
231 -> panic "cmLoadModule: link failed (2)"
233 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
234 ui=ui4, mg=mods_to_keep,
235 pci=pcii, gmode=ghci_mode }
237 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
239 -- choose rather arbitrarily who to return
240 if null mods_to_keep then Nothing
241 else Just (last mods_to_keep_names))
244 -- Return (names of) all those in modsDone who are part of a cycle
245 -- as defined by theGraph.
246 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
247 findPartiallyCompletedCycles modsDone theGraph
251 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
252 chew ((CyclicSCC vs):rest)
253 = let names_in_this_cycle = nub (map name_of_summary vs)
255 = nub ([done | done <- modsDone,
256 done `elem` names_in_this_cycle])
257 chewed_rest = chew rest
259 if not (null mods_in_this_cycle)
260 && length mods_in_this_cycle < length names_in_this_cycle
261 then mods_in_this_cycle ++ chewed_rest
265 exports_main :: ModDetails -> Bool
267 = maybeToBool (lookupNameEnv (md_types md) mainName)
270 -- Add the given (LM-form) Linkables to the UI, overwriting previous
271 -- versions if they exist.
272 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
276 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
278 = li : filter (\li2 -> not (for_same_module li li2)) ui
280 for_same_module :: Linkable -> Linkable -> Bool
281 for_same_module li1 li2
282 = not (is_package_linkable li1)
283 && not (is_package_linkable li2)
284 && modname_of_linkable li1 == modname_of_linkable li2
287 data CmThreaded -- stuff threaded through individual module compilations
288 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
291 -- Compile multiple modules, stopping as soon as an error appears.
292 -- There better had not be any cyclic groups here -- we check for them.
293 upsweep_mods :: UnlinkedImage -- old linkables
294 -> CmThreaded -- PCS & HST & HIT
295 -> [SCC ModSummary] -- mods to do (the worklist)
296 -- ...... RETURNING ......
297 -> IO (Bool{-complete success?-},
299 [ModSummary], -- mods which succeeded
300 [Linkable]) -- new linkables
302 upsweep_mods oldUI threaded []
303 = return (True, threaded, [], [])
305 upsweep_mods oldUI threaded ((CyclicSCC ms):_)
306 = do hPutStrLn stderr ("ghc: module imports form a cycle for modules:\n\t" ++
307 unwords (map (moduleNameUserString.name_of_summary) ms))
308 return (False, threaded, [], [])
310 upsweep_mods oldUI threaded ((AcyclicSCC mod):mods)
311 = do (threaded1, maybe_linkable) <- upsweep_mod oldUI threaded mod
312 case maybe_linkable of
314 -> -- No errors; do the rest
315 do (restOK, threaded2, modOKs, linkables)
316 <- upsweep_mods oldUI threaded1 mods
317 return (restOK, threaded2, mod:modOKs, linkable:linkables)
318 Nothing -- we got a compilation error; give up now
319 -> return (False, threaded1, [], [])
322 -- Compile a single module. Always produce a Linkable for it if
323 -- successful. If no compilation happened, return the old Linkable.
324 upsweep_mod :: UnlinkedImage
327 -> IO (CmThreaded, Maybe Linkable)
329 upsweep_mod oldUI threaded1 summary1
330 = do let mod_name = name_of_summary summary1
331 let (CmThreaded pcs1 hst1 hit1) = threaded1
332 let old_iface = lookupUFM hit1 (name_of_summary summary1)
333 compresult <- compile summary1 old_iface hst1 hit1 pcs1
337 -- Compilation "succeeded", but didn't return a new iface or
338 -- linkable, meaning that compilation wasn't needed, and the
339 -- new details were manufactured from the old iface.
340 CompOK details Nothing pcs2
341 -> let hst2 = addToUFM hst1 mod_name details
343 threaded2 = CmThreaded pcs2 hst2 hit2
344 old_linkable = findModuleLinkable oldUI mod_name
345 in return (threaded2, Just old_linkable)
347 -- Compilation really did happen, and succeeded. A new
348 -- details, iface and linkable are returned.
349 CompOK details (Just (new_iface, new_linkable)) pcs2
350 -> let hst2 = addToUFM hst1 mod_name details
351 hit2 = addToUFM hit1 mod_name new_iface
352 threaded2 = CmThreaded pcs2 hst2 hit2
353 in return (threaded2, Just new_linkable)
355 -- Compilation failed. compile may still have updated
358 -> let threaded2 = CmThreaded pcs2 hst1 hit1
359 in return (threaded2, Nothing)
362 removeFromTopLevelEnvs :: [ModuleName]
363 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
364 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
365 removeFromTopLevelEnvs zap_these (hst, hit, ui)
366 = (delListFromUFM hst zap_these,
367 delListFromUFM hit zap_these,
368 filterModuleLinkables (`notElem` zap_these) ui
372 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
373 topological_sort include_source_imports summaries
375 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
377 = (summ, name_of_summary summ,
378 (if include_source_imports
379 then ms_srcimps summ else []) ++ ms_imps summ)
381 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
382 mash_edge (summ, m, m_imports)
383 = case lookup m key_map of
384 Nothing -> panic "reverse_topological_sort"
385 Just mk -> (summ, mk,
386 -- ignore imports not from the home package
387 catMaybes (map (flip lookup key_map) m_imports))
389 edges = map toEdge summaries
390 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
391 scc_input = map mash_edge edges
392 sccs = stronglyConnComp scc_input
397 -- Chase downwards from the specified root set, returning summaries
398 -- for all home modules encountered. Only follow source-import
400 downsweep :: [ModuleName] -> IO [ModSummary]
402 = do rootSummaries <- mapM getSummary rootNm
403 loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
405 getSummary :: ModuleName -> IO ModSummary
407 | trace ("getSummary: "++ showSDoc (ppr nm)) True
408 = do found <- findModule nm
410 Just (mod, location) -> summarise preprocess mod location
411 Nothing -> throwDyn (OtherError
412 ("no signs of life for module `"
413 ++ showSDoc (ppr nm) ++ "'"))
415 -- loop invariant: homeSummaries doesn't contain package modules
416 loop :: [ModSummary] -> IO [ModSummary]
418 = do let allImps :: [ModuleName]
419 allImps = (nub . concatMap ms_imps) homeSummaries
420 let allHome -- all modules currently in homeSummaries
421 = map (moduleName.ms_mod) homeSummaries
423 = filter (`notElem` allHome) allImps
425 <- mapM getSummary neededImps
427 = filter (isModuleInThisPackage.ms_mod) neededSummaries
428 if null newHomeSummaries
429 then return homeSummaries
430 else loop (newHomeSummaries ++ homeSummaries)