2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 module CompManager ( cmInit, cmLoadModule,
11 CmState, emptyCmState -- abstract
15 #include "HsVersions.h"
20 import Module ( ModuleName, moduleName,
21 isModuleInThisPackage, moduleEnvElts,
22 moduleNameUserString )
23 import CmStaticInfo ( PackageConfigInfo, GhciMode(..) )
26 import HscTypes ( HomeSymbolTable, HomeIfaceTable,
27 PersistentCompilerState, ModDetails(..) )
28 import Name ( lookupNameEnv )
30 import PrelNames ( mainName )
31 import HscMain ( initPersistentCompilerState )
32 import Finder ( findModule, emptyHomeDirCache )
33 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
35 import Unique ( Uniquable )
36 import Digraph ( SCC(..), stronglyConnComp )
37 import DriverUtil ( BarfKind(..), splitFilename3 )
40 import Panic ( panic )
43 import CmdLineOpts ( DynFlags )
44 import Interpreter ( HValue )
45 import HscMain ( hscExpr )
47 import PrelGHC ( unsafeCoerce# )
51 import Exception ( throwDyn )
54 import Time ( ClockTime )
55 import Directory ( getModificationTime, doesFileExist )
58 import Maybe ( catMaybes, fromMaybe, isJust )
63 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
64 cmInit raw_package_info gmode
65 = emptyCmState raw_package_info gmode
72 -> IO (CmState, Maybe HValue)
73 cmGetExpr cmstate dflags modname expr
74 = do (new_pcs, maybe_unlinked_iexpr) <-
75 hscExpr dflags hst hit pcs (mkModuleInThisPackage modname) expr
76 case maybe_unlinked_iexpr of
77 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
79 hValue <- linkExpr pls uiexpr
80 return (cmstate{ pcs=new_pcs }, Just hValue)
82 -- ToDo: check that the module we passed in is sane/exists?
84 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
85 PersistentCMState{ hst=hst, hit=hit } = pcms
87 -- The HValue should represent a value of type IO () (Perhaps IO a?)
88 cmRunExpr :: HValue -> IO ()
90 = do unsafeCoerce# hval :: IO ()
94 -- Persistent state just for CM, excluding link & compile subsystems
95 data PersistentCMState
97 hst :: HomeSymbolTable, -- home symbol table
98 hit :: HomeIfaceTable, -- home interface table
99 ui :: UnlinkedImage, -- the unlinked images
100 mg :: ModuleGraph, -- the module graph
101 pci :: PackageConfigInfo, -- NEVER CHANGES
102 gmode :: GhciMode -- NEVER CHANGES
105 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
107 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
108 ui = emptyUI, mg = emptyMG,
109 pci = pci, gmode = gmode }
111 emptyHIT :: HomeIfaceTable
113 emptyHST :: HomeSymbolTable
118 -- Persistent state for the entire system
121 pcms :: PersistentCMState, -- CM's persistent state
122 pcs :: PersistentCompilerState, -- compile's persistent state
123 pls :: PersistentLinkerState -- link's persistent state
126 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
127 emptyCmState pci gmode
128 = do let pcms = emptyPCMS pci gmode
129 pcs <- initPersistentCompilerState
131 return (CmState { pcms = pcms,
136 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
137 emptyUI :: UnlinkedImage
140 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
141 emptyMG :: ModuleGraph
146 The real business of the compilation manager: given a system state and
147 a module name, try and bring the module up to date, probably changing
148 the system state at the same time.
151 cmLoadModule :: CmState
153 -> IO (CmState, Maybe ModuleName)
155 cmLoadModule cmstate1 rootname
156 = do -- version 1's are the original, before downsweep
157 let pcms1 = pcms cmstate1
158 let pls1 = pls cmstate1
159 let pcs1 = pcs cmstate1
165 let pcii = pci pcms1 -- this never changes
166 let ghci_mode = gmode pcms1 -- ToDo: fix!
168 -- Do the downsweep to reestablish the module graph
169 -- then generate version 2's by removing from HIT,HST,UI any
170 -- modules in the old MG which are not in the new one.
172 -- Throw away the old home dir cache
175 hPutStr stderr "cmLoadModule: downsweep begins\n"
176 mg2unsorted <- downsweep [rootname]
178 let modnames1 = map name_of_summary mg1
179 let modnames2 = map name_of_summary mg2unsorted
180 let mods_to_zap = filter (`notElem` modnames2) modnames1
182 let (hst2, hit2, ui2)
183 = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
184 -- should be cycle free; ignores 'import source's
185 let mg2 = topological_sort False mg2unsorted
186 -- ... whereas this takes them into account. Used for
187 -- backing out partially complete cycles following a failed
188 -- upsweep, and for removing from hst/hit all the modules
189 -- not in strict downwards closure, during calls to compile.
190 let mg2_with_srcimps = topological_sort True mg2unsorted
192 let reachable_from :: ModuleName -> [ModuleName]
193 reachable_from = downwards_closure_of_module mg2unsorted
195 hPutStrLn stderr "after tsort:\n"
196 hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
198 -- Because we don't take into account source imports when doing
199 -- the topological sort, there shouldn't be any cycles in mg2.
200 -- If there is, we complain and give up -- the user needs to
201 -- break the cycle using a boot file.
203 -- Now do the upsweep, calling compile for each module in
204 -- turn. Final result is version 3 of everything.
206 let threaded2 = CmThreaded pcs1 hst2 hit2
208 (upsweep_complete_success, threaded3, modsDone, newLis)
209 <- upsweep_mods ghci_mode ui2 reachable_from threaded2 mg2
211 let ui3 = add_to_ui ui2 newLis
212 let (CmThreaded pcs3 hst3 hit3) = threaded3
214 -- At this point, modsDone and newLis should have the same
215 -- length, so there is one new (or old) linkable for each
216 -- mod which was processed (passed to compile).
218 -- Try and do linking in some form, depending on whether the
219 -- upsweep was completely or only partially successful.
221 if upsweep_complete_success
224 -- Easy; just relink it all.
225 do hPutStrLn stderr "UPSWEEP COMPLETELY SUCCESSFUL"
227 <- link ghci_mode (any exports_main (moduleEnvElts hst3))
231 -> panic "cmLoadModule: link failed (1)"
233 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
235 pci=pcii, gmode=ghci_mode }
237 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
238 return (cmstate3, Just rootname)
241 -- Tricky. We need to back out the effects of compiling any
242 -- half-done cycles, both so as to clean up the top level envs
243 -- and to avoid telling the interactive linker to link them.
244 do hPutStrLn stderr "UPSWEEP PARTIALLY SUCCESSFUL"
247 = map name_of_summary modsDone
248 let mods_to_zap_names
249 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
250 let (hst4, hit4, ui4)
251 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
253 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
254 let mods_to_keep_names
255 = map name_of_summary mods_to_keep
256 -- we could get the relevant linkables by filtering newLis, but
257 -- it seems easier to drag them out of the updated, cleaned-up UI
258 let linkables_to_link
259 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
262 linkresult <- link ghci_mode False linkables_to_link pls1
265 -> panic "cmLoadModule: link failed (2)"
267 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
268 ui=ui4, mg=mods_to_keep,
269 pci=pcii, gmode=ghci_mode }
271 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
273 -- choose rather arbitrarily who to return
274 if null mods_to_keep then Nothing
275 else Just (last mods_to_keep_names))
278 -- Return (names of) all those in modsDone who are part of a cycle
279 -- as defined by theGraph.
280 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
281 findPartiallyCompletedCycles modsDone theGraph
285 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
286 chew ((CyclicSCC vs):rest)
287 = let names_in_this_cycle = nub (map name_of_summary vs)
289 = nub ([done | done <- modsDone,
290 done `elem` names_in_this_cycle])
291 chewed_rest = chew rest
293 if not (null mods_in_this_cycle)
294 && length mods_in_this_cycle < length names_in_this_cycle
295 then mods_in_this_cycle ++ chewed_rest
299 -- Does this ModDetails export Main.main?
300 exports_main :: ModDetails -> Bool
302 = isJust (lookupNameEnv (md_types md) mainName)
305 -- Add the given (LM-form) Linkables to the UI, overwriting previous
306 -- versions if they exist.
307 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
311 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
313 = li : filter (\li2 -> not (for_same_module li li2)) ui
315 for_same_module :: Linkable -> Linkable -> Bool
316 for_same_module li1 li2
317 = not (is_package_linkable li1)
318 && not (is_package_linkable li2)
319 && modname_of_linkable li1 == modname_of_linkable li2
322 data CmThreaded -- stuff threaded through individual module compilations
323 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
326 -- Compile multiple modules, stopping as soon as an error appears.
327 -- There better had not be any cyclic groups here -- we check for them.
328 upsweep_mods :: GhciMode
329 -> UnlinkedImage -- old linkables
330 -> (ModuleName -> [ModuleName]) -- to construct downward closures
331 -> CmThreaded -- PCS & HST & HIT
332 -> [SCC ModSummary] -- mods to do (the worklist)
333 -- ...... RETURNING ......
334 -> IO (Bool{-complete success?-},
336 [ModSummary], -- mods which succeeded
337 [Linkable]) -- new linkables
339 upsweep_mods ghci_mode oldUI reachable_from threaded
341 = return (True, threaded, [], [])
343 upsweep_mods ghci_mode oldUI reachable_from threaded
345 = do hPutStrLn stderr ("ghc: module imports form a cycle for modules:\n\t" ++
346 unwords (map (moduleNameUserString.name_of_summary) ms))
347 return (False, threaded, [], [])
349 upsweep_mods ghci_mode oldUI reachable_from threaded
350 ((AcyclicSCC mod):mods)
351 = do (threaded1, maybe_linkable)
352 <- upsweep_mod ghci_mode oldUI threaded mod
353 (reachable_from (name_of_summary mod))
354 case maybe_linkable of
356 -> -- No errors; do the rest
357 do (restOK, threaded2, modOKs, linkables)
358 <- upsweep_mods ghci_mode oldUI reachable_from
360 return (restOK, threaded2, mod:modOKs, linkable:linkables)
361 Nothing -- we got a compilation error; give up now
362 -> return (False, threaded1, [], [])
365 -- Compile a single module. Always produce a Linkable for it if
366 -- successful. If no compilation happened, return the old Linkable.
367 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
368 maybe_getFileLinkable mod_name obj_fn
369 = do obj_exist <- doesFileExist obj_fn
373 do let stub_fn = case splitFilename3 obj_fn of
374 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
375 stub_exist <- doesFileExist stub_fn
376 obj_time <- getModificationTime obj_fn
378 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
379 else return (Just (LM obj_time mod_name [DotO obj_fn]))
382 upsweep_mod :: GhciMode
387 -> IO (CmThreaded, Maybe Linkable)
389 upsweep_mod ghci_mode oldUI threaded1 summary1 reachable_from_here
390 = do let mod_name = name_of_summary summary1
391 let (CmThreaded pcs1 hst1 hit1) = threaded1
392 let old_iface = lookupUFM hit1 (name_of_summary summary1)
394 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
395 maybe_oldDisk_linkable
396 <- case ml_obj_file (ms_location summary1) of
397 Nothing -> return Nothing
398 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
400 -- The most recent of the old UI linkable or whatever we could
401 -- find on disk. Is returned as the linkable if compile
402 -- doesn't think we need to recompile.
403 let maybe_old_linkable
404 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
405 (Nothing, Nothing) -> Nothing
406 (Nothing, Just di) -> Just di
407 (Just ui, Nothing) -> Just ui
409 | linkableTime ui >= linkableTime di -> Just ui
410 | otherwise -> Just di
412 let compilation_mandatory
413 = case maybe_old_linkable of
415 Just li -> case ms_hs_date summary1 of
416 Nothing -> panic "compilation_mandatory:no src date"
417 Just src_date -> src_date >= linkableTime li
419 = not compilation_mandatory
421 (hst1_strictDC, hit1_strictDC)
422 = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
425 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
427 compresult <- compile ghci_mode summary1 source_unchanged
428 old_iface hst1_strictDC hit1_strictDC pcs1
432 -- Compilation "succeeded", but didn't return a new iface or
433 -- linkable, meaning that compilation wasn't needed, and the
434 -- new details were manufactured from the old iface.
435 CompOK details Nothing pcs2
436 -> let hst2 = addToUFM hst1 mod_name details
438 threaded2 = CmThreaded pcs2 hst2 hit2
439 in return (threaded2, Just old_linkable)
441 -- Compilation really did happen, and succeeded. A new
442 -- details, iface and linkable are returned.
443 CompOK details (Just (new_iface, new_linkable)) pcs2
444 -> let hst2 = addToUFM hst1 mod_name details
445 hit2 = addToUFM hit1 mod_name new_iface
446 threaded2 = CmThreaded pcs2 hst2 hit2
447 in return (threaded2, Just new_linkable)
449 -- Compilation failed. compile may still have updated
452 -> let threaded2 = CmThreaded pcs2 hst1 hit1
453 in return (threaded2, Nothing)
456 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
457 removeFromTopLevelEnvs :: [ModuleName]
458 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
459 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
460 removeFromTopLevelEnvs zap_these (hst, hit, ui)
461 = (delListFromUFM hst zap_these,
462 delListFromUFM hit zap_these,
463 filterModuleLinkables (`notElem` zap_these) ui
466 retainInTopLevelEnvs :: [ModuleName]
467 -> (HomeSymbolTable, HomeIfaceTable)
468 -> (HomeSymbolTable, HomeIfaceTable)
469 retainInTopLevelEnvs keep_these (hst, hit)
470 = (retainInUFM hst keep_these,
471 retainInUFM hit keep_these
474 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
475 retainInUFM ufm keys_to_keep
476 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
478 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
480 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
481 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
482 downwards_closure_of_module summaries root
483 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
485 = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
486 res = simple_transitive_closure (map toEdge summaries) [root]
488 trace (showSDoc (text "DC of mod" <+> ppr root
489 <+> text "=" <+> ppr res)) (
493 -- Calculate transitive closures from a set of roots given an adjacency list
494 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
495 simple_transitive_closure graph set
496 = let set2 = nub (concatMap dsts set ++ set)
497 dsts node = fromMaybe [] (lookup node graph)
499 if length set == length set2
501 else simple_transitive_closure graph set2
504 -- Calculate SCCs of the module graph, with or without taking into
505 -- account source imports.
506 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
507 topological_sort include_source_imports summaries
509 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
511 = (summ, name_of_summary summ,
512 (if include_source_imports
513 then ms_srcimps summ else []) ++ ms_imps summ)
515 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
516 mash_edge (summ, m, m_imports)
517 = case lookup m key_map of
518 Nothing -> panic "reverse_topological_sort"
519 Just mk -> (summ, mk,
520 -- ignore imports not from the home package
521 catMaybes (map (flip lookup key_map) m_imports))
523 edges = map toEdge summaries
524 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
525 scc_input = map mash_edge edges
526 sccs = stronglyConnComp scc_input
531 -- Chase downwards from the specified root set, returning summaries
532 -- for all home modules encountered. Only follow source-import
534 downsweep :: [ModuleName] -> IO [ModSummary]
536 = do rootSummaries <- mapM getSummary rootNm
537 loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
539 getSummary :: ModuleName -> IO ModSummary
541 | trace ("getSummary: "++ showSDoc (ppr nm)) True
542 = do found <- findModule nm
544 -- Be sure not to use the mod and location passed in to
545 -- summarise for any other purpose -- summarise may change
546 -- the module names in them if name of module /= name of file,
547 -- and put the changed versions in the returned summary.
548 -- These will then conflict with the passed-in versions.
549 Just (mod, location) -> summarise mod location
550 Nothing -> throwDyn (OtherError
551 ("no signs of life for module `"
552 ++ showSDoc (ppr nm) ++ "'"))
554 -- loop invariant: homeSummaries doesn't contain package modules
555 loop :: [ModSummary] -> IO [ModSummary]
557 = do let allImps :: [ModuleName]
558 allImps = (nub . concatMap ms_imps) homeSummaries
559 let allHome -- all modules currently in homeSummaries
560 = map (moduleName.ms_mod) homeSummaries
562 = filter (`notElem` allHome) allImps
564 <- mapM getSummary neededImps
566 = filter (isModuleInThisPackage.ms_mod) neededSummaries
567 if null newHomeSummaries
568 then return homeSummaries
569 else loop (newHomeSummaries ++ homeSummaries)
572 -- Summarise a module, and pick up source and interface timestamps.
573 summarise :: Module -> ModuleLocation -> IO ModSummary
574 summarise mod location
575 | isModuleInThisPackage mod
576 = do let hs_fn = unJust "summarise" (ml_hs_file location)
577 hspp_fn <- preprocess hs_fn
578 modsrc <- readFile hspp_fn
579 let (srcimps,imps,mod_name) = getImports modsrc
582 <- case ml_hs_file location of
583 Nothing -> return Nothing
584 Just src_fn -> maybe_getModificationTime src_fn
586 -- If the module name is Main, allow it to be in a file
587 -- different from Main.hs, and mash the mod and loc
588 -- to match. Otherwise just moan.
589 (mashed_mod, mashed_loc)
591 () | mod_name == moduleName mod
592 -> return (mod, location)
593 | mod_name /= moduleName mod && mod_name == mkModuleName "Main"
594 -> return (mash mod location "Main")
596 -> do hPutStrLn stderr (showSDoc (
597 text "ghc: warning: file name - module name mismatch:" <+>
598 ppr (moduleName mod) <+> text "vs" <+> ppr mod_name))
599 return (mash mod location (moduleNameUserString (moduleName mod)))
601 mash old_mod old_loc new_nm
602 = (mkHomeModule (mkModuleName new_nm),
603 old_loc{ml_hi_file = maybe_swizzle_basename new_nm
604 (ml_hi_file old_loc)})
606 maybe_swizzle_basename new Nothing = Nothing
607 maybe_swizzle_basename new (Just old)
608 = case splitFilename3 old of
609 (dir, name, ext) -> Just (dir ++ new ++ ext)
611 return (ModSummary mashed_mod
612 mashed_loc{ml_hspp_file=Just hspp_fn}
617 = return (ModSummary mod location [] [] Nothing)
620 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
621 maybe_getModificationTime fn
622 = (do time <- getModificationTime fn
625 (\err -> return Nothing)