2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 module CompManager ( cmInit, cmLoadModule, cmUnload,
9 cmGetExpr, cmTypeExpr, cmRunExpr,
11 CmState, emptyCmState -- abstract
15 #include "HsVersions.h"
20 import Module ( ModuleName, moduleName,
21 isHomeModule, moduleEnvElts,
22 moduleNameUserString )
23 import CmStaticInfo ( GhciMode(..) )
26 import HscTypes ( HomeSymbolTable, HomeIfaceTable,
27 PersistentCompilerState, ModDetails(..) )
29 import Name ( lookupNameEnv )
31 import PrelNames ( mainName )
32 import HscMain ( initPersistentCompilerState )
34 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
36 import Unique ( Uniquable )
37 import Digraph ( SCC(..), stronglyConnComp )
38 import DriverFlags ( getDynFlags )
40 import DriverUtil ( BarfKind(..), splitFilename3 )
41 import ErrUtils ( showPass )
44 import Panic ( panic )
45 import CmdLineOpts ( DynFlags(..) )
48 import Interpreter ( HValue )
49 import HscMain ( hscExpr, hscTypeExpr )
51 import PrelGHC ( unsafeCoerce# )
55 import Exception ( throwDyn )
58 import Time ( ClockTime )
59 import Directory ( getModificationTime, doesFileExist )
63 import Maybe ( catMaybes, fromMaybe, isJust )
68 cmInit :: GhciMode -> IO CmState
77 -> IO (CmState, Maybe HValue)
78 cmGetExpr cmstate dflags modname expr
79 = do (new_pcs, maybe_unlinked_iexpr) <-
80 hscExpr dflags hst hit pcs (mkHomeModule modname) expr
81 case maybe_unlinked_iexpr of
82 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
84 hValue <- linkExpr pls uiexpr
85 return (cmstate{ pcs=new_pcs }, Just hValue)
87 -- ToDo: check that the module we passed in is sane/exists?
89 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
90 PersistentCMState{ hst=hst, hit=hit } = pcms
96 -> IO (CmState, Maybe (PrintUnqualified, Type))
97 cmTypeExpr cmstate dflags modname expr
98 = do (new_pcs, expr_type) <-
99 hscTypeExpr dflags hst hit pcs (mkHomeModule modname) expr
100 return (cmstate{ pcs=new_pcs }, expr_type)
102 CmState{ pcs=pcs, pcms=pcms, pls=pls } = cmstate
103 PersistentCMState{ hst=hst, hit=hit } = pcms
105 -- The HValue should represent a value of type IO () (Perhaps IO a?)
106 cmRunExpr :: HValue -> IO ()
108 = do unsafeCoerce# hval :: IO ()
112 -- Persistent state just for CM, excluding link & compile subsystems
113 data PersistentCMState
114 = PersistentCMState {
115 hst :: HomeSymbolTable, -- home symbol table
116 hit :: HomeIfaceTable, -- home interface table
117 ui :: UnlinkedImage, -- the unlinked images
118 mg :: ModuleGraph, -- the module graph
119 gmode :: GhciMode -- NEVER CHANGES
122 emptyPCMS :: GhciMode -> PersistentCMState
124 = PersistentCMState { hst = emptyHST, hit = emptyHIT,
125 ui = emptyUI, mg = emptyMG,
128 emptyHIT :: HomeIfaceTable
130 emptyHST :: HomeSymbolTable
135 -- Persistent state for the entire system
138 pcms :: PersistentCMState, -- CM's persistent state
139 pcs :: PersistentCompilerState, -- compile's persistent state
140 pls :: PersistentLinkerState -- link's persistent state
143 emptyCmState :: GhciMode -> IO CmState
145 = do let pcms = emptyPCMS gmode
146 pcs <- initPersistentCompilerState
148 return (CmState { pcms = pcms,
153 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
154 emptyUI :: UnlinkedImage
157 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
158 emptyMG :: ModuleGraph
163 Unload the compilation manager's state: everything it knows about the
164 current collection of modules in the Home package.
167 cmUnload :: CmState -> IO CmState
169 = do -- Throw away the old home dir cache
171 -- Throw away the HIT and the HST
172 return state{ pcms=pcms{ hst=new_hst, hit=new_hit } }
174 CmState{ pcms=pcms } = state
175 PersistentCMState{ hst=hst, hit=hit } = pcms
176 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
179 The real business of the compilation manager: given a system state and
180 a module name, try and bring the module up to date, probably changing
181 the system state at the same time.
184 cmLoadModule :: CmState
186 -> IO (CmState, -- new state
187 Bool, -- was successful
188 [ModuleName]) -- list of modules loaded
190 cmLoadModule cmstate1 rootname
191 = do -- version 1's are the original, before downsweep
192 let pcms1 = pcms cmstate1
193 let pls1 = pls cmstate1
194 let pcs1 = pcs cmstate1
200 let ghci_mode = gmode pcms1 -- this never changes
202 -- Do the downsweep to reestablish the module graph
203 -- then generate version 2's by removing from HIT,HST,UI any
204 -- modules in the old MG which are not in the new one.
206 dflags <- getDynFlags
207 let verb = verbosity dflags
209 showPass dflags "Chasing dependencies"
210 when (verb >= 1 && ghci_mode == Batch) $
211 hPutStrLn stderr ("ghc: chasing modules from: " ++ rootname)
213 mg2unsorted <- downsweep [rootname]
215 let modnames1 = map name_of_summary mg1
216 let modnames2 = map name_of_summary mg2unsorted
217 let mods_to_zap = filter (`notElem` modnames2) modnames1
219 let (hst2, hit2, ui2)
220 = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
221 -- should be cycle free; ignores 'import source's
222 let mg2 = topological_sort False mg2unsorted
223 -- ... whereas this takes them into account. Used for
224 -- backing out partially complete cycles following a failed
225 -- upsweep, and for removing from hst/hit all the modules
226 -- not in strict downwards closure, during calls to compile.
227 let mg2_with_srcimps = topological_sort True mg2unsorted
229 let reachable_from :: ModuleName -> [ModuleName]
230 reachable_from = downwards_closure_of_module mg2unsorted
232 --hPutStrLn stderr "after tsort:\n"
233 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
235 -- Because we don't take into account source imports when doing
236 -- the topological sort, there shouldn't be any cycles in mg2.
237 -- If there is, we complain and give up -- the user needs to
238 -- break the cycle using a boot file.
240 -- Now do the upsweep, calling compile for each module in
241 -- turn. Final result is version 3 of everything.
243 let threaded2 = CmThreaded pcs1 hst2 hit2
245 (upsweep_complete_success, threaded3, modsDone, newLis)
246 <- upsweep_mods ghci_mode ui2 reachable_from threaded2 mg2
248 let ui3 = add_to_ui ui2 newLis
249 let (CmThreaded pcs3 hst3 hit3) = threaded3
251 -- At this point, modsDone and newLis should have the same
252 -- length, so there is one new (or old) linkable for each
253 -- mod which was processed (passed to compile).
255 -- Try and do linking in some form, depending on whether the
256 -- upsweep was completely or only partially successful.
258 if upsweep_complete_success
261 -- Easy; just relink it all.
262 do when (verb >= 2) $
263 hPutStrLn stderr "Upsweep completely successful."
265 <- link ghci_mode dflags
266 (any exports_main (moduleEnvElts hst3))
270 -> panic "cmLoadModule: link failed (1)"
272 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
276 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
277 return (cmstate3, True, map name_of_summary modsDone)
280 -- Tricky. We need to back out the effects of compiling any
281 -- half-done cycles, both so as to clean up the top level envs
282 -- and to avoid telling the interactive linker to link them.
283 do when (verb >= 2) $
284 hPutStrLn stderr "Upsweep partially successful."
287 = map name_of_summary modsDone
288 let mods_to_zap_names
289 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
290 let (hst4, hit4, ui4)
291 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
293 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
294 let mods_to_keep_names
295 = map name_of_summary mods_to_keep
296 -- we could get the relevant linkables by filtering newLis, but
297 -- it seems easier to drag them out of the updated, cleaned-up UI
298 let linkables_to_link
299 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
302 linkresult <- link ghci_mode dflags False linkables_to_link pls1
305 -> panic "cmLoadModule: link failed (2)"
307 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
308 ui=ui4, mg=mods_to_keep,
311 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
312 return (cmstate4, False, mods_to_keep_names)
315 -- Return (names of) all those in modsDone who are part of a cycle
316 -- as defined by theGraph.
317 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
318 findPartiallyCompletedCycles modsDone theGraph
322 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
323 chew ((CyclicSCC vs):rest)
324 = let names_in_this_cycle = nub (map name_of_summary vs)
326 = nub ([done | done <- modsDone,
327 done `elem` names_in_this_cycle])
328 chewed_rest = chew rest
330 if not (null mods_in_this_cycle)
331 && length mods_in_this_cycle < length names_in_this_cycle
332 then mods_in_this_cycle ++ chewed_rest
336 -- Does this ModDetails export Main.main?
337 exports_main :: ModDetails -> Bool
339 = isJust (lookupNameEnv (md_types md) mainName)
342 -- Add the given (LM-form) Linkables to the UI, overwriting previous
343 -- versions if they exist.
344 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
348 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
350 = li : filter (\li2 -> not (for_same_module li li2)) ui
352 for_same_module :: Linkable -> Linkable -> Bool
353 for_same_module li1 li2
354 = not (is_package_linkable li1)
355 && not (is_package_linkable li2)
356 && modname_of_linkable li1 == modname_of_linkable li2
359 data CmThreaded -- stuff threaded through individual module compilations
360 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
363 -- Compile multiple modules, stopping as soon as an error appears.
364 -- There better had not be any cyclic groups here -- we check for them.
365 upsweep_mods :: GhciMode
366 -> UnlinkedImage -- old linkables
367 -> (ModuleName -> [ModuleName]) -- to construct downward closures
368 -> CmThreaded -- PCS & HST & HIT
369 -> [SCC ModSummary] -- mods to do (the worklist)
370 -- ...... RETURNING ......
371 -> IO (Bool{-complete success?-},
373 [ModSummary], -- mods which succeeded
374 [Linkable]) -- new linkables
376 upsweep_mods ghci_mode oldUI reachable_from threaded
378 = return (True, threaded, [], [])
380 upsweep_mods ghci_mode oldUI reachable_from threaded
382 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
383 unwords (map (moduleNameUserString.name_of_summary) ms))
384 return (False, threaded, [], [])
386 upsweep_mods ghci_mode oldUI reachable_from threaded
387 ((AcyclicSCC mod):mods)
388 = do (threaded1, maybe_linkable)
389 <- upsweep_mod ghci_mode oldUI threaded mod
390 (reachable_from (name_of_summary mod))
391 case maybe_linkable of
393 -> -- No errors; do the rest
394 do (restOK, threaded2, modOKs, linkables)
395 <- upsweep_mods ghci_mode oldUI reachable_from
397 return (restOK, threaded2, mod:modOKs, linkable:linkables)
398 Nothing -- we got a compilation error; give up now
399 -> return (False, threaded1, [], [])
402 -- Compile a single module. Always produce a Linkable for it if
403 -- successful. If no compilation happened, return the old Linkable.
404 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
405 maybe_getFileLinkable mod_name obj_fn
406 = do obj_exist <- doesFileExist obj_fn
410 do let stub_fn = case splitFilename3 obj_fn of
411 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
412 stub_exist <- doesFileExist stub_fn
413 obj_time <- getModificationTime obj_fn
415 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
416 else return (Just (LM obj_time mod_name [DotO obj_fn]))
419 upsweep_mod :: GhciMode
424 -> IO (CmThreaded, Maybe Linkable)
426 upsweep_mod ghci_mode oldUI threaded1 summary1 reachable_from_here
427 = do hPutStr stderr ("ghc: module "
428 ++ moduleNameUserString (name_of_summary summary1) ++ ": ")
429 let mod_name = name_of_summary summary1
430 let (CmThreaded pcs1 hst1 hit1) = threaded1
431 let old_iface = lookupUFM hit1 (name_of_summary summary1)
433 -- We *have* to compile it if we're in batch mode and we can't see
434 -- a previous linkable for it on disk.
435 compilation_mandatory
436 <- if ghci_mode /= Batch then return False
437 else case ml_obj_file (ms_location summary1) of
438 Nothing -> do --putStrLn "cmcm: object?!"
440 Just obj_fn -> do --putStrLn ("cmcm: old obj " ++ obj_fn)
441 b <- doesFileExist obj_fn
444 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
445 maybe_oldDisk_linkable
446 <- case ml_obj_file (ms_location summary1) of
447 Nothing -> return Nothing
448 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
450 -- The most recent of the old UI linkable or whatever we could
451 -- find on disk. Is returned as the linkable if compile
452 -- doesn't think we need to recompile.
453 let maybe_old_linkable
454 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
455 (Nothing, Nothing) -> Nothing
456 (Nothing, Just di) -> Just di
457 (Just ui, Nothing) -> Just ui
459 | linkableTime ui >= linkableTime di -> Just ui
460 | otherwise -> Just di
462 let compilation_mandatory
463 = case maybe_old_linkable of
465 Just li -> case ms_hs_date summary1 of
466 Nothing -> panic "compilation_mandatory:no src date"
467 Just src_date -> src_date >= linkableTime li
469 = not compilation_mandatory
471 (hst1_strictDC, hit1_strictDC)
472 = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
475 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
477 compresult <- compile ghci_mode summary1 source_unchanged
478 old_iface hst1_strictDC hit1_strictDC pcs1
482 -- Compilation "succeeded", but didn't return a new
483 -- linkable, meaning that compilation wasn't needed, and the
484 -- new details were manufactured from the old iface.
485 CompOK pcs2 new_details new_iface Nothing
486 -> let hst2 = addToUFM hst1 mod_name new_details
487 hit2 = addToUFM hit1 mod_name new_iface
488 threaded2 = CmThreaded pcs2 hst2 hit2
489 in return (threaded2, Just old_linkable)
491 -- Compilation really did happen, and succeeded. A new
492 -- details, iface and linkable are returned.
493 CompOK pcs2 new_details new_iface (Just new_linkable)
494 -> let hst2 = addToUFM hst1 mod_name new_details
495 hit2 = addToUFM hit1 mod_name new_iface
496 threaded2 = CmThreaded pcs2 hst2 hit2
497 in return (threaded2, Just new_linkable)
499 -- Compilation failed. compile may still have updated
502 -> let threaded2 = CmThreaded pcs2 hst1 hit1
503 in return (threaded2, Nothing)
506 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
507 removeFromTopLevelEnvs :: [ModuleName]
508 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
509 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
510 removeFromTopLevelEnvs zap_these (hst, hit, ui)
511 = (delListFromUFM hst zap_these,
512 delListFromUFM hit zap_these,
513 filterModuleLinkables (`notElem` zap_these) ui
516 retainInTopLevelEnvs :: [ModuleName]
517 -> (HomeSymbolTable, HomeIfaceTable)
518 -> (HomeSymbolTable, HomeIfaceTable)
519 retainInTopLevelEnvs keep_these (hst, hit)
520 = (retainInUFM hst keep_these,
521 retainInUFM hit keep_these
524 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
525 retainInUFM ufm keys_to_keep
526 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
528 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
530 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
531 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
532 downwards_closure_of_module summaries root
533 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
535 = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
536 res = simple_transitive_closure (map toEdge summaries) [root]
538 --trace (showSDoc (text "DC of mod" <+> ppr root
539 -- <+> text "=" <+> ppr res)) (
543 -- Calculate transitive closures from a set of roots given an adjacency list
544 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
545 simple_transitive_closure graph set
546 = let set2 = nub (concatMap dsts set ++ set)
547 dsts node = fromMaybe [] (lookup node graph)
549 if length set == length set2
551 else simple_transitive_closure graph set2
554 -- Calculate SCCs of the module graph, with or without taking into
555 -- account source imports.
556 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
557 topological_sort include_source_imports summaries
559 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
561 = (summ, name_of_summary summ,
562 (if include_source_imports
563 then ms_srcimps summ else []) ++ ms_imps summ)
565 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
566 mash_edge (summ, m, m_imports)
567 = case lookup m key_map of
568 Nothing -> panic "reverse_topological_sort"
569 Just mk -> (summ, mk,
570 -- ignore imports not from the home package
571 catMaybes (map (flip lookup key_map) m_imports))
573 edges = map toEdge summaries
574 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
575 scc_input = map mash_edge edges
576 sccs = stronglyConnComp scc_input
581 -- Chase downwards from the specified root set, returning summaries
582 -- for all home modules encountered. Only follow source-import
584 downsweep :: [FilePath] -> IO [ModSummary]
586 = do rootSummaries <- mapM getRootSummary rootNm
587 loop (filter (isHomeModule.ms_mod) rootSummaries)
589 getRootSummary :: FilePath -> IO ModSummary
591 | haskellish_file file
592 = do exists <- doesFileExist file
593 if exists then summariseFile file else do
594 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
596 = do exists <- doesFileExist hs_file
597 if exists then summariseFile hs_file else do
598 exists <- doesFileExist lhs_file
599 if exists then summariseFile lhs_file else do
600 getSummary (mkModuleName file)
602 hs_file = file ++ ".hs"
603 lhs_file = file ++ ".lhs"
605 getSummary :: ModuleName -> IO ModSummary
607 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
608 = do found <- findModule nm
610 -- Be sure not to use the mod and location passed in to
611 -- summarise for any other purpose -- summarise may change
612 -- the module names in them if name of module /= name of file,
613 -- and put the changed versions in the returned summary.
614 -- These will then conflict with the passed-in versions.
615 Just (mod, location) -> summarise mod location
616 Nothing -> throwDyn (OtherError
617 ("can't find module `"
618 ++ showSDoc (ppr nm) ++ "'"))
620 -- loop invariant: homeSummaries doesn't contain package modules
621 loop :: [ModSummary] -> IO [ModSummary]
623 = do let allImps :: [ModuleName]
624 allImps = (nub . concatMap ms_imps) homeSummaries
625 let allHome -- all modules currently in homeSummaries
626 = map (moduleName.ms_mod) homeSummaries
628 = filter (`notElem` allHome) allImps
630 <- mapM getSummary neededImps
632 = filter (isHomeModule.ms_mod) neededSummaries
633 if null newHomeSummaries
634 then return homeSummaries
635 else loop (newHomeSummaries ++ homeSummaries)
638 -----------------------------------------------------------------------------
639 -- Summarising modules
641 -- We have two types of summarisation:
643 -- * Summarise a file. This is used for the root module passed to
644 -- cmLoadModule. The file is read, and used to determine the root
645 -- module name. The module name may differ from the filename.
647 -- * Summarise a module. We are given a module name, and must provide
648 -- a summary. The finder is used to locate the file in which the module
651 summariseFile :: FilePath -> IO ModSummary
653 = do hspp_fn <- preprocess file
654 modsrc <- readFile hspp_fn
656 let (srcimps,imps,mod_name) = getImports modsrc
657 (path, basename, ext) = splitFilename3 file
660 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
663 <- case ml_hs_file location of
664 Nothing -> return Nothing
665 Just src_fn -> maybe_getModificationTime src_fn
667 return (ModSummary mod
668 location{ml_hspp_file=Just hspp_fn}
672 -- Summarise a module, and pick up source and interface timestamps.
673 summarise :: Module -> ModuleLocation -> IO ModSummary
674 summarise mod location
676 = do let hs_fn = unJust "summarise" (ml_hs_file location)
677 hspp_fn <- preprocess hs_fn
678 modsrc <- readFile hspp_fn
679 let (srcimps,imps,mod_name) = getImports modsrc
682 <- case ml_hs_file location of
683 Nothing -> return Nothing
684 Just src_fn -> maybe_getModificationTime src_fn
686 if mod_name == moduleName mod
688 else throwDyn (OtherError
689 (showSDoc (text "file name does not match module name: "
690 <+> ppr (moduleName mod) <+> text "vs"
693 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
698 = return (ModSummary mod location [] [] Nothing)
700 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
701 maybe_getModificationTime fn
702 = (do time <- getModificationTime fn
705 (\err -> return Nothing)