2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 module CompManager ( cmInit, cmLoadModule,
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 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 The real business of the compilation manager: given a system state and
164 a module name, try and bring the module up to date, probably changing
165 the system state at the same time.
168 cmLoadModule :: CmState
170 -> IO (CmState, -- new state
171 Bool, -- was successful
172 [ModuleName]) -- list of modules loaded
174 cmLoadModule cmstate1 rootname
175 = do -- version 1's are the original, before downsweep
176 let pcms1 = pcms cmstate1
177 let pls1 = pls cmstate1
178 let pcs1 = pcs cmstate1
184 let ghci_mode = gmode pcms1 -- this never changes
186 -- Do the downsweep to reestablish the module graph
187 -- then generate version 2's by removing from HIT,HST,UI any
188 -- modules in the old MG which are not in the new one.
190 -- Throw away the old home dir cache
193 dflags <- getDynFlags
194 let verb = verbosity dflags
196 showPass dflags "Chasing dependencies"
197 when (verb >= 1 && ghci_mode == Batch) $
198 hPutStrLn stderr ("ghc: chasing modules from: " ++ rootname)
200 mg2unsorted <- downsweep [rootname]
202 let modnames1 = map name_of_summary mg1
203 let modnames2 = map name_of_summary mg2unsorted
204 let mods_to_zap = filter (`notElem` modnames2) modnames1
206 let (hst2, hit2, ui2)
207 = removeFromTopLevelEnvs mods_to_zap (hst1, hit1, ui1)
208 -- should be cycle free; ignores 'import source's
209 let mg2 = topological_sort False mg2unsorted
210 -- ... whereas this takes them into account. Used for
211 -- backing out partially complete cycles following a failed
212 -- upsweep, and for removing from hst/hit all the modules
213 -- not in strict downwards closure, during calls to compile.
214 let mg2_with_srcimps = topological_sort True mg2unsorted
216 let reachable_from :: ModuleName -> [ModuleName]
217 reachable_from = downwards_closure_of_module mg2unsorted
219 --hPutStrLn stderr "after tsort:\n"
220 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
222 -- Because we don't take into account source imports when doing
223 -- the topological sort, there shouldn't be any cycles in mg2.
224 -- If there is, we complain and give up -- the user needs to
225 -- break the cycle using a boot file.
227 -- Now do the upsweep, calling compile for each module in
228 -- turn. Final result is version 3 of everything.
230 let threaded2 = CmThreaded pcs1 hst2 hit2
232 (upsweep_complete_success, threaded3, modsDone, newLis)
233 <- upsweep_mods ghci_mode ui2 reachable_from threaded2 mg2
235 let ui3 = add_to_ui ui2 newLis
236 let (CmThreaded pcs3 hst3 hit3) = threaded3
238 -- At this point, modsDone and newLis should have the same
239 -- length, so there is one new (or old) linkable for each
240 -- mod which was processed (passed to compile).
242 -- Try and do linking in some form, depending on whether the
243 -- upsweep was completely or only partially successful.
245 if upsweep_complete_success
248 -- Easy; just relink it all.
249 do when (verb >= 2) $
250 hPutStrLn stderr "Upsweep completely successful."
252 <- link ghci_mode dflags
253 (any exports_main (moduleEnvElts hst3))
257 -> panic "cmLoadModule: link failed (1)"
259 -> do let pcms3 = PersistentCMState { hst=hst3, hit=hit3,
263 = CmState { pcms=pcms3, pcs=pcs3, pls=pls3 }
264 return (cmstate3, True, map name_of_summary modsDone)
267 -- Tricky. We need to back out the effects of compiling any
268 -- half-done cycles, both so as to clean up the top level envs
269 -- and to avoid telling the interactive linker to link them.
270 do when (verb >= 2) $
271 hPutStrLn stderr "Upsweep partially successful."
274 = map name_of_summary modsDone
275 let mods_to_zap_names
276 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
277 let (hst4, hit4, ui4)
278 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
280 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
281 let mods_to_keep_names
282 = map name_of_summary mods_to_keep
283 -- we could get the relevant linkables by filtering newLis, but
284 -- it seems easier to drag them out of the updated, cleaned-up UI
285 let linkables_to_link
286 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
289 linkresult <- link ghci_mode dflags False linkables_to_link pls1
292 -> panic "cmLoadModule: link failed (2)"
294 -> do let pcms4 = PersistentCMState { hst=hst4, hit=hit4,
295 ui=ui4, mg=mods_to_keep,
298 = CmState { pcms=pcms4, pcs=pcs3, pls=pls4 }
299 return (cmstate4, False, mods_to_keep_names)
302 -- Return (names of) all those in modsDone who are part of a cycle
303 -- as defined by theGraph.
304 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
305 findPartiallyCompletedCycles modsDone theGraph
309 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
310 chew ((CyclicSCC vs):rest)
311 = let names_in_this_cycle = nub (map name_of_summary vs)
313 = nub ([done | done <- modsDone,
314 done `elem` names_in_this_cycle])
315 chewed_rest = chew rest
317 if not (null mods_in_this_cycle)
318 && length mods_in_this_cycle < length names_in_this_cycle
319 then mods_in_this_cycle ++ chewed_rest
323 -- Does this ModDetails export Main.main?
324 exports_main :: ModDetails -> Bool
326 = isJust (lookupNameEnv (md_types md) mainName)
329 -- Add the given (LM-form) Linkables to the UI, overwriting previous
330 -- versions if they exist.
331 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
335 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
337 = li : filter (\li2 -> not (for_same_module li li2)) ui
339 for_same_module :: Linkable -> Linkable -> Bool
340 for_same_module li1 li2
341 = not (is_package_linkable li1)
342 && not (is_package_linkable li2)
343 && modname_of_linkable li1 == modname_of_linkable li2
346 data CmThreaded -- stuff threaded through individual module compilations
347 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
350 -- Compile multiple modules, stopping as soon as an error appears.
351 -- There better had not be any cyclic groups here -- we check for them.
352 upsweep_mods :: GhciMode
353 -> UnlinkedImage -- old linkables
354 -> (ModuleName -> [ModuleName]) -- to construct downward closures
355 -> CmThreaded -- PCS & HST & HIT
356 -> [SCC ModSummary] -- mods to do (the worklist)
357 -- ...... RETURNING ......
358 -> IO (Bool{-complete success?-},
360 [ModSummary], -- mods which succeeded
361 [Linkable]) -- new linkables
363 upsweep_mods ghci_mode oldUI reachable_from threaded
365 = return (True, threaded, [], [])
367 upsweep_mods ghci_mode oldUI reachable_from threaded
369 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
370 unwords (map (moduleNameUserString.name_of_summary) ms))
371 return (False, threaded, [], [])
373 upsweep_mods ghci_mode oldUI reachable_from threaded
374 ((AcyclicSCC mod):mods)
375 = do (threaded1, maybe_linkable)
376 <- upsweep_mod ghci_mode oldUI threaded mod
377 (reachable_from (name_of_summary mod))
378 case maybe_linkable of
380 -> -- No errors; do the rest
381 do (restOK, threaded2, modOKs, linkables)
382 <- upsweep_mods ghci_mode oldUI reachable_from
384 return (restOK, threaded2, mod:modOKs, linkable:linkables)
385 Nothing -- we got a compilation error; give up now
386 -> return (False, threaded1, [], [])
389 -- Compile a single module. Always produce a Linkable for it if
390 -- successful. If no compilation happened, return the old Linkable.
391 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
392 maybe_getFileLinkable mod_name obj_fn
393 = do obj_exist <- doesFileExist obj_fn
397 do let stub_fn = case splitFilename3 obj_fn of
398 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
399 stub_exist <- doesFileExist stub_fn
400 obj_time <- getModificationTime obj_fn
402 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
403 else return (Just (LM obj_time mod_name [DotO obj_fn]))
406 upsweep_mod :: GhciMode
411 -> IO (CmThreaded, Maybe Linkable)
413 upsweep_mod ghci_mode oldUI threaded1 summary1 reachable_from_here
414 = do hPutStr stderr ("ghc: module "
415 ++ moduleNameUserString (name_of_summary summary1) ++ ": ")
416 let mod_name = name_of_summary summary1
417 let (CmThreaded pcs1 hst1 hit1) = threaded1
418 let old_iface = lookupUFM hit1 (name_of_summary summary1)
420 -- We *have* to compile it if we're in batch mode and we can't see
421 -- a previous linkable for it on disk.
422 compilation_mandatory
423 <- if ghci_mode /= Batch then return False
424 else case ml_obj_file (ms_location summary1) of
425 Nothing -> do --putStrLn "cmcm: object?!"
427 Just obj_fn -> do --putStrLn ("cmcm: old obj " ++ obj_fn)
428 b <- doesFileExist obj_fn
431 let maybe_oldUI_linkable = findModuleLinkable_maybe oldUI mod_name
432 maybe_oldDisk_linkable
433 <- case ml_obj_file (ms_location summary1) of
434 Nothing -> return Nothing
435 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
437 -- The most recent of the old UI linkable or whatever we could
438 -- find on disk. Is returned as the linkable if compile
439 -- doesn't think we need to recompile.
440 let maybe_old_linkable
441 = case (maybe_oldUI_linkable, maybe_oldDisk_linkable) of
442 (Nothing, Nothing) -> Nothing
443 (Nothing, Just di) -> Just di
444 (Just ui, Nothing) -> Just ui
446 | linkableTime ui >= linkableTime di -> Just ui
447 | otherwise -> Just di
449 let compilation_mandatory
450 = case maybe_old_linkable of
452 Just li -> case ms_hs_date summary1 of
453 Nothing -> panic "compilation_mandatory:no src date"
454 Just src_date -> src_date >= linkableTime li
456 = not compilation_mandatory
458 (hst1_strictDC, hit1_strictDC)
459 = retainInTopLevelEnvs reachable_from_here (hst1,hit1)
462 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
464 compresult <- compile ghci_mode summary1 source_unchanged
465 old_iface hst1_strictDC hit1_strictDC pcs1
469 -- Compilation "succeeded", but didn't return a new
470 -- linkable, meaning that compilation wasn't needed, and the
471 -- new details were manufactured from the old iface.
472 CompOK pcs2 new_details new_iface Nothing
473 -> let hst2 = addToUFM hst1 mod_name new_details
474 hit2 = addToUFM hit1 mod_name new_iface
475 threaded2 = CmThreaded pcs2 hst2 hit2
476 in return (threaded2, Just old_linkable)
478 -- Compilation really did happen, and succeeded. A new
479 -- details, iface and linkable are returned.
480 CompOK pcs2 new_details new_iface (Just new_linkable)
481 -> let hst2 = addToUFM hst1 mod_name new_details
482 hit2 = addToUFM hit1 mod_name new_iface
483 threaded2 = CmThreaded pcs2 hst2 hit2
484 in return (threaded2, Just new_linkable)
486 -- Compilation failed. compile may still have updated
489 -> let threaded2 = CmThreaded pcs2 hst1 hit1
490 in return (threaded2, Nothing)
493 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
494 removeFromTopLevelEnvs :: [ModuleName]
495 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
496 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
497 removeFromTopLevelEnvs zap_these (hst, hit, ui)
498 = (delListFromUFM hst zap_these,
499 delListFromUFM hit zap_these,
500 filterModuleLinkables (`notElem` zap_these) ui
503 retainInTopLevelEnvs :: [ModuleName]
504 -> (HomeSymbolTable, HomeIfaceTable)
505 -> (HomeSymbolTable, HomeIfaceTable)
506 retainInTopLevelEnvs keep_these (hst, hit)
507 = (retainInUFM hst keep_these,
508 retainInUFM hit keep_these
511 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
512 retainInUFM ufm keys_to_keep
513 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
515 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
517 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
518 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
519 downwards_closure_of_module summaries root
520 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
522 = (name_of_summary summ, ms_srcimps summ ++ ms_imps summ)
523 res = simple_transitive_closure (map toEdge summaries) [root]
525 --trace (showSDoc (text "DC of mod" <+> ppr root
526 -- <+> text "=" <+> ppr res)) (
530 -- Calculate transitive closures from a set of roots given an adjacency list
531 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
532 simple_transitive_closure graph set
533 = let set2 = nub (concatMap dsts set ++ set)
534 dsts node = fromMaybe [] (lookup node graph)
536 if length set == length set2
538 else simple_transitive_closure graph set2
541 -- Calculate SCCs of the module graph, with or without taking into
542 -- account source imports.
543 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
544 topological_sort include_source_imports summaries
546 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
548 = (summ, name_of_summary summ,
549 (if include_source_imports
550 then ms_srcimps summ else []) ++ ms_imps summ)
552 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
553 mash_edge (summ, m, m_imports)
554 = case lookup m key_map of
555 Nothing -> panic "reverse_topological_sort"
556 Just mk -> (summ, mk,
557 -- ignore imports not from the home package
558 catMaybes (map (flip lookup key_map) m_imports))
560 edges = map toEdge summaries
561 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
562 scc_input = map mash_edge edges
563 sccs = stronglyConnComp scc_input
568 -- Chase downwards from the specified root set, returning summaries
569 -- for all home modules encountered. Only follow source-import
571 downsweep :: [FilePath] -> IO [ModSummary]
573 = do rootSummaries <- mapM getRootSummary rootNm
574 loop (filter (isHomeModule.ms_mod) rootSummaries)
576 getRootSummary :: FilePath -> IO ModSummary
578 | haskellish_file file
579 = do exists <- doesFileExist file
580 if exists then summariseFile file else do
581 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
583 = do exists <- doesFileExist hs_file
584 if exists then summariseFile hs_file else do
585 exists <- doesFileExist lhs_file
586 if exists then summariseFile lhs_file else do
587 getSummary (mkModuleName file)
589 hs_file = file ++ ".hs"
590 lhs_file = file ++ ".lhs"
592 getSummary :: ModuleName -> IO ModSummary
594 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
595 = do found <- findModule nm
597 -- Be sure not to use the mod and location passed in to
598 -- summarise for any other purpose -- summarise may change
599 -- the module names in them if name of module /= name of file,
600 -- and put the changed versions in the returned summary.
601 -- These will then conflict with the passed-in versions.
602 Just (mod, location) -> summarise mod location
603 Nothing -> throwDyn (OtherError
604 ("can't find module `"
605 ++ showSDoc (ppr nm) ++ "'"))
607 -- loop invariant: homeSummaries doesn't contain package modules
608 loop :: [ModSummary] -> IO [ModSummary]
610 = do let allImps :: [ModuleName]
611 allImps = (nub . concatMap ms_imps) homeSummaries
612 let allHome -- all modules currently in homeSummaries
613 = map (moduleName.ms_mod) homeSummaries
615 = filter (`notElem` allHome) allImps
617 <- mapM getSummary neededImps
619 = filter (isHomeModule.ms_mod) neededSummaries
620 if null newHomeSummaries
621 then return homeSummaries
622 else loop (newHomeSummaries ++ homeSummaries)
625 -----------------------------------------------------------------------------
626 -- Summarising modules
628 -- We have two types of summarisation:
630 -- * Summarise a file. This is used for the root module passed to
631 -- cmLoadModule. The file is read, and used to determine the root
632 -- module name. The module name may differ from the filename.
634 -- * Summarise a module. We are given a module name, and must provide
635 -- a summary. The finder is used to locate the file in which the module
638 summariseFile :: FilePath -> IO ModSummary
640 = do hspp_fn <- preprocess file
641 modsrc <- readFile hspp_fn
643 let (srcimps,imps,mod_name) = getImports modsrc
644 (path, basename, ext) = splitFilename3 file
647 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
650 <- case ml_hs_file location of
651 Nothing -> return Nothing
652 Just src_fn -> maybe_getModificationTime src_fn
654 return (ModSummary mod
655 location{ml_hspp_file=Just hspp_fn}
659 -- Summarise a module, and pick up source and interface timestamps.
660 summarise :: Module -> ModuleLocation -> IO ModSummary
661 summarise mod location
663 = do let hs_fn = unJust "summarise" (ml_hs_file location)
664 hspp_fn <- preprocess hs_fn
665 modsrc <- readFile hspp_fn
666 let (srcimps,imps,mod_name) = getImports modsrc
669 <- case ml_hs_file location of
670 Nothing -> return Nothing
671 Just src_fn -> maybe_getModificationTime src_fn
673 if mod_name == moduleName mod
675 else throwDyn (OtherError
676 (showSDoc (text "file name does not match module name: "
677 <+> ppr (moduleName mod) <+> text "vs"
680 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
685 = return (ModSummary mod location [] [] Nothing)
687 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
688 maybe_getModificationTime fn
689 = (do time <- getModificationTime fn
692 (\err -> return Nothing)