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"
18 import HscMain ( hscExpr )
19 import Interpreter ( HValue )
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 )
31 import PrelNames ( mainName )
32 import HscMain ( initPersistentCompilerState )
33 import Finder ( findModule, emptyHomeDirCache )
34 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
36 import Unique ( Uniquable )
37 import Digraph ( SCC(..), stronglyConnComp )
38 import DriverUtil ( BarfKind(..), splitFilename3 )
39 import CmdLineOpts ( DynFlags )
42 import Panic ( panic )
45 import Exception ( throwDyn )
48 import Time ( ClockTime )
49 import Directory ( getModificationTime, doesFileExist )
52 import Maybe ( catMaybes, fromMaybe, isJust )
53 import PrelGHC ( unsafeCoerce# )
58 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
59 cmInit raw_package_info gmode
60 = emptyCmState raw_package_info gmode
66 -> IO (CmState, Maybe HValue)
67 cmGetExpr cmstate dflags modname expr
68 = do (new_pcs, maybe_unlinked_iexpr) <-
69 hscExpr dflags hst hit pcs (mkModuleInThisPackage modname) expr
70 case maybe_unlinked_iexpr of
71 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
73 hValue <- linkExpr pls uiexpr
74 return (cmstate{ pcs=new_pcs }, Just hValue)
76 -- ToDo: check that the module we passed in is sane/exists?
78 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
79 PersistentCMState{ hst=hst, hit=hit } = pcms
81 -- The HValue should represent a value of type IO () (Perhaps IO a?)
82 cmRunExpr :: HValue -> IO ()
84 = do unsafeCoerce# hval :: IO ()
87 -- Persistent state just for CM, excluding link & compile subsystems
88 data PersistentCMState
90 hst :: HomeSymbolTable, -- home symbol table
91 hit :: HomeIfaceTable, -- home interface table
92 ui :: UnlinkedImage, -- the unlinked images
93 mg :: ModuleGraph, -- the module graph
94 pci :: PackageConfigInfo, -- NEVER CHANGES
95 gmode :: GhciMode -- NEVER CHANGES
98 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
100 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
101 ui = emptyUI, mg = emptyMG,
102 pci = pci, gmode = gmode }
104 emptyHIT :: HomeIfaceTable
106 emptyHST :: HomeSymbolTable
111 -- Persistent state for the entire system
114 pcms :: PersistentCMState, -- CM's persistent state
115 pcs :: PersistentCompilerState, -- compile's persistent state
116 pls :: PersistentLinkerState -- link's persistent state
119 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
120 emptyCmState pci gmode
121 = do let pcms = emptyPCMS pci gmode
122 pcs <- initPersistentCompilerState
124 return (CmState { pcms = pcms,
129 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
130 emptyUI :: UnlinkedImage
133 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
134 emptyMG :: ModuleGraph
139 The real business of the compilation manager: given a system state and
140 a module name, try and bring the module up to date, probably changing
141 the system state at the same time.
144 cmLoadModule :: CmState
146 -> IO (CmState, Maybe ModuleName)
148 cmLoadModule cmstate1 rootname
149 = do -- version 1's are the original, before downsweep
150 let pcms1 = pcms cmstate1
151 let pls1 = pls cmstate1
152 let pcs1 = pcs cmstate1
158 let pcii = pci pcms1 -- this never changes
159 let ghci_mode = gmode pcms1 -- ToDo: fix!
161 -- Do the downsweep to reestablish the module graph
162 -- then generate version 2's by removing from HIT,HST,UI any
163 -- modules in the old MG which are not in the new one.
165 -- Throw away the old home dir cache
168 hPutStr stderr "cmLoadModule: downsweep begins\n"
169 mg2unsorted <- downsweep [rootname]
171 let modnames1 = map name_of_summary mg1
172 let modnames2 = map name_of_summary mg2unsorted
173 let mods_to_zap = filter (`notElem` modnames2) modnames1
175 let (hst2, hit2, ui2)
176 = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
177 -- should be cycle free; ignores 'import source's
178 let mg2 = topological_sort False mg2unsorted
179 -- ... whereas this takes them into account. Used for
180 -- backing out partially complete cycles following a failed
181 -- upsweep, and for removing from hst/hit all the modules
182 -- not in strict downwards closure, during calls to compile.
183 let mg2_with_srcimps = topological_sort True mg2unsorted
185 let reachable_from :: ModuleName -> [ModuleName]
186 reachable_from = downwards_closure_of_module mg2unsorted
188 hPutStrLn stderr "after tsort:\n"
189 hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
191 -- Because we don't take into account source imports when doing
192 -- the topological sort, there shouldn't be any cycles in mg2.
193 -- If there is, we complain and give up -- the user needs to
194 -- break the cycle using a boot file.
196 -- Now do the upsweep, calling compile for each module in
197 -- turn. Final result is version 3 of everything.
199 let threaded2 = CmThreaded pcs1 hst2 hit2
201 (upsweep_complete_success, threaded3, modsDone, newLis)
202 <- upsweep_mods ghci_mode ui2 reachable_from threaded2 mg2
204 let ui3 = add_to_ui ui2 newLis
205 let (CmThreaded pcs3 hst3 hit3) = threaded3
207 -- At this point, modsDone and newLis should have the same
208 -- length, so there is one new (or old) linkable for each
209 -- mod which was processed (passed to compile).
211 -- Try and do linking in some form, depending on whether the
212 -- upsweep was completely or only partially successful.
214 if upsweep_complete_success
217 -- Easy; just relink it all.
218 do hPutStrLn stderr "UPSWEEP COMPLETELY SUCCESSFUL"
220 <- link ghci_mode (any exports_main (moduleEnvElts hst3))
224 -> panic "cmLoadModule: link failed (1)"
226 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
228 pci=pcii, gmode=ghci_mode }
230 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
231 return (cmstate3, Just rootname)
234 -- Tricky. We need to back out the effects of compiling any
235 -- half-done cycles, both so as to clean up the top level envs
236 -- and to avoid telling the interactive linker to link them.
237 do hPutStrLn stderr "UPSWEEP PARTIALLY SUCCESSFUL"
240 = map name_of_summary modsDone
241 let mods_to_zap_names
242 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
243 let (hst4, hit4, ui4)
244 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
246 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
247 let mods_to_keep_names
248 = map name_of_summary mods_to_keep
249 -- we could get the relevant linkables by filtering newLis, but
250 -- it seems easier to drag them out of the updated, cleaned-up UI
251 let linkables_to_link
252 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
255 linkresult <- link ghci_mode False linkables_to_link pls1
258 -> panic "cmLoadModule: link failed (2)"
260 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
261 ui=ui4, mg=mods_to_keep,
262 pci=pcii, gmode=ghci_mode }
264 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
266 -- choose rather arbitrarily who to return
267 if null mods_to_keep then Nothing
268 else Just (last mods_to_keep_names))
271 -- Return (names of) all those in modsDone who are part of a cycle
272 -- as defined by theGraph.
273 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
274 findPartiallyCompletedCycles modsDone theGraph
278 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
279 chew ((CyclicSCC vs):rest)
280 = let names_in_this_cycle = nub (map name_of_summary vs)
282 = nub ([done | done <- modsDone,
283 done `elem` names_in_this_cycle])
284 chewed_rest = chew rest
286 if not (null mods_in_this_cycle)
287 && length mods_in_this_cycle < length names_in_this_cycle
288 then mods_in_this_cycle ++ chewed_rest
292 -- Does this ModDetails export Main.main?
293 exports_main :: ModDetails -> Bool
295 = isJust (lookupNameEnv (md_types md) mainName)
298 -- Add the given (LM-form) Linkables to the UI, overwriting previous
299 -- versions if they exist.
300 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
304 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
306 = li : filter (\li2 -> not (for_same_module li li2)) ui
308 for_same_module :: Linkable -> Linkable -> Bool
309 for_same_module li1 li2
310 = not (is_package_linkable li1)
311 && not (is_package_linkable li2)
312 && modname_of_linkable li1 == modname_of_linkable li2
315 data CmThreaded -- stuff threaded through individual module compilations
316 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
319 -- Compile multiple modules, stopping as soon as an error appears.
320 -- There better had not be any cyclic groups here -- we check for them.
321 upsweep_mods :: GhciMode
322 -> UnlinkedImage -- old linkables
323 -> (ModuleName -> [ModuleName]) -- to construct downward closures
324 -> CmThreaded -- PCS & HST & HIT
325 -> [SCC ModSummary] -- mods to do (the worklist)
326 -- ...... RETURNING ......
327 -> IO (Bool{-complete success?-},
329 [ModSummary], -- mods which succeeded
330 [Linkable]) -- new linkables
332 upsweep_mods ghci_mode oldUI reachable_from threaded
334 = return (True, threaded, [], [])
336 upsweep_mods ghci_mode oldUI reachable_from threaded
338 = do hPutStrLn stderr ("ghc: module imports form a cycle for modules:\n\t" ++
339 unwords (map (moduleNameUserString.name_of_summary) ms))
340 return (False, threaded, [], [])
342 upsweep_mods ghci_mode oldUI reachable_from threaded
343 ((AcyclicSCC mod):mods)
344 = do (threaded1, maybe_linkable)
345 <- upsweep_mod ghci_mode oldUI threaded mod
346 (reachable_from (name_of_summary mod))
347 case maybe_linkable of
349 -> -- No errors; do the rest
350 do (restOK, threaded2, modOKs, linkables)
351 <- upsweep_mods ghci_mode oldUI reachable_from
353 return (restOK, threaded2, mod:modOKs, linkable:linkables)
354 Nothing -- we got a compilation error; give up now
355 -> return (False, threaded1, [], [])
358 -- Compile a single module. Always produce a Linkable for it if
359 -- successful. If no compilation happened, return the old Linkable.
360 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
361 maybe_getFileLinkable mod_name obj_fn
362 = do obj_exist <- doesFileExist obj_fn
366 do let stub_fn = case splitFilename3 obj_fn of
367 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
368 stub_exist <- doesFileExist stub_fn
369 obj_time <- getModificationTime obj_fn
371 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
372 else return (Just (LM obj_time mod_name [DotO obj_fn]))
375 upsweep_mod :: GhciMode
380 -> IO (CmThreaded, Maybe Linkable)
382 upsweep_mod ghci_mode oldUI threaded1 summary1 reachable_from_here
383 = do let mod_name = name_of_summary summary1
384 let (CmThreaded pcs1 hst1 hit1) = threaded1
385 let old_iface = lookupUFM hit1 (name_of_summary summary1)
387 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
388 maybe_oldDisk_linkable
389 <- case ml_obj_file (ms_location summary1) of
390 Nothing -> return Nothing
391 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
393 -- The most recent of the old UI linkable or whatever we could
394 -- find on disk. Is returned as the linkable if compile
395 -- doesn't think we need to recompile.
396 let maybe_old_linkable
397 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
398 (Nothing, Nothing) -> Nothing
399 (Nothing, Just di) -> Just di
400 (Just ui, Nothing) -> Just ui
402 | linkableTime ui >= linkableTime di -> Just ui
403 | otherwise -> Just di
405 let compilation_mandatory
406 = case maybe_old_linkable of
408 Just li -> case ms_hs_date summary1 of
409 Nothing -> panic "compilation_mandatory:no src date"
410 Just src_date -> src_date >= linkableTime li
412 = not compilation_mandatory
414 (hst1_strictDC, hit1_strictDC)
415 = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
418 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
420 compresult <- compile ghci_mode summary1 source_unchanged
421 old_iface hst1_strictDC hit1_strictDC pcs1
425 -- Compilation "succeeded", but didn't return a new iface or
426 -- linkable, meaning that compilation wasn't needed, and the
427 -- new details were manufactured from the old iface.
428 CompOK details Nothing pcs2
429 -> let hst2 = addToUFM hst1 mod_name details
431 threaded2 = CmThreaded pcs2 hst2 hit2
432 in return (threaded2, Just old_linkable)
434 -- Compilation really did happen, and succeeded. A new
435 -- details, iface and linkable are returned.
436 CompOK details (Just (new_iface, new_linkable)) pcs2
437 -> let hst2 = addToUFM hst1 mod_name details
438 hit2 = addToUFM hit1 mod_name new_iface
439 threaded2 = CmThreaded pcs2 hst2 hit2
440 in return (threaded2, Just new_linkable)
442 -- Compilation failed. compile may still have updated
445 -> let threaded2 = CmThreaded pcs2 hst1 hit1
446 in return (threaded2, Nothing)
449 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
450 removeFromTopLevelEnvs :: [ModuleName]
451 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
452 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
453 removeFromTopLevelEnvs zap_these (hst, hit, ui)
454 = (delListFromUFM hst zap_these,
455 delListFromUFM hit zap_these,
456 filterModuleLinkables (`notElem` zap_these) ui
459 retainInTopLevelEnvs :: [ModuleName]
460 -> (HomeSymbolTable, HomeIfaceTable)
461 -> (HomeSymbolTable, HomeIfaceTable)
462 retainInTopLevelEnvs keep_these (hst, hit)
463 = (retainInUFM hst keep_these,
464 retainInUFM hit keep_these
467 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
468 retainInUFM ufm keys_to_keep
469 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
471 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
473 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
474 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
475 downwards_closure_of_module summaries root
476 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
478 = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
479 res = simple_transitive_closure (map toEdge summaries) [root]
481 trace (showSDoc (text "DC of mod" <+> ppr root
482 <+> text "=" <+> ppr res)) (
486 -- Calculate transitive closures from a set of roots given an adjacency list
487 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
488 simple_transitive_closure graph set
489 = let set2 = nub (concatMap dsts set ++ set)
490 dsts node = fromMaybe [] (lookup node graph)
492 if length set == length set2
494 else simple_transitive_closure graph set2
497 -- Calculate SCCs of the module graph, with or without taking into
498 -- account source imports.
499 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
500 topological_sort include_source_imports summaries
502 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
504 = (summ, name_of_summary summ,
505 (if include_source_imports
506 then ms_srcimps summ else []) ++ ms_imps summ)
508 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
509 mash_edge (summ, m, m_imports)
510 = case lookup m key_map of
511 Nothing -> panic "reverse_topological_sort"
512 Just mk -> (summ, mk,
513 -- ignore imports not from the home package
514 catMaybes (map (flip lookup key_map) m_imports))
516 edges = map toEdge summaries
517 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
518 scc_input = map mash_edge edges
519 sccs = stronglyConnComp scc_input
524 -- Chase downwards from the specified root set, returning summaries
525 -- for all home modules encountered. Only follow source-import
527 downsweep :: [ModuleName] -> IO [ModSummary]
529 = do rootSummaries <- mapM getSummary rootNm
530 loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
532 getSummary :: ModuleName -> IO ModSummary
534 | trace ("getSummary: "++ showSDoc (ppr nm)) True
535 = do found <- findModule nm
537 -- Be sure not to use the mod and location passed in to
538 -- summarise for any other purpose -- summarise may change
539 -- the module names in them if name of module /= name of file,
540 -- and put the changed versions in the returned summary.
541 -- These will then conflict with the passed-in versions.
542 Just (mod, location) -> summarise mod location
543 Nothing -> throwDyn (OtherError
544 ("no signs of life for module `"
545 ++ showSDoc (ppr nm) ++ "'"))
547 -- loop invariant: homeSummaries doesn't contain package modules
548 loop :: [ModSummary] -> IO [ModSummary]
550 = do let allImps :: [ModuleName]
551 allImps = (nub . concatMap ms_imps) homeSummaries
552 let allHome -- all modules currently in homeSummaries
553 = map (moduleName.ms_mod) homeSummaries
555 = filter (`notElem` allHome) allImps
557 <- mapM getSummary neededImps
559 = filter (isModuleInThisPackage.ms_mod) neededSummaries
560 if null newHomeSummaries
561 then return homeSummaries
562 else loop (newHomeSummaries ++ homeSummaries)
565 -- Summarise a module, and pick up source and interface timestamps.
566 summarise :: Module -> ModuleLocation -> IO ModSummary
567 summarise mod location
568 | isModuleInThisPackage mod
569 = do let hs_fn = unJust "summarise" (ml_hs_file location)
570 hspp_fn <- preprocess hs_fn
571 modsrc <- readFile hspp_fn
572 let (srcimps,imps,mod_name) = getImports modsrc
575 <- case ml_hs_file location of
576 Nothing -> return Nothing
577 Just src_fn -> maybe_getModificationTime src_fn
579 -- If the module name is Main, allow it to be in a file
580 -- different from Main.hs, and mash the mod and loc
581 -- to match. Otherwise just moan.
582 (mashed_mod, mashed_loc)
584 () | mod_name == moduleName mod
585 -> return (mod, location)
586 | mod_name /= moduleName mod && mod_name == mkModuleName "Main"
587 -> return (mash mod location "Main")
589 -> do hPutStrLn stderr (showSDoc (
590 text "ghc: warning: file name - module name mismatch:" <+>
591 ppr (moduleName mod) <+> text "vs" <+> ppr mod_name))
592 return (mash mod location (moduleNameUserString (moduleName mod)))
594 mash old_mod old_loc new_nm
595 = (mkHomeModule (mkModuleName new_nm),
596 old_loc{ml_hi_file = maybe_swizzle_basename new_nm
597 (ml_hi_file old_loc)})
599 maybe_swizzle_basename new Nothing = Nothing
600 maybe_swizzle_basename new (Just old)
601 = case splitFilename3 old of
602 (dir, name, ext) -> Just (dir ++ new ++ ext)
604 return (ModSummary mashed_mod
605 mashed_loc{ml_hspp_file=Just hspp_fn}
610 = return (ModSummary mod location [] [] Nothing)
613 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
614 maybe_getModificationTime fn
615 = (do time <- getModificationTime fn
618 (\err -> return Nothing)