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 isHomeModule, 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 )
33 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
35 import Unique ( Uniquable )
36 import Digraph ( SCC(..), stronglyConnComp )
38 import DriverUtil ( BarfKind(..), splitFilename3 )
41 import Panic ( panic )
44 import CmdLineOpts ( DynFlags )
45 import Interpreter ( HValue )
46 import HscMain ( hscExpr )
48 import PrelGHC ( unsafeCoerce# )
52 import Exception ( throwDyn )
55 import Time ( ClockTime )
56 import Directory ( getModificationTime, doesFileExist )
59 import Maybe ( catMaybes, fromMaybe, isJust )
64 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
65 cmInit raw_package_info gmode
66 = emptyCmState raw_package_info gmode
73 -> IO (CmState, Maybe HValue)
74 cmGetExpr cmstate dflags modname expr
75 = do (new_pcs, maybe_unlinked_iexpr) <-
76 hscExpr dflags hst hit pcs (mkHomeModule modname) expr
77 case maybe_unlinked_iexpr of
78 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
80 hValue <- linkExpr pls uiexpr
81 return (cmstate{ pcs=new_pcs }, Just hValue)
83 -- ToDo: check that the module we passed in is sane/exists?
85 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
86 PersistentCMState{ hst=hst, hit=hit } = pcms
88 -- The HValue should represent a value of type IO () (Perhaps IO a?)
89 cmRunExpr :: HValue -> IO ()
91 = do unsafeCoerce# hval :: IO ()
95 -- Persistent state just for CM, excluding link & compile subsystems
96 data PersistentCMState
98 hst :: HomeSymbolTable, -- home symbol table
99 hit :: HomeIfaceTable, -- home interface table
100 ui :: UnlinkedImage, -- the unlinked images
101 mg :: ModuleGraph, -- the module graph
102 pci :: PackageConfigInfo, -- NEVER CHANGES
103 gmode :: GhciMode -- NEVER CHANGES
106 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
108 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
109 ui = emptyUI, mg = emptyMG,
110 pci = pci, gmode = gmode }
112 emptyHIT :: HomeIfaceTable
114 emptyHST :: HomeSymbolTable
119 -- Persistent state for the entire system
122 pcms :: PersistentCMState, -- CM's persistent state
123 pcs :: PersistentCompilerState, -- compile's persistent state
124 pls :: PersistentLinkerState -- link's persistent state
127 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
128 emptyCmState pci gmode
129 = do let pcms = emptyPCMS pci gmode
130 pcs <- initPersistentCompilerState
132 return (CmState { pcms = pcms,
137 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
138 emptyUI :: UnlinkedImage
141 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
142 emptyMG :: ModuleGraph
147 The real business of the compilation manager: given a system state and
148 a module name, try and bring the module up to date, probably changing
149 the system state at the same time.
152 cmLoadModule :: CmState
154 -> IO (CmState, -- new state
155 Bool, -- was successful
156 [ModuleName]) -- list of modules loaded
158 cmLoadModule cmstate1 rootname
159 = do -- version 1's are the original, before downsweep
160 let pcms1 = pcms cmstate1
161 let pls1 = pls cmstate1
162 let pcs1 = pcs cmstate1
168 let pcii = pci pcms1 -- this never changes
169 let ghci_mode = gmode pcms1 -- ToDo: fix!
171 -- Do the downsweep to reestablish the module graph
172 -- then generate version 2's by removing from HIT,HST,UI any
173 -- modules in the old MG which are not in the new one.
175 -- Throw away the old home dir cache
178 hPutStr stderr "cmLoadModule: downsweep begins\n"
179 mg2unsorted <- downsweep [rootname]
181 let modnames1 = map name_of_summary mg1
182 let modnames2 = map name_of_summary mg2unsorted
183 let mods_to_zap = filter (`notElem` modnames2) modnames1
185 let (hst2, hit2, ui2)
186 = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
187 -- should be cycle free; ignores 'import source's
188 let mg2 = topological_sort False mg2unsorted
189 -- ... whereas this takes them into account. Used for
190 -- backing out partially complete cycles following a failed
191 -- upsweep, and for removing from hst/hit all the modules
192 -- not in strict downwards closure, during calls to compile.
193 let mg2_with_srcimps = topological_sort True mg2unsorted
195 let reachable_from :: ModuleName -> [ModuleName]
196 reachable_from = downwards_closure_of_module mg2unsorted
198 hPutStrLn stderr "after tsort:\n"
199 hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
201 -- Because we don't take into account source imports when doing
202 -- the topological sort, there shouldn't be any cycles in mg2.
203 -- If there is, we complain and give up -- the user needs to
204 -- break the cycle using a boot file.
206 -- Now do the upsweep, calling compile for each module in
207 -- turn. Final result is version 3 of everything.
209 let threaded2 = CmThreaded pcs1 hst2 hit2
211 (upsweep_complete_success, threaded3, modsDone, newLis)
212 <- upsweep_mods ghci_mode ui2 reachable_from threaded2 mg2
214 let ui3 = add_to_ui ui2 newLis
215 let (CmThreaded pcs3 hst3 hit3) = threaded3
217 -- At this point, modsDone and newLis should have the same
218 -- length, so there is one new (or old) linkable for each
219 -- mod which was processed (passed to compile).
221 -- Try and do linking in some form, depending on whether the
222 -- upsweep was completely or only partially successful.
224 if upsweep_complete_success
227 -- Easy; just relink it all.
228 do hPutStrLn stderr "UPSWEEP COMPLETELY SUCCESSFUL"
230 <- link ghci_mode (any exports_main (moduleEnvElts hst3))
234 -> panic "cmLoadModule: link failed (1)"
236 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
238 pci=pcii, gmode=ghci_mode }
240 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
241 return (cmstate3, True, map name_of_summary modsDone)
244 -- Tricky. We need to back out the effects of compiling any
245 -- half-done cycles, both so as to clean up the top level envs
246 -- and to avoid telling the interactive linker to link them.
247 do hPutStrLn stderr "UPSWEEP PARTIALLY SUCCESSFUL"
250 = map name_of_summary modsDone
251 let mods_to_zap_names
252 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
253 let (hst4, hit4, ui4)
254 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
256 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
257 let mods_to_keep_names
258 = map name_of_summary mods_to_keep
259 -- we could get the relevant linkables by filtering newLis, but
260 -- it seems easier to drag them out of the updated, cleaned-up UI
261 let linkables_to_link
262 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
265 linkresult <- link ghci_mode False linkables_to_link pls1
268 -> panic "cmLoadModule: link failed (2)"
270 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
271 ui=ui4, mg=mods_to_keep,
272 pci=pcii, gmode=ghci_mode }
274 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
275 return (cmstate4, False, 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 -- We *have* to compile it if we're in batch mode and we can't see
395 -- a previous linkable for it on disk.
396 compilation_mandatory
397 <- if ghci_mode /= Batch then return False
398 else case ml_obj_file (ms_location summary1) of
399 Nothing -> do --putStrLn "cmcm: object?!"
401 Just obj_fn -> do --putStrLn ("cmcm: old obj " ++ obj_fn)
402 b <- doesFileExist obj_fn
405 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
406 maybe_oldDisk_linkable
407 <- case ml_obj_file (ms_location summary1) of
408 Nothing -> return Nothing
409 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
411 -- The most recent of the old UI linkable or whatever we could
412 -- find on disk. Is returned as the linkable if compile
413 -- doesn't think we need to recompile.
414 let maybe_old_linkable
415 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
416 (Nothing, Nothing) -> Nothing
417 (Nothing, Just di) -> Just di
418 (Just ui, Nothing) -> Just ui
420 | linkableTime ui >= linkableTime di -> Just ui
421 | otherwise -> Just di
423 let compilation_mandatory
424 = case maybe_old_linkable of
426 Just li -> case ms_hs_date summary1 of
427 Nothing -> panic "compilation_mandatory:no src date"
428 Just src_date -> src_date >= linkableTime li
430 = not compilation_mandatory
432 (hst1_strictDC, hit1_strictDC)
433 = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
436 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
438 compresult <- compile ghci_mode summary1 source_unchanged
439 old_iface hst1_strictDC hit1_strictDC pcs1
443 -- Compilation "succeeded", but didn't return a new
444 -- linkable, meaning that compilation wasn't needed, and the
445 -- new details were manufactured from the old iface.
446 CompOK pcs2 new_details new_iface Nothing
447 -> let hst2 = addToUFM hst1 mod_name new_details
448 hit2 = addToUFM hit1 mod_name new_iface
449 threaded2 = CmThreaded pcs2 hst2 hit2
450 in return (threaded2, Just old_linkable)
452 -- Compilation really did happen, and succeeded. A new
453 -- details, iface and linkable are returned.
454 CompOK pcs2 new_details new_iface (Just new_linkable)
455 -> let hst2 = addToUFM hst1 mod_name new_details
456 hit2 = addToUFM hit1 mod_name new_iface
457 threaded2 = CmThreaded pcs2 hst2 hit2
458 in return (threaded2, Just new_linkable)
460 -- Compilation failed. compile may still have updated
463 -> let threaded2 = CmThreaded pcs2 hst1 hit1
464 in return (threaded2, Nothing)
467 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
468 removeFromTopLevelEnvs :: [ModuleName]
469 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
470 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
471 removeFromTopLevelEnvs zap_these (hst, hit, ui)
472 = (delListFromUFM hst zap_these,
473 delListFromUFM hit zap_these,
474 filterModuleLinkables (`notElem` zap_these) ui
477 retainInTopLevelEnvs :: [ModuleName]
478 -> (HomeSymbolTable, HomeIfaceTable)
479 -> (HomeSymbolTable, HomeIfaceTable)
480 retainInTopLevelEnvs keep_these (hst, hit)
481 = (retainInUFM hst keep_these,
482 retainInUFM hit keep_these
485 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
486 retainInUFM ufm keys_to_keep
487 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
489 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
491 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
492 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
493 downwards_closure_of_module summaries root
494 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
496 = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
497 res = simple_transitive_closure (map toEdge summaries) [root]
499 trace (showSDoc (text "DC of mod" <+> ppr root
500 <+> text "=" <+> ppr res)) (
504 -- Calculate transitive closures from a set of roots given an adjacency list
505 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
506 simple_transitive_closure graph set
507 = let set2 = nub (concatMap dsts set ++ set)
508 dsts node = fromMaybe [] (lookup node graph)
510 if length set == length set2
512 else simple_transitive_closure graph set2
515 -- Calculate SCCs of the module graph, with or without taking into
516 -- account source imports.
517 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
518 topological_sort include_source_imports summaries
520 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
522 = (summ, name_of_summary summ,
523 (if include_source_imports
524 then ms_srcimps summ else []) ++ ms_imps summ)
526 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
527 mash_edge (summ, m, m_imports)
528 = case lookup m key_map of
529 Nothing -> panic "reverse_topological_sort"
530 Just mk -> (summ, mk,
531 -- ignore imports not from the home package
532 catMaybes (map (flip lookup key_map) m_imports))
534 edges = map toEdge summaries
535 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
536 scc_input = map mash_edge edges
537 sccs = stronglyConnComp scc_input
542 -- Chase downwards from the specified root set, returning summaries
543 -- for all home modules encountered. Only follow source-import
545 downsweep :: [FilePath] -> IO [ModSummary]
547 = do rootSummaries <- mapM getRootSummary rootNm
548 loop (filter (isHomeModule.ms_mod) rootSummaries)
550 getRootSummary :: FilePath -> IO ModSummary
552 | haskellish_file file
553 = do exists <- doesFileExist file
554 if exists then summariseFile file
555 else getSummary (mkModuleName file)
556 -- ToDo: should check import paths
558 = getSummary (mkModuleName file)
560 getSummary :: ModuleName -> IO ModSummary
562 | trace ("getSummary: "++ showSDoc (ppr nm)) True
563 = do found <- findModule nm
565 -- Be sure not to use the mod and location passed in to
566 -- summarise for any other purpose -- summarise may change
567 -- the module names in them if name of module /= name of file,
568 -- and put the changed versions in the returned summary.
569 -- These will then conflict with the passed-in versions.
570 Just (mod, location) -> summarise mod location
571 Nothing -> throwDyn (OtherError
572 ("no signs of life for module `"
573 ++ showSDoc (ppr nm) ++ "'"))
575 -- loop invariant: homeSummaries doesn't contain package modules
576 loop :: [ModSummary] -> IO [ModSummary]
578 = do let allImps :: [ModuleName]
579 allImps = (nub . concatMap ms_imps) homeSummaries
580 let allHome -- all modules currently in homeSummaries
581 = map (moduleName.ms_mod) homeSummaries
583 = filter (`notElem` allHome) allImps
585 <- mapM getSummary neededImps
587 = filter (isHomeModule.ms_mod) neededSummaries
588 if null newHomeSummaries
589 then return homeSummaries
590 else loop (newHomeSummaries ++ homeSummaries)
593 -----------------------------------------------------------------------------
594 -- Summarising modules
596 -- We have two types of summarisation:
598 -- * Summarise a file. This is used for the root module passed to
599 -- cmLoadModule. The file is read, and used to determine the root
600 -- module name. The module name may differ from the filename.
602 -- * Summarise a module. We are given a module name, and must provide
603 -- a summary. The finder is used to locate the file in which the module
606 summariseFile :: FilePath -> IO ModSummary
608 = do hspp_fn <- preprocess file
609 modsrc <- readFile hspp_fn
611 let (srcimps,imps,mod_name) = getImports modsrc
612 (path, basename, ext) = splitFilename3 file
615 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
618 <- case ml_hs_file location of
619 Nothing -> return Nothing
620 Just src_fn -> maybe_getModificationTime src_fn
622 return (ModSummary mod
623 location{ml_hspp_file=Just hspp_fn}
627 -- Summarise a module, and pick up source and interface timestamps.
628 summarise :: Module -> ModuleLocation -> IO ModSummary
629 summarise mod location
631 = do let hs_fn = unJust "summarise" (ml_hs_file location)
632 hspp_fn <- preprocess hs_fn
633 modsrc <- readFile hspp_fn
634 let (srcimps,imps,mod_name) = getImports modsrc
637 <- case ml_hs_file location of
638 Nothing -> return Nothing
639 Just src_fn -> maybe_getModificationTime src_fn
641 if mod_name == moduleName mod
643 else throwDyn (OtherError
644 (showSDoc (text "file name does not match module name: "
645 <+> ppr (moduleName mod) <+> text "vs"
648 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
653 = return (ModSummary mod location [] [] Nothing)
655 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
656 maybe_getModificationTime fn
657 = (do time <- getModificationTime fn
660 (\err -> return Nothing)