2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 module CompManager ( cmInit, cmLoadModule, cmUnload,
11 CmState, emptyCmState -- abstract
15 #include "HsVersions.h"
20 import Module ( Module, ModuleName, moduleName, isHomeModule,
21 mkModuleName, moduleNameUserString )
22 import CmStaticInfo ( GhciMode(..) )
25 import HscTypes ( HomeSymbolTable, HomeIfaceTable,
26 PersistentCompilerState, ModDetails(..) )
27 import HscMain ( initPersistentCompilerState )
29 import UniqFM ( emptyUFM, lookupUFM, addToUFM, delListFromUFM,
31 import Unique ( Uniquable )
32 import Digraph ( SCC(..), stronglyConnComp, flattenSCC )
33 import DriverFlags ( getDynFlags )
35 import DriverUtil ( splitFilename3 )
36 import ErrUtils ( showPass )
41 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 )
60 import Maybe ( catMaybes, fromMaybe, maybeToList, isJust )
65 cmInit :: GhciMode -> IO CmState
72 -> Bool -- True <=> wrap in 'print' to get an IO-typed result
75 -> IO (CmState, Maybe (HValue, PrintUnqualified, Type))
76 cmGetExpr cmstate dflags wrap_io mod expr
77 = do (new_pcs, maybe_stuff) <-
78 hscExpr dflags wrap_io hst hit pcs mod expr
80 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
81 Just (bcos, print_unqual, ty) -> do
82 hValue <- linkExpr pls bcos
83 return (cmstate{ pcs=new_pcs },
84 Just (hValue, print_unqual, ty))
86 -- ToDo: check that the module we passed in is sane/exists?
88 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls } = cmstate
90 -- The HValue should represent a value of type IO () (Perhaps IO a?)
91 cmRunExpr :: HValue -> IO ()
93 = do unsafeCoerce# hval :: IO ()
97 emptyHIT :: HomeIfaceTable
99 emptyHST :: HomeSymbolTable
102 -- Persistent state for the entire system
105 hst :: HomeSymbolTable, -- home symbol table
106 hit :: HomeIfaceTable, -- home interface table
107 ui :: UnlinkedImage, -- the unlinked images
108 mg :: ModuleGraph, -- the module graph
109 gmode :: GhciMode, -- NEVER CHANGES
111 pcs :: PersistentCompilerState, -- compile's persistent state
112 pls :: PersistentLinkerState -- link's persistent state
115 emptyCmState :: GhciMode -> IO CmState
117 = do pcs <- initPersistentCompilerState
119 return (CmState { hst = emptyHST,
128 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
129 emptyUI :: UnlinkedImage
132 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
133 emptyMG :: ModuleGraph
138 Unload the compilation manager's state: everything it knows about the
139 current collection of modules in the Home package.
142 cmUnload :: CmState -> IO CmState
144 = do -- Throw away the old home dir cache
146 -- Throw away the HIT and the HST
147 return state{ hst=new_hst, hit=new_hit, ui=emptyUI }
149 CmState{ hst=hst, hit=hit } = state
150 (new_hst, new_hit) = retainInTopLevelEnvs [] (hst,hit)
153 The real business of the compilation manager: given a system state and
154 a module name, try and bring the module up to date, probably changing
155 the system state at the same time.
158 cmLoadModule :: CmState
160 -> IO (CmState, -- new state
161 Bool, -- was successful
162 [Module]) -- list of modules loaded
164 cmLoadModule cmstate1 rootname
165 = do -- version 1's are the original, before downsweep
166 let pls1 = pls cmstate1
167 let pcs1 = pcs cmstate1
168 let hst1 = hst cmstate1
169 let hit1 = hit cmstate1
170 -- similarly, ui1 is the (complete) set of linkables from
171 -- the previous pass, if any.
172 let ui1 = ui cmstate1
174 let ghci_mode = gmode cmstate1 -- this never changes
176 -- Do the downsweep to reestablish the module graph
177 -- then generate version 2's by retaining in HIT,HST,UI a
178 -- stable set S of modules, as defined below.
180 dflags <- getDynFlags
181 let verb = verbosity dflags
183 showPass dflags "Chasing dependencies"
184 when (verb >= 1 && ghci_mode == Batch) $
185 hPutStrLn stderr (progName ++ ": chasing modules from: " ++ rootname)
187 (mg2unsorted, a_root_is_Main) <- downsweep [rootname]
188 let mg2unsorted_names = map name_of_summary mg2unsorted
190 -- reachable_from follows source as well as normal imports
191 let reachable_from :: ModuleName -> [ModuleName]
192 reachable_from = downwards_closure_of_module mg2unsorted
194 -- should be cycle free; ignores 'import source's
195 let mg2 = topological_sort False mg2unsorted
196 -- ... whereas this takes them into account. Used for
197 -- backing out partially complete cycles following a failed
198 -- upsweep, and for removing from hst/hit all the modules
199 -- not in strict downwards closure, during calls to compile.
200 let mg2_with_srcimps = topological_sort True mg2unsorted
202 -- Sort out which linkables we wish to keep in the unlinked image.
203 -- For each module, we take:
205 -- - the old in-core linkable, if available
206 -- - an on-disk linkable, if available
208 -- and we take the youngest of these, provided it is younger than the
211 -- If a module has a valid linkable, then it may be STABLE (see below),
212 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
214 valid_linkables <- getValidLinkables ui1 mg2unsorted
216 -- Figure out a stable set of modules which can be retained
217 -- the top level envs, to avoid upsweeping them. Goes to a
218 -- bit of trouble to avoid upsweeping module cycles.
220 -- Construct a set S of stable modules like this:
221 -- Travel upwards, over the sccified graph. For each scc
222 -- of modules ms, add ms to S only if:
223 -- 1. All home imports of ms are either in ms or S
224 -- 2. A valid linkable exists for each module in ms
227 <- preUpsweep valid_linkables mg2unsorted_names [] mg2_with_srcimps
230 = concatMap (findInSummaries mg2unsorted) stable_mods
233 putStrLn (showSDoc (text "STABLE MODULES:"
234 <+> sep (map (text.moduleNameUserString) stable_mods)))
236 -- We could at this point detect cycles which aren't broken by
237 -- a source-import, and complain immediately, but it seems better
238 -- to let upsweep_mods do this, so at least some useful work gets
239 -- done before the upsweep is abandoned.
241 = filter (\scc -> any (`notElem` stable_mods)
242 (map name_of_summary (flattenSCC scc)))
245 --hPutStrLn stderr "after tsort:\n"
246 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
248 -- Because we don't take into account source imports when doing
249 -- the topological sort, there shouldn't be any cycles in mg2.
250 -- If there is, we complain and give up -- the user needs to
251 -- break the cycle using a boot file.
253 -- Now do the upsweep, calling compile for each module in
254 -- turn. Final result is version 3 of everything.
256 let threaded2 = CmThreaded pcs1 hst1 hit1
258 (upsweep_complete_success, threaded3, modsUpswept, newLis)
259 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
260 threaded2 upsweep_these
262 let ui3 = add_to_ui valid_linkables newLis
263 let (CmThreaded pcs3 hst3 hit3) = threaded3
265 -- At this point, modsUpswept and newLis should have the same
266 -- length, so there is one new (or old) linkable for each
267 -- mod which was processed (passed to compile).
269 -- Make modsDone be the summaries for each home module now
270 -- available; this should equal the domains of hst3 and hit3.
271 -- (NOT STRICTLY TRUE if an interactive session was started
272 -- with some object on disk ???)
273 -- Get in in a roughly top .. bottom order (hence reverse).
275 let modsDone = reverse modsUpswept ++ stable_summaries
277 -- Try and do linking in some form, depending on whether the
278 -- upsweep was completely or only partially successful.
280 if upsweep_complete_success
283 -- Easy; just relink it all.
284 do when (verb >= 2) $
285 hPutStrLn stderr "Upsweep completely successful."
287 <- link ghci_mode dflags a_root_is_Main ui3 pls1
290 -> panic "cmLoadModule: link failed (1)"
293 = CmState { hst=hst3, hit=hit3,
297 return (cmstate3, True,
301 -- Tricky. We need to back out the effects of compiling any
302 -- half-done cycles, both so as to clean up the top level envs
303 -- and to avoid telling the interactive linker to link them.
304 do when (verb >= 2) $
305 hPutStrLn stderr "Upsweep partially successful."
308 = map name_of_summary modsDone
309 let mods_to_zap_names
310 = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps
311 let (hst4, hit4, ui4)
312 = removeFromTopLevelEnvs mods_to_zap_names (hst3,hit3,ui3)
314 = filter ((`notElem` mods_to_zap_names).name_of_summary) modsDone
315 let mods_to_keep_names
316 = map name_of_summary mods_to_keep
317 -- we could get the relevant linkables by filtering newLis, but
318 -- it seems easier to drag them out of the updated, cleaned-up UI
319 let linkables_to_link
320 = map (unJust "linkables_to_link" . findModuleLinkable_maybe ui4)
323 linkresult <- link ghci_mode dflags False linkables_to_link pls1
326 -> panic "cmLoadModule: link failed (2)"
329 = CmState { hst=hst4, hit=hit4,
330 ui=ui4, mg=mods_to_keep,
331 gmode=ghci_mode, pcs=pcs3, pls=pls4 }
332 return (cmstate4, False,
333 map ms_mod mods_to_keep)
336 -----------------------------------------------------------------------------
340 :: [Linkable] -- old linkables
341 -> [ModSummary] -- all modules in the program
342 -> IO [Linkable] -- still-valid linkables
344 getValidLinkables old_linkables summaries
345 = do lis <- mapM (getValidLinkable old_linkables) summaries
348 getValidLinkable old_linkables summary
349 = do let mod_name = moduleName (ms_mod summary)
351 <- case ml_obj_file (ms_location summary) of
352 Nothing -> return Nothing
353 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
355 -- find an old in-core linkable if we have one. (forget about
356 -- on-disk linkables for now, we'll check again whether there's
357 -- one here below, just in case a new one has popped up recently).
358 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
361 Just (LM _ _ ls) | all isInterpretable ls -> old_linkable
364 -- The most recent of the old UI linkable or whatever we could
365 -- find on disk. Is returned as the linkable if compile
366 -- doesn't think we need to recompile.
368 = case (maybe_old_linkable, maybe_disk_linkable) of
369 (Nothing, Nothing) -> []
370 (Nothing, Just di) -> [di]
371 (Just ui, Nothing) -> [ui]
373 | linkableTime ui >= linkableTime di -> [ui]
376 -- only linkables newer than the source code are valid
377 let maybe_src_date = ms_hs_date summary
380 = case maybe_src_date of
381 Nothing -> panic "valid_linkable_list"
383 -> filter (\li -> linkableTime li > src_date) linkable_list
385 return valid_linkable_list
389 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
390 maybe_getFileLinkable mod_name obj_fn
391 = do obj_exist <- doesFileExist obj_fn
395 do let stub_fn = case splitFilename3 obj_fn of
396 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
397 stub_exist <- doesFileExist stub_fn
398 obj_time <- getModificationTime obj_fn
400 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
401 else return (Just (LM obj_time mod_name [DotO obj_fn]))
404 -----------------------------------------------------------------------------
405 -- Do a pre-upsweep without use of "compile", to establish a
406 -- (downward-closed) set of stable modules which can be retained
407 -- in the top-level environments. Also return linkables for those
408 -- modules determined to be stable, since (in Batch mode, at least)
409 -- there's no other way for them to get into UI.
411 preUpsweep :: [Linkable] -- valid linkables
412 -> [ModuleName] -- names of all mods encountered in downsweep
413 -> [ModuleName] -- accumulating stable modules
414 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
415 -> IO [ModuleName] -- stable modules
417 preUpsweep valid_lis all_home_mods stable []
419 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
420 = do let scc = flattenSCC scc0
421 scc_allhomeimps :: [ModuleName]
423 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
424 all_imports_in_scc_or_stable
425 = all in_stable_or_scc scc_allhomeimps
427 = map name_of_summary scc
429 = --trace (showSDoc (text "ISOS" <+> ppr m <+> ppr scc_names <+> ppr stable)) (
430 m `elem` scc_names || m `elem` stable
433 <- if not all_imports_in_scc_or_stable
434 then do --putStrLn ("PART1 fail " ++ showSDoc (ppr scc_allhomeimps <+> ppr (filter (not.in_stable_or_scc) scc_allhomeimps)))
436 else do --when (not (and bools)) (putStrLn ("PART2 fail: " ++ showSDoc (ppr scc_names)))
437 return (all is_stable scc)
438 if not all_scc_stable
439 then preUpsweep valid_lis all_home_mods stable sccs
440 else preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
442 where is_stable new_summary
443 = isJust (findModuleLinkable_maybe valid_lis (name_of_summary new_summary))
446 -- Helper for preUpsweep. Assuming that new_summary's imports are all
447 -- stable (in the sense of preUpsweep), determine if new_summary is itself
448 -- stable, and, if so, in batch mode, return its linkable.
449 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
450 findInSummaries old_summaries mod_name
451 = [s | s <- old_summaries, name_of_summary s == mod_name]
454 -- Return (names of) all those in modsDone who are part of a cycle
455 -- as defined by theGraph.
456 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
457 findPartiallyCompletedCycles modsDone theGraph
461 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
462 chew ((CyclicSCC vs):rest)
463 = let names_in_this_cycle = nub (map name_of_summary vs)
465 = nub ([done | done <- modsDone,
466 done `elem` names_in_this_cycle])
467 chewed_rest = chew rest
469 if not (null mods_in_this_cycle)
470 && length mods_in_this_cycle < length names_in_this_cycle
471 then mods_in_this_cycle ++ chewed_rest
475 -- Does this ModDetails export Main.main?
476 --exports_main :: ModDetails -> Bool
478 -- = isJust (lookupNameEnv (md_types md) mainName)
481 -- Add the given (LM-form) Linkables to the UI, overwriting previous
482 -- versions if they exist.
483 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
487 add1 :: Linkable -> UnlinkedImage -> UnlinkedImage
489 = li : filter (\li2 -> not (for_same_module li li2)) ui
491 for_same_module :: Linkable -> Linkable -> Bool
492 for_same_module li1 li2
493 = not (is_package_linkable li1)
494 && not (is_package_linkable li2)
495 && modname_of_linkable li1 == modname_of_linkable li2
498 data CmThreaded -- stuff threaded through individual module compilations
499 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
502 -- Compile multiple modules, stopping as soon as an error appears.
503 -- There better had not be any cyclic groups here -- we check for them.
504 upsweep_mods :: GhciMode
506 -> UnlinkedImage -- valid linkables
507 -> (ModuleName -> [ModuleName]) -- to construct downward closures
508 -> CmThreaded -- PCS & HST & HIT
509 -> [SCC ModSummary] -- mods to do (the worklist)
510 -- ...... RETURNING ......
511 -> IO (Bool{-complete success?-},
513 [ModSummary], -- mods which succeeded
514 [Linkable]) -- new linkables
516 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
518 = return (True, threaded, [], [])
520 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
522 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
523 unwords (map (moduleNameUserString.name_of_summary) ms))
524 return (False, threaded, [], [])
526 upsweep_mods ghci_mode dflags oldUI reachable_from threaded
527 ((AcyclicSCC mod):mods)
528 = do --case threaded of
529 -- CmThreaded pcsz hstz hitz
530 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
532 (threaded1, maybe_linkable)
533 <- upsweep_mod ghci_mode dflags oldUI threaded mod
534 (reachable_from (name_of_summary mod))
535 case maybe_linkable of
537 -> -- No errors; do the rest
538 do (restOK, threaded2, modOKs, linkables)
539 <- upsweep_mods ghci_mode dflags oldUI reachable_from
541 return (restOK, threaded2, mod:modOKs, linkable:linkables)
542 Nothing -- we got a compilation error; give up now
543 -> return (False, threaded1, [], [])
546 -- Compile a single module. Always produce a Linkable for it if
547 -- successful. If no compilation happened, return the old Linkable.
548 upsweep_mod :: GhciMode
554 -> IO (CmThreaded, Maybe Linkable)
556 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_from_here
558 let mod_name = name_of_summary summary1
559 let verb = verbosity dflags
562 if (ghci_mode == Batch)
563 then hPutStr stderr (progName ++ ": module "
564 ++ moduleNameUserString mod_name
566 else hPutStr stderr ("Compiling "
567 ++ moduleNameUserString mod_name
570 let (CmThreaded pcs1 hst1 hit1) = threaded1
571 let old_iface = lookupUFM hit1 mod_name
573 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
575 source_unchanged = isJust maybe_old_linkable
577 (hst1_strictDC, hit1_strictDC)
578 = retainInTopLevelEnvs
579 (filter (/= (name_of_summary summary1)) reachable_from_here)
583 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
585 compresult <- compile ghci_mode summary1 source_unchanged
586 old_iface hst1_strictDC hit1_strictDC pcs1
590 -- Compilation "succeeded", but didn't return a new
591 -- linkable, meaning that compilation wasn't needed, and the
592 -- new details were manufactured from the old iface.
593 CompOK pcs2 new_details new_iface Nothing
594 -> do let hst2 = addToUFM hst1 mod_name new_details
595 hit2 = addToUFM hit1 mod_name new_iface
596 threaded2 = CmThreaded pcs2 hst2 hit2
598 if ghci_mode == Interactive && verb >= 1 then
599 -- if we're using an object file, tell the user
600 case maybe_old_linkable of
601 Just (LM _ _ objs@(DotO _:_))
602 -> do hPutStr stderr (showSDoc (space <>
603 parens (hsep (text "using":
605 [ text o | DotO o <- objs ]))))
606 when (verb > 1) $ hPutStrLn stderr ""
611 when (verb == 1) $ hPutStrLn stderr ""
612 return (threaded2, Just old_linkable)
614 -- Compilation really did happen, and succeeded. A new
615 -- details, iface and linkable are returned.
616 CompOK pcs2 new_details new_iface (Just new_linkable)
617 -> do let hst2 = addToUFM hst1 mod_name new_details
618 hit2 = addToUFM hit1 mod_name new_iface
619 threaded2 = CmThreaded pcs2 hst2 hit2
621 when (verb == 1) $ hPutStrLn stderr ""
622 return (threaded2, Just new_linkable)
624 -- Compilation failed. compile may still have updated
627 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
628 when (verb == 1) $ hPutStrLn stderr ""
629 return (threaded2, Nothing)
631 -- Remove unwanted modules from the top level envs (HST, HIT, UI).
632 removeFromTopLevelEnvs :: [ModuleName]
633 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
634 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
635 removeFromTopLevelEnvs zap_these (hst, hit, ui)
636 = (delListFromUFM hst zap_these,
637 delListFromUFM hit zap_these,
638 filterModuleLinkables (`notElem` zap_these) ui
641 retainInTopLevelEnvs :: [ModuleName]
642 -> (HomeSymbolTable, HomeIfaceTable)
643 -> (HomeSymbolTable, HomeIfaceTable)
644 retainInTopLevelEnvs keep_these (hst, hit)
645 = (retainInUFM hst keep_these,
646 retainInUFM hit keep_these
649 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
650 retainInUFM ufm keys_to_keep
651 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
653 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
655 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
656 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
657 downwards_closure_of_module summaries root
658 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
659 toEdge summ = (name_of_summary summ, ms_allimps summ)
660 res = simple_transitive_closure (map toEdge summaries) [root]
662 --trace (showSDoc (text "DC of mod" <+> ppr root
663 -- <+> text "=" <+> ppr res)) (
667 -- Calculate transitive closures from a set of roots given an adjacency list
668 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
669 simple_transitive_closure graph set
670 = let set2 = nub (concatMap dsts set ++ set)
671 dsts node = fromMaybe [] (lookup node graph)
673 if length set == length set2
675 else simple_transitive_closure graph set2
678 -- Calculate SCCs of the module graph, with or without taking into
679 -- account source imports.
680 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
681 topological_sort include_source_imports summaries
683 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
685 = (summ, name_of_summary summ,
686 (if include_source_imports
687 then ms_srcimps summ else []) ++ ms_imps summ)
689 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
690 mash_edge (summ, m, m_imports)
691 = case lookup m key_map of
692 Nothing -> panic "reverse_topological_sort"
693 Just mk -> (summ, mk,
694 -- ignore imports not from the home package
695 catMaybes (map (flip lookup key_map) m_imports))
697 edges = map toEdge summaries
698 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
699 scc_input = map mash_edge edges
700 sccs = stronglyConnComp scc_input
705 -- Chase downwards from the specified root set, returning summaries
706 -- for all home modules encountered. Only follow source-import
707 -- links. Also returns a Bool to indicate whether any of the roots
709 downsweep :: [FilePath] -> IO ([ModSummary], Bool)
711 = do rootSummaries <- mapM getRootSummary rootNm
713 = any ((=="Main").moduleNameUserString.name_of_summary)
716 <- loop (filter (isHomeModule.ms_mod) rootSummaries)
717 return (all_summaries, a_root_is_Main)
719 getRootSummary :: FilePath -> IO ModSummary
721 | haskellish_file file
722 = do exists <- doesFileExist file
723 if exists then summariseFile file else do
724 throwDyn (OtherError ("can't find file `" ++ file ++ "'"))
726 = do exists <- doesFileExist hs_file
727 if exists then summariseFile hs_file else do
728 exists <- doesFileExist lhs_file
729 if exists then summariseFile lhs_file else do
730 getSummary (mkModuleName file)
732 hs_file = file ++ ".hs"
733 lhs_file = file ++ ".lhs"
735 getSummary :: ModuleName -> IO ModSummary
737 -- | trace ("getSummary: "++ showSDoc (ppr nm)) True
738 = do found <- findModule nm
740 -- Be sure not to use the mod and location passed in to
741 -- summarise for any other purpose -- summarise may change
742 -- the module names in them if name of module /= name of file,
743 -- and put the changed versions in the returned summary.
744 -- These will then conflict with the passed-in versions.
745 Just (mod, location) -> summarise mod location
746 Nothing -> throwDyn (OtherError
747 ("can't find module `"
748 ++ showSDoc (ppr nm) ++ "'"))
750 -- loop invariant: homeSummaries doesn't contain package modules
751 loop :: [ModSummary] -> IO [ModSummary]
753 = do let allImps :: [ModuleName]
754 allImps = (nub . concatMap ms_imps) homeSummaries
755 let allHome -- all modules currently in homeSummaries
756 = map (moduleName.ms_mod) homeSummaries
758 = filter (`notElem` allHome) allImps
760 <- mapM getSummary neededImps
762 = filter (isHomeModule.ms_mod) neededSummaries
763 if null newHomeSummaries
764 then return homeSummaries
765 else loop (newHomeSummaries ++ homeSummaries)
768 -----------------------------------------------------------------------------
769 -- Summarising modules
771 -- We have two types of summarisation:
773 -- * Summarise a file. This is used for the root module passed to
774 -- cmLoadModule. The file is read, and used to determine the root
775 -- module name. The module name may differ from the filename.
777 -- * Summarise a module. We are given a module name, and must provide
778 -- a summary. The finder is used to locate the file in which the module
781 summariseFile :: FilePath -> IO ModSummary
783 = do hspp_fn <- preprocess file
784 modsrc <- readFile hspp_fn
786 let (srcimps,imps,mod_name) = getImports modsrc
787 (path, basename, ext) = splitFilename3 file
790 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
793 <- case ml_hs_file location of
794 Nothing -> return Nothing
795 Just src_fn -> maybe_getModificationTime src_fn
797 return (ModSummary mod
798 location{ml_hspp_file=Just hspp_fn}
802 -- Summarise a module, and pick up source and interface timestamps.
803 summarise :: Module -> ModuleLocation -> IO ModSummary
804 summarise mod location
806 = do let hs_fn = unJust "summarise" (ml_hs_file location)
807 hspp_fn <- preprocess hs_fn
808 modsrc <- readFile hspp_fn
809 let (srcimps,imps,mod_name) = getImports modsrc
812 <- case ml_hs_file location of
813 Nothing -> return Nothing
814 Just src_fn -> maybe_getModificationTime src_fn
816 if mod_name == moduleName mod
818 else throwDyn (OtherError
819 (showSDoc (text "file name does not match module name: "
820 <+> ppr (moduleName mod) <+> text "vs"
823 return (ModSummary mod location{ml_hspp_file=Just hspp_fn}
828 = return (ModSummary mod location [] [] Nothing)
830 maybe_getModificationTime :: FilePath -> IO (Maybe ClockTime)
831 maybe_getModificationTime fn
832 = (do time <- getModificationTime fn
835 (\err -> return Nothing)