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 )
54 import PrelGHC ( unsafeCoerce# )
59 cmInit :: PackageConfigInfo -> GhciMode -> IO CmState
60 cmInit raw_package_info gmode
61 = emptyCmState raw_package_info gmode
67 -> IO (CmState, Maybe HValue)
68 cmGetExpr cmstate dflags modname expr
69 = do (new_pcs, maybe_unlinked_iexpr) <-
70 hscExpr dflags hst hit pcs (mkModuleInThisPackage modname) expr
71 case maybe_unlinked_iexpr of
72 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
74 hValue <- linkExpr pls uiexpr
75 return (cmstate{ pcs=new_pcs }, Just hValue)
77 -- ToDo: check that the module we passed in is sane/exists?
79 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
80 PersistentCMState{ hst=hst, hit=hit } = pcms
82 -- The HValue should represent a value of type IO () (Perhaps IO a?)
83 cmRunExpr :: HValue -> IO ()
85 = do unsafeCoerce# hval :: IO ()
88 -- Persistent state just for CM, excluding link & compile subsystems
89 data PersistentCMState
91 hst :: HomeSymbolTable, -- home symbol table
92 hit :: HomeIfaceTable, -- home interface table
93 ui :: UnlinkedImage, -- the unlinked images
94 mg :: ModuleGraph, -- the module graph
95 pci :: PackageConfigInfo, -- NEVER CHANGES
96 gmode :: GhciMode -- NEVER CHANGES
99 emptyPCMS :: PackageConfigInfo -> GhciMode -> PersistentCMState
101 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
102 ui = emptyUI, mg = emptyMG,
103 pci = pci, gmode = gmode }
105 emptyHIT :: HomeIfaceTable
107 emptyHST :: HomeSymbolTable
112 -- Persistent state for the entire system
115 pcms :: PersistentCMState, -- CM's persistent state
116 pcs :: PersistentCompilerState, -- compile's persistent state
117 pls :: PersistentLinkerState -- link's persistent state
120 emptyCmState :: PackageConfigInfo -> GhciMode -> IO CmState
121 emptyCmState pci gmode
122 = do let pcms = emptyPCMS pci gmode
123 pcs <- initPersistentCompilerState
125 return (CmState { pcms = pcms,
130 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
131 emptyUI :: UnlinkedImage
134 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
135 emptyMG :: ModuleGraph
140 The real business of the compilation manager: given a system state and
141 a module name, try and bring the module up to date, probably changing
142 the system state at the same time.
145 cmLoadModule :: CmState
147 -> IO (CmState, Maybe ModuleName)
149 cmLoadModule cmstate1 rootname
150 = do -- version 1's are the original, before downsweep
151 let pcms1 = pcms cmstate1
152 let pls1 = pls cmstate1
153 let pcs1 = pcs cmstate1
159 let pcii = pci pcms1 -- this never changes
160 let ghci_mode = gmode pcms1 -- ToDo: fix!
162 -- During upsweep, look at new summaries to see if source has
163 -- changed. Here's a function to pass down; it takes a new
165 let source_changed :: ModSummary -> Bool
166 source_changed = summary_indicates_source_changed mg1
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 source_changed 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 (findModuleLinkable ui4) mods_to_keep_names
261 linkresult <- link ghci_mode False linkables_to_link pls1
264 -> panic "cmLoadModule: link failed (2)"
266 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
267 ui=ui4, mg=mods_to_keep,
268 pci=pcii, gmode=ghci_mode }
270 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
272 -- choose rather arbitrarily who to return
273 if null mods_to_keep then Nothing
274 else Just (last mods_to_keep_names))
277 -- Given a bunch of old summaries and a new summary, try and
278 -- find the corresponding old summary, and, if found, compare
279 -- its source timestamp with that of the new summary. If in
281 summary_indicates_source_changed :: [ModSummary] -> ModSummary -> Bool
282 summary_indicates_source_changed old_summaries new_summary
283 = case [old | old <- old_summaries,
284 name_of_summary old == name_of_summary new_summary] of
286 (_:_:_) -> panic "summary_indicates_newer_source"
288 [] -> -- can't find a corresponding old summary, so
289 -- compare source and iface dates in the new summary.
290 trace (showSDoc (text "SISC: no old summary, new ="
291 <+> pprSummaryTimes new_summary)) (
292 case (ms_hs_date new_summary, ms_hi_date new_summary) of
293 (Just hs_t, Just hi_t) -> hs_t > hi_t
297 [old] -> -- found old summary; compare source timestamps
298 trace (showSDoc (text "SISC: old ="
299 <+> pprSummaryTimes old
300 <+> pprSummaryTimes new_summary)) (
301 case (ms_hs_date old, ms_hs_date new_summary) of
302 (Just old_t, Just new_t) -> new_t > old_t
306 -- Return (names of) all those in modsDone who are part of a cycle
307 -- as defined by theGraph.
308 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
309 findPartiallyCompletedCycles modsDone theGraph
313 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
314 chew ((CyclicSCC vs):rest)
315 = let names_in_this_cycle = nub (map name_of_summary vs)
317 = nub ([done | done <- modsDone,
318 done `elem` names_in_this_cycle])
319 chewed_rest = chew rest
321 if not (null mods_in_this_cycle)
322 && length mods_in_this_cycle < length names_in_this_cycle
323 then mods_in_this_cycle ++ chewed_rest
327 -- Does this ModDetails export Main.main?
328 exports_main :: ModDetails -> Bool
330 = isJust (lookupNameEnv (md_types md) mainName)
333 -- Add the given (LM-form) Linkables to the UI, overwriting previous
334 -- versions if they exist.
335 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
339 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
341 = li : filter (\li2 -> not (for_same_module li li2)) ui
343 for_same_module :: Linkable -> Linkable -> Bool
344 for_same_module li1 li2
345 = not (is_package_linkable li1)
346 && not (is_package_linkable li2)
347 && modname_of_linkable li1 == modname_of_linkable li2
350 data CmThreaded -- stuff threaded through individual module compilations
351 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
354 -- Compile multiple modules, stopping as soon as an error appears.
355 -- There better had not be any cyclic groups here -- we check for them.
356 upsweep_mods :: GhciMode
357 -> UnlinkedImage -- old linkables
358 -> (ModuleName -> [ModuleName]) -- to construct downward closures
359 -> (ModSummary -> Bool) -- has source changed?
360 -> CmThreaded -- PCS & HST & HIT
361 -> [SCC ModSummary] -- mods to do (the worklist)
362 -- ...... RETURNING ......
363 -> IO (Bool{-complete success?-},
365 [ModSummary], -- mods which succeeded
366 [Linkable]) -- new linkables
368 upsweep_mods ghci_mode oldUI reachable_from source_changed threaded []
369 = return (True, threaded, [], [])
371 upsweep_mods ghci_mode oldUI reachable_from source_changed threaded ((CyclicSCC ms):_)
372 = do hPutStrLn stderr ("ghc: module imports form a cycle for modules:\n\t" ++
373 unwords (map (moduleNameUserString.name_of_summary) ms))
374 return (False, threaded, [], [])
376 upsweep_mods ghci_mode oldUI reachable_from source_changed threaded ((AcyclicSCC mod):mods)
377 = do (threaded1, maybe_linkable)
378 <- upsweep_mod ghci_mode oldUI threaded mod
379 (reachable_from (name_of_summary mod))
381 case maybe_linkable of
383 -> -- No errors; do the rest
384 do (restOK, threaded2, modOKs, linkables)
385 <- upsweep_mods ghci_mode oldUI reachable_from source_changed threaded1 mods
386 return (restOK, threaded2, mod:modOKs, linkable:linkables)
387 Nothing -- we got a compilation error; give up now
388 -> return (False, threaded1, [], [])
391 -- Compile a single module. Always produce a Linkable for it if
392 -- successful. If no compilation happened, return the old Linkable.
393 upsweep_mod :: GhciMode
399 -> IO (CmThreaded, Maybe Linkable)
401 upsweep_mod ghci_mode oldUI threaded1 summary1
402 reachable_from_here source_might_have_changed
403 = do let mod_name = name_of_summary summary1
404 let (CmThreaded pcs1 hst1 hit1) = threaded1
405 let old_iface = lookupUFM hit1 (name_of_summary summary1)
407 -- We *have* to compile it if we're in batch mode and we can't see
408 -- a previous linkable for it on disk.
409 compilation_mandatory
410 <- if ghci_mode /= Batch then return False
411 else case ml_obj_file (ms_location summary1) of
412 Nothing -> do --putStrLn "cmcm: object?!"
414 Just obj_fn -> do --putStrLn ("cmcm: old obj " ++ obj_fn)
415 b <- doesFileExist obj_fn
418 let compilation_might_be_needed
419 = source_might_have_changed || compilation_mandatory
421 = not compilation_might_be_needed
422 (hst1_strictDC, hit1_strictDC)
423 = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
425 compresult <- compile ghci_mode summary1 source_unchanged
426 old_iface hst1_strictDC hit1_strictDC pcs1
428 --putStrLn ( "UPSWEEP_MOD: smhc = " ++ show source_might_have_changed
429 -- ++ ", cman = " ++ show compilation_mandatory)
433 -- Compilation "succeeded", but didn't return a new iface or
434 -- linkable, meaning that compilation wasn't needed, and the
435 -- new details were manufactured from the old iface.
436 CompOK details Nothing pcs2
437 -> let hst2 = addToUFM hst1 mod_name details
439 threaded2 = CmThreaded pcs2 hst2 hit2
441 | ghci_mode == Interactive
442 = findModuleLinkable oldUI mod_name
445 [DotO (unJust (ml_obj_file (ms_location summary1))
447 in return (threaded2, Just old_linkable)
449 -- Compilation really did happen, and succeeded. A new
450 -- details, iface and linkable are returned.
451 CompOK details (Just (new_iface, new_linkable)) pcs2
452 -> let hst2 = addToUFM hst1 mod_name details
453 hit2 = addToUFM hit1 mod_name new_iface
454 threaded2 = CmThreaded pcs2 hst2 hit2
455 in return (threaded2, Just new_linkable)
457 -- Compilation failed. compile may still have updated
460 -> let threaded2 = CmThreaded pcs2 hst1 hit1
461 in return (threaded2, Nothing)
464 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
465 removeFromTopLevelEnvs :: [ModuleName]
466 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
467 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
468 removeFromTopLevelEnvs zap_these (hst, hit, ui)
469 = (delListFromUFM hst zap_these,
470 delListFromUFM hit zap_these,
471 filterModuleLinkables (`notElem` zap_these) ui
474 retainInTopLevelEnvs :: [ModuleName]
475 -> (HomeSymbolTable, HomeIfaceTable)
476 -> (HomeSymbolTable, HomeIfaceTable)
477 retainInTopLevelEnvs keep_these (hst, hit)
478 = (retainInUFM hst keep_these,
479 retainInUFM hit keep_these
482 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
483 retainInUFM ufm keys_to_keep
484 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
486 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
488 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
489 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
490 downwards_closure_of_module summaries root
491 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
493 = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
494 res = simple_transitive_closure (map toEdge summaries) [root]
496 trace (showSDoc (text "DC of mod" <+> ppr root
497 <+> text "=" <+> ppr res)) (
501 -- Calculate transitive closures from a set of roots given an adjacency list
502 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
503 simple_transitive_closure graph set
504 = let set2 = nub (concatMap dsts set ++ set)
505 dsts node = fromMaybe [] (lookup node graph)
507 if length set == length set2
509 else simple_transitive_closure graph set2
512 -- Calculate SCCs of the module graph, with or without taking into
513 -- account source imports.
514 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
515 topological_sort include_source_imports summaries
517 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
519 = (summ, name_of_summary summ,
520 (if include_source_imports
521 then ms_srcimps summ else []) ++ ms_imps summ)
523 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
524 mash_edge (summ, m, m_imports)
525 = case lookup m key_map of
526 Nothing -> panic "reverse_topological_sort"
527 Just mk -> (summ, mk,
528 -- ignore imports not from the home package
529 catMaybes (map (flip lookup key_map) m_imports))
531 edges = map toEdge summaries
532 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
533 scc_input = map mash_edge edges
534 sccs = stronglyConnComp scc_input
539 -- Chase downwards from the specified root set, returning summaries
540 -- for all home modules encountered. Only follow source-import
542 downsweep :: [ModuleName] -> IO [ModSummary]
544 = do rootSummaries <- mapM getSummary rootNm
545 loop (filter (isModuleInThisPackage.ms_mod) rootSummaries)
547 getSummary :: ModuleName -> IO ModSummary
549 | trace ("getSummary: "++ showSDoc (ppr nm)) True
550 = do found <- findModule nm
552 -- Be sure not to use the mod and location passed in to
553 -- summarise for any other purpose -- summarise may change
554 -- the module names in them if name of module /= name of file,
555 -- and put the changed versions in the returned summary.
556 -- These will then conflict with the passed-in versions.
557 Just (mod, location) -> summarise mod location
558 Nothing -> throwDyn (OtherError
559 ("no signs of life for module `"
560 ++ showSDoc (ppr nm) ++ "'"))
562 -- loop invariant: homeSummaries doesn't contain package modules
563 loop :: [ModSummary] -> IO [ModSummary]
565 = do let allImps :: [ModuleName]
566 allImps = (nub . concatMap ms_imps) homeSummaries
567 let allHome -- all modules currently in homeSummaries
568 = map (moduleName.ms_mod) homeSummaries
570 = filter (`notElem` allHome) allImps
572 <- mapM getSummary neededImps
574 = filter (isModuleInThisPackage.ms_mod) neededSummaries
575 if null newHomeSummaries
576 then return homeSummaries
577 else loop (newHomeSummaries ++ homeSummaries)
580 -- Summarise a module, and pick up source and interface timestamps.
581 summarise :: Module -> ModuleLocation -> IO ModSummary
582 summarise mod location
583 | isModuleInThisPackage mod
584 = do let hs_fn = unJust (ml_hs_file location) "summarise"
585 hspp_fn <- preprocess hs_fn
586 modsrc <- readFile hspp_fn
587 let (srcimps,imps,mod_name) = getImports modsrc
590 <- case ml_hs_file location of
591 Nothing -> return Nothing
592 Just src_fn -> maybe_getModificationTime src_fn
593 maybe_iface_timestamp
594 <- case ml_hi_file location of
595 Nothing -> return Nothing
596 Just if_fn -> maybe_getModificationTime if_fn
598 -- If the module name is Main, allow it to be in a file
599 -- different from Main.hs, and mash the mod and loc
600 -- to match. Otherwise just moan.
601 (mashed_mod, mashed_loc)
603 () | mod_name == moduleName mod
604 -> return (mod, location)
605 | mod_name /= moduleName mod && mod_name == mkModuleName "Main"
606 -> return (mash mod location "Main")
608 -> do hPutStrLn stderr (showSDoc (
609 text "ghc: warning: file name - module name mismatch:" <+>
610 ppr (moduleName mod) <+> text "vs" <+> ppr mod_name))
611 return (mash mod location (moduleNameUserString (moduleName mod)))
613 mash old_mod old_loc new_nm
614 = (mkHomeModule (mkModuleName new_nm),
615 old_loc{ml_hi_file = maybe_swizzle_basename new_nm
616 (ml_hi_file old_loc)})
618 maybe_swizzle_basename new Nothing = Nothing
619 maybe_swizzle_basename new (Just old)
620 = case splitFilename3 old of
621 (dir, name, ext) -> Just (dir ++ new ++ ext)
623 return (ModSummary mashed_mod
624 mashed_loc{ml_hspp_file=Just hspp_fn}
626 maybe_src_timestamp maybe_iface_timestamp)
629 = return (ModSummary mod location [] [] Nothing Nothing)
632 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
633 maybe_getModificationTime fn
634 = (do time <- getModificationTime fn
637 (\err -> return Nothing)