2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 {-# OPTIONS -fvia-C #-}
9 cmInit, -- :: GhciMode -> IO CmState
11 cmLoadModule, -- :: CmState -> FilePath -> IO (CmState, [String])
13 cmUnload, -- :: CmState -> DynFlags -> IO CmState
15 cmSetContext, -- :: CmState -> String -> IO CmState
17 cmGetContext, -- :: CmState -> IO String
20 cmInfoThing, -- :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
23 cmRunStmt, -- :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
25 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
26 -- -> IO (CmState, Maybe String)
28 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
30 cmCompileExpr,-- :: CmState -> DynFlags -> String
31 -- -> IO (CmState, Maybe HValue)#endif
33 CmState, emptyCmState -- abstract
37 #include "HsVersions.h"
42 import DriverFlags ( getDynFlags )
43 import DriverState ( v_Output_file )
48 import HscMain ( initPersistentCompilerState, hscThing )
50 import HscMain ( initPersistentCompilerState )
53 import RnEnv ( unQualInScope )
54 import Id ( idType, idName )
55 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
58 import RdrName ( lookupRdrEnv, emptyRdrEnv )
61 import Type ( tidyType )
62 import VarEnv ( emptyTidyEnv )
64 import Unique ( Uniquable )
65 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
66 import ErrUtils ( showPass )
67 import SysTools ( cleanTempFilesExcept )
70 import BasicTypes ( Fixity, defaultFixity )
72 import CmdLineOpts ( DynFlags(..) )
77 import Interpreter ( HValue )
78 import HscMain ( hscStmt )
79 import PrelGHC ( unsafeCoerce# )
85 import Exception ( Exception, try, throwDyn )
88 import Directory ( getModificationTime, doesFileExist )
97 -- Persistent state for the entire system
100 hst :: HomeSymbolTable, -- home symbol table
101 hit :: HomeIfaceTable, -- home interface table
102 ui :: UnlinkedImage, -- the unlinked images
103 mg :: ModuleGraph, -- the module graph
104 gmode :: GhciMode, -- NEVER CHANGES
105 ic :: InteractiveContext, -- command-line binding info
107 pcs :: PersistentCompilerState, -- compile's persistent state
108 pls :: PersistentLinkerState -- link's persistent state
111 emptyCmState :: GhciMode -> Module -> IO CmState
112 emptyCmState gmode mod
113 = do pcs <- initPersistentCompilerState
115 return (CmState { hst = emptySymbolTable,
116 hit = emptyIfaceTable,
120 ic = emptyInteractiveContext mod,
124 emptyInteractiveContext mod
125 = InteractiveContext { ic_module = mod,
126 ic_rn_env = emptyRdrEnv,
127 ic_type_env = emptyTypeEnv }
129 defaultCurrentModuleName = mkModuleName "Prelude"
130 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
133 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
134 emptyUI :: UnlinkedImage
137 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
138 emptyMG :: ModuleGraph
141 -----------------------------------------------------------------------------
142 -- Produce an initial CmState.
144 cmInit :: GhciMode -> IO CmState
146 prel <- moduleNameToModule defaultCurrentModuleName
147 writeIORef defaultCurrentModule prel
148 emptyCmState mode prel
150 -----------------------------------------------------------------------------
151 -- Setting the context doesn't throw away any bindings; the bindings
152 -- we've built up in the InteractiveContext simply move to the new
153 -- module. They always shadow anything in scope in the current context.
155 cmSetContext :: CmState -> String -> IO CmState
156 cmSetContext cmstate str
157 = do let mn = mkModuleName str
158 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
160 m <- case lookup mn modules_loaded of
163 mod <- moduleNameToModule mn
165 then throwDyn (CmdLineError (showSDoc
166 (quotes (ppr (moduleName mod))
167 <+> text "is not currently loaded")))
170 return cmstate{ ic = (ic cmstate){ic_module=m} }
172 cmGetContext :: CmState -> IO String
173 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
175 moduleNameToModule :: ModuleName -> IO Module
176 moduleNameToModule mn
177 = do maybe_stuff <- findModule mn
179 Nothing -> throwDyn (CmdLineError ("can't find module `"
180 ++ moduleNameUserString mn ++ "'"))
181 Just (m,_) -> return m
183 -----------------------------------------------------------------------------
184 -- cmInfoThing: convert a String to a TyThing
186 -- A string may refer to more than one TyThing (eg. a constructor,
187 -- and type constructor), so we return a list of all the possible TyThings.
190 cmInfoThing :: CmState -> DynFlags -> String
191 -> IO (CmState, PrintUnqualified, [(TyThing,Fixity)])
192 cmInfoThing cmstate dflags id
193 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
194 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
195 return (cmstate{ pcs=new_pcs }, unqual, pairs)
197 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
198 unqual = getUnqual pcs hit icontext
200 getFixity :: PersistentCompilerState -> Name -> Fixity
202 | Just iface <- lookupModuleEnv iface_table (nameModule name),
203 Just fixity <- lookupNameEnv (mi_fixities iface) name
207 where iface_table | isHomePackageName name = hit
208 | otherwise = pcs_PIT pcs
211 -----------------------------------------------------------------------------
212 -- cmRunStmt: Run a statement/expr.
216 = CmRunOk [Name] -- names bound by this evaluation
218 | CmRunDeadlocked -- statement deadlocked
219 | CmRunException Exception -- statement raised an exception
221 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
222 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
225 let InteractiveContext {
227 ic_type_env = type_env,
228 ic_module = this_mod } = icontext
230 (new_pcs, maybe_stuff)
231 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
234 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
235 Just (ids, _, bcos) -> do
237 -- update the interactive context
239 names = map idName ids
241 -- these names have just been shadowed
242 shadowed = [ n | r <- map nameRdrName names,
243 Just n <- [lookupRdrEnv rn_env r] ]
245 new_rn_env = extendLocalRdrEnv rn_env names
247 -- remove any shadowed bindings from the type_env
248 filtered_type_env = delListFromNameEnv type_env shadowed
250 new_type_env = extendNameEnvList filtered_type_env
251 [ (getName id, AnId id) | id <- ids]
253 new_ic = icontext { ic_rn_env = new_rn_env,
254 ic_type_env = new_type_env }
257 hval <- linkExpr pls bcos
260 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
261 either_hvals <- sandboxIO thing_to_run
265 -> return ( cmstate{ pcs=new_pcs, ic=new_ic },
268 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
269 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
274 return ( cmstate{ pcs=new_pcs, ic=new_ic },
277 -- Get the newly bound things, and bind them.
278 -- Don't forget to delete any shadowed bindings from the
279 -- closure_env, lest we end up with a space leak.
280 pls <- delListFromClosureEnv pls shadowed
281 new_pls <- addListToClosureEnv pls (zip names hvals)
283 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
286 -- We run the statement in a "sandbox", which amounts to calling into
287 -- the RTS to request a new main thread. The main benefit is that we
288 -- get to detect a deadlock this way, but also there's no danger that
289 -- exceptions raised by the expression can affect the interpreter.
291 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
293 st_thing <- newStablePtr (Exception.try thing)
294 alloca $ \ p_st_result -> do
295 stat <- rts_evalStableIO st_thing p_st_result
296 freeStablePtr st_thing
298 then do st_result <- peek p_st_result
299 result <- deRefStablePtr st_result
300 freeStablePtr st_result
301 return (Right result)
303 return (Left (fromIntegral stat))
305 -- ToDo: slurp this in from ghc/includes/RtsAPI.h somehow
306 dEADLOCKED = 4 :: Int
308 foreign import "rts_evalStableIO" {- safe -}
309 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
310 -- more informative than the C type!
313 -----------------------------------------------------------------------------
314 -- cmTypeOfExpr: returns a string representing the type of an expression
317 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
318 cmTypeOfExpr cmstate dflags expr
319 = do (new_pcs, maybe_stuff)
320 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
322 let new_cmstate = cmstate{pcs = new_pcs}
325 Nothing -> return (new_cmstate, Nothing)
326 Just (_, ty, _) -> return (new_cmstate, Just str)
328 str = showSDocForUser unqual (ppr tidy_ty)
329 unqual = getUnqual pcs hit ic
330 tidy_ty = tidyType emptyTidyEnv ty
332 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
336 = case lookupIfaceByModName hit pit modname of
337 Nothing -> alwaysQualify
338 Just iface -> unQualInScope (mi_globals iface)
341 modname = moduleName (ic_module ic)
343 -----------------------------------------------------------------------------
344 -- cmTypeOfName: returns a string representing the type of a name.
347 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
348 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
349 = case lookupNameEnv (ic_type_env ic) name of
350 Nothing -> return Nothing
351 Just (AnId id) -> return (Just str)
353 unqual = getUnqual pcs hit ic
354 ty = tidyType emptyTidyEnv (idType id)
355 str = showSDocForUser unqual (ppr ty)
357 _ -> panic "cmTypeOfName"
360 -----------------------------------------------------------------------------
361 -- cmCompileExpr: compile an expression and deliver an HValue
364 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
365 cmCompileExpr cmstate dflags expr
367 let InteractiveContext {
369 ic_type_env = type_env,
370 ic_module = this_mod } = icontext
372 (new_pcs, maybe_stuff)
373 <- hscStmt dflags hst hit pcs icontext
374 ("let __cmCompileExpr = "++expr) False{-stmt-}
377 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
378 Just (ids, _, bcos) -> do
381 hval <- linkExpr pls bcos
384 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
385 hvals <- thing_to_run
388 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
389 _ -> panic "cmCompileExpr"
392 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
395 -----------------------------------------------------------------------------
396 -- cmInfo: return "info" about an expression. The info might be:
398 -- * its type, for an expression,
399 -- * the class definition, for a class
400 -- * the datatype definition, for a tycon (or synonym)
401 -- * the export list, for a module
403 -- Can be used to find the type of the last expression compiled, by looking
406 cmInfo :: CmState -> String -> IO (Maybe String)
408 = do error "cmInfo not implemented yet"
410 -----------------------------------------------------------------------------
411 -- Unload the compilation manager's state: everything it knows about the
412 -- current collection of modules in the Home package.
414 cmUnload :: CmState -> DynFlags -> IO CmState
415 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
416 = do -- Throw away the old home dir cache
419 -- Unload everything the linker knows about
420 new_pls <- CmLink.unload mode dflags [] pls
422 -- Start with a fresh CmState, but keep the PersistentCompilerState
423 new_state <- cmInit mode
424 return new_state{ pcs=pcs, pls=new_pls }
426 -----------------------------------------------------------------------------
427 -- The real business of the compilation manager: given a system state and
428 -- a module name, try and bring the module up to date, probably changing
429 -- the system state at the same time.
431 cmLoadModule :: CmState
433 -> IO (CmState, -- new state
434 Bool, -- was successful
435 [String]) -- list of modules loaded
437 cmLoadModule cmstate1 rootnames
438 = do -- version 1's are the original, before downsweep
439 let pls1 = pls cmstate1
440 let pcs1 = pcs cmstate1
441 let hst1 = hst cmstate1
442 let hit1 = hit cmstate1
443 -- similarly, ui1 is the (complete) set of linkables from
444 -- the previous pass, if any.
445 let ui1 = ui cmstate1
446 let mg1 = mg cmstate1
447 let ic1 = ic cmstate1
449 let ghci_mode = gmode cmstate1 -- this never changes
451 -- Do the downsweep to reestablish the module graph
452 dflags <- getDynFlags
453 let verb = verbosity dflags
455 showPass dflags "Chasing dependencies"
456 when (verb >= 1 && ghci_mode == Batch) $
457 hPutStrLn stderr (showSDoc (hcat [
458 text progName, text ": chasing modules from: ",
459 hcat (punctuate comma (map text rootnames))]))
461 (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
462 let mg2unsorted_names = map name_of_summary mg2unsorted
464 -- reachable_from follows source as well as normal imports
465 let reachable_from :: ModuleName -> [ModuleName]
466 reachable_from = downwards_closure_of_module mg2unsorted
468 -- should be cycle free; ignores 'import source's
469 let mg2 = topological_sort False mg2unsorted
470 -- ... whereas this takes them into account. Used for
471 -- backing out partially complete cycles following a failed
472 -- upsweep, and for removing from hst/hit all the modules
473 -- not in strict downwards closure, during calls to compile.
474 let mg2_with_srcimps = topological_sort True mg2unsorted
476 -- Sort out which linkables we wish to keep in the unlinked image.
477 -- See getValidLinkables below for details.
478 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
480 -- when (verb >= 2) $
481 -- putStrLn (showSDoc (text "Valid linkables:"
482 -- <+> ppr valid_linkables))
484 -- Figure out a stable set of modules which can be retained
485 -- the top level envs, to avoid upsweeping them. Goes to a
486 -- bit of trouble to avoid upsweeping module cycles.
488 -- Construct a set S of stable modules like this:
489 -- Travel upwards, over the sccified graph. For each scc
490 -- of modules ms, add ms to S only if:
491 -- 1. All home imports of ms are either in ms or S
492 -- 2. A valid linkable exists for each module in ms
494 stable_mods <- preUpsweep valid_linkables hit1
495 mg2unsorted_names [] mg2_with_srcimps
498 = concatMap (findInSummaries mg2unsorted) stable_mods
501 = filter (\m -> linkableModName m `elem` stable_mods)
505 putStrLn (showSDoc (text "Stable modules:"
506 <+> sep (map (text.moduleNameUserString) stable_mods)))
508 -- unload any modules which aren't going to be re-linked this
510 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
512 -- We could at this point detect cycles which aren't broken by
513 -- a source-import, and complain immediately, but it seems better
514 -- to let upsweep_mods do this, so at least some useful work gets
515 -- done before the upsweep is abandoned.
517 = filter (\scc -> any (`notElem` stable_mods)
518 (map name_of_summary (flattenSCC scc)))
521 --hPutStrLn stderr "after tsort:\n"
522 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
524 -- Because we don't take into account source imports when doing
525 -- the topological sort, there shouldn't be any cycles in mg2.
526 -- If there is, we complain and give up -- the user needs to
527 -- break the cycle using a boot file.
529 -- Now do the upsweep, calling compile for each module in
530 -- turn. Final result is version 3 of everything.
532 let threaded2 = CmThreaded pcs1 hst1 hit1
534 -- clean up between compilations
535 let cleanup = cleanTempFilesExcept verb
536 (ppFilesFromSummaries (flattenSCCs upsweep_these))
538 (upsweep_complete_success, threaded3, modsUpswept, newLis)
539 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
540 threaded2 cleanup upsweep_these
542 let ui3 = add_to_ui valid_linkables newLis
543 let (CmThreaded pcs3 hst3 hit3) = threaded3
545 -- At this point, modsUpswept and newLis should have the same
546 -- length, so there is one new (or old) linkable for each
547 -- mod which was processed (passed to compile).
549 -- Make modsDone be the summaries for each home module now
550 -- available; this should equal the domains of hst3 and hit3.
551 -- (NOT STRICTLY TRUE if an interactive session was started
552 -- with some object on disk ???)
553 -- Get in in a roughly top .. bottom order (hence reverse).
555 let modsDone = reverse modsUpswept ++ stable_summaries
557 -- Try and do linking in some form, depending on whether the
558 -- upsweep was completely or only partially successful.
560 if upsweep_complete_success
563 -- Easy; just relink it all.
564 do when (verb >= 2) $
565 hPutStrLn stderr "Upsweep completely successful."
567 -- clean up after ourselves
568 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
570 -- issue a warning for the confusing case where the user said '-o foo'
571 -- but we're not going to do any linking.
572 ofile <- readIORef v_Output_file
573 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
575 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
577 -- link everything together
578 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
580 cmLoadFinish True linkresult
581 hst3 hit3 ui3 modsDone ghci_mode pcs3
584 -- Tricky. We need to back out the effects of compiling any
585 -- half-done cycles, both so as to clean up the top level envs
586 -- and to avoid telling the interactive linker to link them.
587 do when (verb >= 2) $
588 hPutStrLn stderr "Upsweep partially successful."
591 = map name_of_summary modsDone
592 let mods_to_zap_names
593 = findPartiallyCompletedCycles modsDone_names
596 = filter ((`notElem` mods_to_zap_names).name_of_summary)
599 let (hst4, hit4, ui4)
600 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
603 -- clean up after ourselves
604 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
606 -- link everything together
607 linkresult <- link ghci_mode dflags False ui4 pls2
609 cmLoadFinish False linkresult
610 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
613 -- Finish up after a cmLoad.
615 -- If the link failed, unload everything and return.
616 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
617 dflags <- getDynFlags
618 new_pls <- CmLink.unload ghci_mode dflags [] pls
619 new_state <- cmInit ghci_mode
620 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
622 -- Empty the interactive context and set the module context to the topmost
623 -- newly loaded module, or the Prelude if none were loaded.
624 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
625 = do def_mod <- readIORef defaultCurrentModule
626 let current_mod = case mods of
630 new_ic = emptyInteractiveContext current_mod
632 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
633 gmode=ghci_mode, pcs=pcs, pls=pls,
635 mods_loaded = map (moduleNameUserString.name_of_summary) mods
637 return (new_cmstate, ok, mods_loaded)
639 -- used to fish out the preprocess output files for the purposes
641 ppFilesFromSummaries summaries
642 = [ fn | Just fn <- map toPpFile summaries ]
645 | hspp /= ml_hs_file loc = hspp
646 | otherwise = Nothing
648 loc = ms_location sum
649 hspp = ml_hspp_file loc
652 -----------------------------------------------------------------------------
655 -- For each module (or SCC of modules), we take:
657 -- - an on-disk linkable, if this is the first time around and one
660 -- - the old linkable, otherwise (and if one is available).
662 -- and we throw away the linkable if it is older than the source
663 -- file. We ignore the on-disk linkables unless all of the dependents
664 -- of this SCC also have on-disk linkables.
666 -- If a module has a valid linkable, then it may be STABLE (see below),
667 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
670 -- ToDo: this pass could be merged with the preUpsweep.
673 :: [Linkable] -- old linkables
674 -> [ModuleName] -- all home modules
675 -> [SCC ModSummary] -- all modules in the program, dependency order
676 -> IO [Linkable] -- still-valid linkables
678 getValidLinkables old_linkables all_home_mods module_graph
679 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
681 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
683 scc = flattenSCC scc0
684 scc_names = map name_of_summary scc
685 home_module m = m `elem` all_home_mods && m `notElem` scc_names
686 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
687 -- NOTE: ms_imps, not ms_allimps above. We don't want to
688 -- force a module's SOURCE imports to be already compiled for
689 -- its object linkable to be valid.
691 has_object m = case findModuleLinkable_maybe new_linkables m of
693 Just l -> isObjectLinkable l
695 objects_allowed = all has_object scc_allhomeimps
699 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
701 -- since an scc can contain only all objects or no objects at all,
702 -- we have to check whether we got all objects or not, and re-do
703 -- the linkable check if not.
705 <- if objects_allowed && not (all isObjectLinkable these_linkables)
706 then foldM (getValidLinkable old_linkables False) [] scc
707 else return these_linkables
709 return (adjusted_linkables ++ new_linkables)
712 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
714 getValidLinkable old_linkables objects_allowed new_linkables summary
715 = do let mod_name = name_of_summary summary
718 <- if (not objects_allowed)
720 else case ml_obj_file (ms_location summary) of
721 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
722 Nothing -> return Nothing
724 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
727 Just l | not (isObjectLinkable l) || stillThere l
729 -- ToDo: emit a warning if not (stillThere l)
732 -- make sure that if we had an old disk linkable around, that it's
733 -- still there on the disk (in case we need to re-link it).
735 case maybe_disk_linkable of
737 Just l_disk -> linkableTime l == linkableTime l_disk
739 -- we only look for objects on disk the first time around;
740 -- if the user compiles a module on the side during a GHCi session,
741 -- it won't be picked up until the next ":load". This is what the
742 -- "null old_linkables" test below is.
743 linkable | null old_linkables = maybeToList maybe_disk_linkable
744 | otherwise = maybeToList maybe_old_linkable
746 -- only linkables newer than the source code are valid
747 src_date = ms_hs_date summary
750 = filter (\l -> linkableTime l >= src_date) linkable
751 -- why '>=' rather than '>' above? If the filesystem stores
752 -- times to the nearset second, we may occasionally find that
753 -- the object & source have the same modification time,
754 -- especially if the source was automatically generated
755 -- and compiled. Using >= is slightly unsafe, but it matches
758 return (valid_linkable ++ new_linkables)
761 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
762 maybe_getFileLinkable mod_name obj_fn
763 = do obj_exist <- doesFileExist obj_fn
767 do let stub_fn = case splitFilename3 obj_fn of
768 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
769 stub_exist <- doesFileExist stub_fn
770 obj_time <- getModificationTime obj_fn
772 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
773 else return (Just (LM obj_time mod_name [DotO obj_fn]))
776 -----------------------------------------------------------------------------
777 -- Do a pre-upsweep without use of "compile", to establish a
778 -- (downward-closed) set of stable modules for which we won't call compile.
781 -- * has a valid linkable (see getValidLinkables above)
782 -- * depends only on stable modules
783 -- * has an interface in the HIT (interactive mode only)
785 preUpsweep :: [Linkable] -- new valid linkables
787 -> [ModuleName] -- names of all mods encountered in downsweep
788 -> [ModuleName] -- accumulating stable modules
789 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
790 -> IO [ModuleName] -- stable modules
792 preUpsweep valid_lis hit all_home_mods stable [] = return stable
793 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
794 = do let scc = flattenSCC scc0
795 scc_allhomeimps :: [ModuleName]
797 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
798 all_imports_in_scc_or_stable
799 = all in_stable_or_scc scc_allhomeimps
801 = map name_of_summary scc
803 = m `elem` scc_names || m `elem` stable
805 -- now we check for valid linkables: each module in the SCC must
806 -- have a valid linkable (see getValidLinkables above).
807 has_valid_linkable new_summary
808 = isJust (findModuleLinkable_maybe valid_lis modname)
809 where modname = name_of_summary new_summary
811 has_interface summary = ms_mod summary `elemUFM` hit
813 scc_is_stable = all_imports_in_scc_or_stable
814 && all has_valid_linkable scc
815 && all has_interface scc
818 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
819 else preUpsweep valid_lis hit all_home_mods stable sccs
822 -- Helper for preUpsweep. Assuming that new_summary's imports are all
823 -- stable (in the sense of preUpsweep), determine if new_summary is itself
824 -- stable, and, if so, in batch mode, return its linkable.
825 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
826 findInSummaries old_summaries mod_name
827 = [s | s <- old_summaries, name_of_summary s == mod_name]
829 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
830 findModInSummaries old_summaries mod
831 = case [s | s <- old_summaries, ms_mod s == mod] of
835 -- Return (names of) all those in modsDone who are part of a cycle
836 -- as defined by theGraph.
837 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
838 findPartiallyCompletedCycles modsDone theGraph
842 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
843 chew ((CyclicSCC vs):rest)
844 = let names_in_this_cycle = nub (map name_of_summary vs)
846 = nub ([done | done <- modsDone,
847 done `elem` names_in_this_cycle])
848 chewed_rest = chew rest
850 if not (null mods_in_this_cycle)
851 && length mods_in_this_cycle < length names_in_this_cycle
852 then mods_in_this_cycle ++ chewed_rest
856 -- Add the given (LM-form) Linkables to the UI, overwriting previous
857 -- versions if they exist.
858 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
860 = filter (not_in lis) ui ++ lis
862 not_in :: [Linkable] -> Linkable -> Bool
864 = all (\l -> linkableModName l /= mod) lis
865 where mod = linkableModName li
868 data CmThreaded -- stuff threaded through individual module compilations
869 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
872 -- Compile multiple modules, stopping as soon as an error appears.
873 -- There better had not be any cyclic groups here -- we check for them.
874 upsweep_mods :: GhciMode
876 -> UnlinkedImage -- valid linkables
877 -> (ModuleName -> [ModuleName]) -- to construct downward closures
878 -> CmThreaded -- PCS & HST & HIT
879 -> IO () -- how to clean up unwanted tmp files
880 -> [SCC ModSummary] -- mods to do (the worklist)
881 -- ...... RETURNING ......
882 -> IO (Bool{-complete success?-},
884 [ModSummary], -- mods which succeeded
885 [Linkable]) -- new linkables
887 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
889 = return (True, threaded, [], [])
891 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
893 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
894 unwords (map (moduleNameUserString.name_of_summary) ms))
895 return (False, threaded, [], [])
897 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
898 ((AcyclicSCC mod):mods)
899 = do --case threaded of
900 -- CmThreaded pcsz hstz hitz
901 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
903 (threaded1, maybe_linkable)
904 <- upsweep_mod ghci_mode dflags oldUI threaded mod
905 (reachable_from (name_of_summary mod))
907 -- remove unwanted tmp files between compilations
910 case maybe_linkable of
912 -> -- No errors; do the rest
913 do (restOK, threaded2, modOKs, linkables)
914 <- upsweep_mods ghci_mode dflags oldUI reachable_from
915 threaded1 cleanup mods
916 return (restOK, threaded2, mod:modOKs, linkable:linkables)
917 Nothing -- we got a compilation error; give up now
918 -> return (False, threaded1, [], [])
921 -- Compile a single module. Always produce a Linkable for it if
922 -- successful. If no compilation happened, return the old Linkable.
923 upsweep_mod :: GhciMode
929 -> IO (CmThreaded, Maybe Linkable)
931 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
933 let mod_name = name_of_summary summary1
934 let verb = verbosity dflags
936 let (CmThreaded pcs1 hst1 hit1) = threaded1
937 let old_iface = lookupUFM hit1 mod_name
939 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
941 source_unchanged = isJust maybe_old_linkable
943 reachable_only = filter (/= (name_of_summary summary1))
946 -- in interactive mode, all home modules below us *must* have an
947 -- interface in the HIT. We never demand-load home interfaces in
949 (hst1_strictDC, hit1_strictDC, [])
950 = ASSERT(ghci_mode == Batch ||
951 all (`elemUFM` hit1) reachable_only)
952 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
955 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
958 | Just l <- maybe_old_linkable, isObjectLinkable l = True
961 compresult <- compile ghci_mode summary1 source_unchanged
962 have_object old_iface hst1_strictDC hit1_strictDC pcs1
966 -- Compilation "succeeded", and may or may not have returned a new
967 -- linkable (depending on whether compilation was actually performed
969 CompOK pcs2 new_details new_iface maybe_new_linkable
970 -> do let hst2 = addToUFM hst1 mod_name new_details
971 hit2 = addToUFM hit1 mod_name new_iface
972 threaded2 = CmThreaded pcs2 hst2 hit2
974 return (threaded2, if isJust maybe_new_linkable
975 then maybe_new_linkable
976 else Just old_linkable)
978 -- Compilation failed. compile may still have updated
981 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
982 return (threaded2, Nothing)
984 -- Filter modules in the top level envs (HST, HIT, UI).
985 retainInTopLevelEnvs :: [ModuleName]
986 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
987 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
988 retainInTopLevelEnvs keep_these (hst, hit, ui)
989 = (retainInUFM hst keep_these,
990 retainInUFM hit keep_these,
991 filterModuleLinkables (`elem` keep_these) ui
994 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
995 retainInUFM ufm keys_to_keep
996 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
998 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1000 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1001 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1002 downwards_closure_of_module summaries root
1003 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1004 toEdge summ = (name_of_summary summ,
1005 filter (`elem` all_mods) (ms_allimps summ))
1007 all_mods = map name_of_summary summaries
1009 res = simple_transitive_closure (map toEdge summaries) [root]
1011 -- trace (showSDoc (text "DC of mod" <+> ppr root
1012 -- <+> text "=" <+> ppr res)) $
1015 -- Calculate transitive closures from a set of roots given an adjacency list
1016 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1017 simple_transitive_closure graph set
1018 = let set2 = nub (concatMap dsts set ++ set)
1019 dsts node = fromMaybe [] (lookup node graph)
1021 if length set == length set2
1023 else simple_transitive_closure graph set2
1026 -- Calculate SCCs of the module graph, with or without taking into
1027 -- account source imports.
1028 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1029 topological_sort include_source_imports summaries
1031 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1033 = (summ, name_of_summary summ,
1034 (if include_source_imports
1035 then ms_srcimps summ else []) ++ ms_imps summ)
1037 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1038 mash_edge (summ, m, m_imports)
1039 = case lookup m key_map of
1040 Nothing -> panic "reverse_topological_sort"
1041 Just mk -> (summ, mk,
1042 -- ignore imports not from the home package
1043 catMaybes (map (flip lookup key_map) m_imports))
1045 edges = map toEdge summaries
1046 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1047 scc_input = map mash_edge edges
1048 sccs = stronglyConnComp scc_input
1053 -- Chase downwards from the specified root set, returning summaries
1054 -- for all home modules encountered. Only follow source-import
1055 -- links. Also returns a Bool to indicate whether any of the roots
1057 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
1058 downsweep rootNm old_summaries
1059 = do rootSummaries <- mapM getRootSummary rootNm
1061 = any ((=="Main").moduleNameUserString.name_of_summary)
1064 <- loop (concat (map ms_imps rootSummaries))
1065 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1066 let mod = ms_mod s, isHomeModule mod
1068 return (all_summaries, a_root_is_Main)
1070 getRootSummary :: FilePath -> IO ModSummary
1072 | haskellish_src_file file
1073 = do exists <- doesFileExist file
1074 if exists then summariseFile file else do
1075 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1077 = do exists <- doesFileExist hs_file
1078 if exists then summariseFile hs_file else do
1079 exists <- doesFileExist lhs_file
1080 if exists then summariseFile lhs_file else do
1081 let mod_name = mkModuleName file
1082 maybe_summary <- getSummary mod_name
1083 case maybe_summary of
1084 Nothing -> packageModErr mod_name
1087 hs_file = file ++ ".hs"
1088 lhs_file = file ++ ".lhs"
1090 getSummary :: ModuleName -> IO (Maybe ModSummary)
1092 = do found <- findModule nm
1094 Just (mod, location) -> do
1095 let old_summary = findModInSummaries old_summaries mod
1096 summarise mod location old_summary
1098 Nothing -> throwDyn (CmdLineError
1099 ("can't find module `"
1100 ++ showSDoc (ppr nm) ++ "'"))
1102 -- loop invariant: env doesn't contain package modules
1103 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1104 loop [] env = return (moduleEnvElts env)
1106 = do -- imports for modules we don't already have
1107 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1110 needed_summaries <- mapM getSummary needed_imps
1112 -- get just the "home" modules
1113 let new_home_summaries = [ s | Just s <- needed_summaries ]
1115 -- loop, checking the new imports
1116 let new_imps = concat (map ms_imps new_home_summaries)
1117 loop new_imps (extendModuleEnvList env
1118 [ (ms_mod s, s) | s <- new_home_summaries ])
1120 -----------------------------------------------------------------------------
1121 -- Summarising modules
1123 -- We have two types of summarisation:
1125 -- * Summarise a file. This is used for the root module passed to
1126 -- cmLoadModule. The file is read, and used to determine the root
1127 -- module name. The module name may differ from the filename.
1129 -- * Summarise a module. We are given a module name, and must provide
1130 -- a summary. The finder is used to locate the file in which the module
1133 summariseFile :: FilePath -> IO ModSummary
1135 = do hspp_fn <- preprocess file
1136 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1138 let (path, basename, ext) = splitFilename3 file
1141 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1144 <- case ml_hs_file location of
1145 Nothing -> noHsFileErr mod_name
1146 Just src_fn -> getModificationTime src_fn
1148 return (ModSummary mod
1149 location{ml_hspp_file=Just hspp_fn}
1150 srcimps imps src_timestamp)
1152 -- Summarise a module, and pick up source and timestamp.
1153 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1154 -> IO (Maybe ModSummary)
1155 summarise mod location old_summary
1156 | not (isHomeModule mod) = return Nothing
1158 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1160 case ml_hs_file location of {
1161 Nothing -> noHsFileErr mod;
1164 src_timestamp <- getModificationTime src_fn
1166 -- return the cached summary if the source didn't change
1167 case old_summary of {
1168 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1171 hspp_fn <- preprocess hs_fn
1172 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1174 when (mod_name /= moduleName mod) $
1175 throwDyn (ProgramError
1176 (showSDoc (text hs_fn
1177 <> text ": file name does not match module name"
1178 <+> quotes (ppr (moduleName mod)))))
1180 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1181 srcimps imps src_timestamp))
1187 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1190 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1191 quotes (ppr mod) <+>
1192 text "is a package module")))