2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
7 {-# OPTIONS -fvia-C #-}
11 CmState, emptyCmState, -- abstract
13 cmInit, -- :: GhciMode -> IO CmState
15 cmDepAnal, -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
17 cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
18 -- -> IO (CmState, Bool, [String])
20 cmUnload, -- :: CmState -> DynFlags -> IO CmState
23 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
25 cmSetContext, -- :: CmState -> DynFlags -> [String] -> [String] -> IO CmState
26 cmGetContext, -- :: CmState -> IO ([String],[String])
28 cmInfoThing, -- :: CmState -> DynFlags -> String
29 -- -> IO (CmState, [(TyThing,Fixity)])
31 cmBrowseModule, -- :: CmState -> IO [TyThing]
34 cmRunStmt, -- :: CmState -> DynFlags -> String
35 -- -> IO (CmState, CmRunResult)
37 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
38 -- -> IO (CmState, Maybe String)
40 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
43 cmCompileExpr, -- :: CmState -> DynFlags -> String
44 -- -> IO (CmState, Maybe HValue)
46 cmGetModuleGraph, -- :: CmState -> ModuleGraph
47 cmGetLinkables, -- :: CmState -> [Linkable]
49 cmGetBindings, -- :: CmState -> [TyThing]
50 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
58 #include "HsVersions.h"
66 import DriverState ( v_Output_file )
71 import HscMain ( initPersistentCompilerState, hscThing,
74 import HscMain ( initPersistentCompilerState )
76 import HscTypes hiding ( moduleNameToModule )
77 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
78 isHomePackageName, isExternalName )
80 import PrelNames ( gHC_PRIM_Name )
81 import Rename ( mkGlobalContext )
82 import RdrName ( emptyRdrEnv )
86 import Unique ( Uniquable )
87 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
88 import ErrUtils ( showPass )
89 import SysTools ( cleanTempFilesExcept )
93 import CmdLineOpts ( DynFlags(..), getDynFlags )
94 import Maybes ( expectJust )
99 import RdrName ( lookupRdrEnv )
100 import Id ( idType, idName )
101 import Type ( tidyType )
102 import VarEnv ( emptyTidyEnv )
103 import BasicTypes ( Fixity, defaultFixity )
104 import Interpreter ( HValue )
105 import HscMain ( hscStmt )
106 import GlaExts ( unsafeCoerce# )
109 import Exception ( Exception, try )
113 import Exception ( throwDyn )
116 import Directory ( getModificationTime, doesFileExist )
125 -- Persistent state for the entire system
128 hst :: HomeSymbolTable, -- home symbol table
129 hit :: HomeIfaceTable, -- home interface table
130 ui :: UnlinkedImage, -- the unlinked images
131 mg :: ModuleGraph, -- the module graph
132 gmode :: GhciMode, -- NEVER CHANGES
133 ic :: InteractiveContext, -- command-line binding info
135 pcs :: PersistentCompilerState, -- compile's persistent state
136 pls :: PersistentLinkerState -- link's persistent state
139 emptyCmState :: GhciMode -> IO CmState
141 = do pcs <- initPersistentCompilerState
143 return (CmState { hst = emptySymbolTable,
144 hit = emptyIfaceTable,
148 ic = emptyInteractiveContext,
152 emptyInteractiveContext
153 = InteractiveContext { ic_toplev_scope = [],
155 ic_rn_gbl_env = emptyRdrEnv,
156 ic_print_unqual = alwaysQualify,
157 ic_rn_local_env = emptyRdrEnv,
158 ic_type_env = emptyTypeEnv }
161 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
162 emptyUI :: UnlinkedImage
165 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
166 emptyMG :: ModuleGraph
169 -----------------------------------------------------------------------------
170 -- Produce an initial CmState.
172 cmInit :: GhciMode -> IO CmState
173 cmInit mode = emptyCmState mode
175 -----------------------------------------------------------------------------
176 -- Grab information from the CmState
178 cmGetModuleGraph = mg
181 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
182 cmGetPrintUnqual cmstate = ic_print_unqual (ic cmstate)
184 -----------------------------------------------------------------------------
185 -- Setting the context doesn't throw away any bindings; the bindings
186 -- we've built up in the InteractiveContext simply move to the new
187 -- module. They always shadow anything in scope in the current context.
190 :: CmState -> DynFlags
191 -> [String] -- take the top-level scopes of these modules
192 -> [String] -- and the just the exports from these
194 cmSetContext cmstate dflags toplevs exports = do
195 let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
197 toplev_mods <- mapM (getTopLevModule hit) (map mkModuleName toplevs)
198 export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
200 (new_pcs, print_unqual, maybe_env)
201 <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
204 Nothing -> return cmstate
205 Just env -> return cmstate{ pcs = new_pcs,
206 ic = old_ic{ ic_toplev_scope = toplev_mods,
207 ic_exports = export_mods,
209 ic_print_unqual = print_unqual } }
211 getTopLevModule hit mn =
212 case lookupModuleEnvByName hit mn of
214 | Just _ <- mi_globals iface -> return (mi_module iface)
215 _other -> throwDyn (CmdLineError (
216 "cannot enter the top-level scope of a compiled module (module `" ++
217 moduleNameUserString mn ++ "')"))
219 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
220 moduleNameToModule hit mn = do
221 case lookupModuleEnvByName hit mn of
222 Just iface -> return (mi_module iface)
223 _not_a_home_module -> do
224 maybe_stuff <- findModule mn
226 Nothing -> throwDyn (CmdLineError ("can't find module `"
227 ++ moduleNameUserString mn ++ "'"))
228 Just (m,_) -> return m
230 cmGetContext :: CmState -> IO ([String],[String])
231 cmGetContext CmState{ic=ic} =
232 return (map moduleUserString (ic_toplev_scope ic),
233 map moduleUserString (ic_exports ic))
235 cmModuleIsInterpreted :: CmState -> String -> IO Bool
236 cmModuleIsInterpreted cmstate str
237 = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
238 Just iface -> return (not (isNothing (mi_globals iface)))
239 _not_a_home_module -> return False
241 -----------------------------------------------------------------------------
242 -- cmInfoThing: convert a String to a TyThing
244 -- A string may refer to more than one TyThing (eg. a constructor,
245 -- and type constructor), so we return a list of all the possible TyThings.
248 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
249 cmInfoThing cmstate dflags id
250 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
251 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
252 return (cmstate{ pcs=new_pcs }, pairs)
254 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
256 getFixity :: PersistentCompilerState -> Name -> Fixity
258 | isExternalName name,
259 Just iface <- lookupModuleEnv iface_table (nameModule name),
260 Just fixity <- lookupNameEnv (mi_fixities iface) name
264 where iface_table | isHomePackageName name = hit
265 | otherwise = pcs_PIT pcs
268 -- ---------------------------------------------------------------------------
269 -- cmBrowseModule: get all the TyThings defined in a module
272 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
273 -> IO (CmState, [TyThing])
274 cmBrowseModule cmstate dflags str exports_only = do
275 let mn = mkModuleName str
276 mod <- moduleNameToModule hit mn
277 (pcs1, maybe_ty_things)
278 <- hscModuleContents dflags hst hit pcs mod exports_only
279 case maybe_ty_things of
280 Nothing -> return (cmstate{pcs=pcs1}, [])
281 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
283 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
286 -----------------------------------------------------------------------------
287 -- cmRunStmt: Run a statement/expr.
291 = CmRunOk [Name] -- names bound by this evaluation
293 | CmRunException Exception -- statement raised an exception
295 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
296 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
299 let InteractiveContext {
300 ic_rn_local_env = rn_env,
301 ic_type_env = type_env } = icontext
303 (new_pcs, maybe_stuff)
304 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
307 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
308 Just (ids, _, bcos) -> do
310 -- update the interactive context
312 names = map idName ids
314 -- these names have just been shadowed
315 shadowed = [ n | r <- map nameRdrName names,
316 Just n <- [lookupRdrEnv rn_env r] ]
318 new_rn_env = extendLocalRdrEnv rn_env names
320 -- remove any shadowed bindings from the type_env
321 filtered_type_env = delListFromNameEnv type_env shadowed
323 new_type_env = extendNameEnvList filtered_type_env
324 [ (getName id, AnId id) | id <- ids]
326 new_ic = icontext { ic_rn_local_env = new_rn_env,
327 ic_type_env = new_type_env }
330 hval <- linkExpr pls bcos
333 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
334 either_hvals <- sandboxIO thing_to_run
337 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
338 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
343 return ( cmstate{ pcs=new_pcs, ic=new_ic },
346 -- Get the newly bound things, and bind them.
347 -- Don't forget to delete any shadowed bindings from the
348 -- closure_env, lest we end up with a space leak.
349 pls <- delListFromClosureEnv pls shadowed
350 new_pls <- addListToClosureEnv pls (zip names hvals)
352 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
356 -- We run the statement in a "sandbox" to protect the rest of the
357 -- system from anything the expression might do. For now, this
358 -- consists of just wrapping it in an exception handler, but see below
359 -- for another version.
361 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
363 r <- Exception.try thing
367 -- This version of sandboxIO runs the expression in a completely new
368 -- RTS main thread. It is disabled for now because ^C exceptions
369 -- won't be delivered to the new thread, instead they'll be delivered
370 -- to the (blocked) GHCi main thread.
372 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
374 st_thing <- newStablePtr (Exception.try thing)
375 alloca $ \ p_st_result -> do
376 stat <- rts_evalStableIO st_thing p_st_result
377 freeStablePtr st_thing
379 then do st_result <- peek p_st_result
380 result <- deRefStablePtr st_result
381 freeStablePtr st_result
382 return (Right result)
384 return (Left (fromIntegral stat))
386 foreign import "rts_evalStableIO" {- safe -}
387 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
388 -- more informative than the C type!
392 -----------------------------------------------------------------------------
393 -- cmTypeOfExpr: returns a string representing the type of an expression
396 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
397 cmTypeOfExpr cmstate dflags expr
398 = do (new_pcs, maybe_stuff)
399 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
401 let new_cmstate = cmstate{pcs = new_pcs}
404 Nothing -> return (new_cmstate, Nothing)
405 Just (_, ty, _) -> return (new_cmstate, Just str)
407 str = showSDocForUser unqual (ppr tidy_ty)
408 unqual = ic_print_unqual ic
409 tidy_ty = tidyType emptyTidyEnv ty
411 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
414 -----------------------------------------------------------------------------
415 -- cmTypeOfName: returns a string representing the type of a name.
418 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
419 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
420 = case lookupNameEnv (ic_type_env ic) name of
421 Nothing -> return Nothing
422 Just (AnId id) -> return (Just str)
424 unqual = ic_print_unqual ic
425 ty = tidyType emptyTidyEnv (idType id)
426 str = showSDocForUser unqual (ppr ty)
428 _ -> panic "cmTypeOfName"
431 -----------------------------------------------------------------------------
432 -- cmCompileExpr: compile an expression and deliver an HValue
435 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
436 cmCompileExpr cmstate dflags expr
438 let InteractiveContext {
439 ic_rn_local_env = rn_env,
440 ic_type_env = type_env } = icontext
442 (new_pcs, maybe_stuff)
443 <- hscStmt dflags hst hit pcs icontext
444 ("let __cmCompileExpr = "++expr) False{-stmt-}
447 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
448 Just (ids, _, bcos) -> do
451 hval <- linkExpr pls bcos
454 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
455 hvals <- thing_to_run
458 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
459 _ -> panic "cmCompileExpr"
462 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
465 -----------------------------------------------------------------------------
466 -- Unload the compilation manager's state: everything it knows about the
467 -- current collection of modules in the Home package.
469 cmUnload :: CmState -> DynFlags -> IO CmState
470 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
471 = do -- Throw away the old home dir cache
474 -- Unload everything the linker knows about
475 new_pls <- CmLink.unload mode dflags [] pls
477 -- Start with a fresh CmState, but keep the PersistentCompilerState
478 new_state <- cmInit mode
479 return new_state{ pcs=pcs, pls=new_pls }
482 -----------------------------------------------------------------------------
483 -- Trace dependency graph
485 -- This is a seperate pass so that the caller can back off and keep
486 -- the current state if the downsweep fails.
488 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
489 cmDepAnal cmstate dflags rootnames
490 = do showPass dflags "Chasing dependencies"
491 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
492 hPutStrLn stderr (showSDoc (hcat [
493 text progName, text ": chasing modules from: ",
494 hcat (punctuate comma (map text rootnames))]))
495 downsweep rootnames (mg cmstate)
497 -----------------------------------------------------------------------------
498 -- The real business of the compilation manager: given a system state and
499 -- a module name, try and bring the module up to date, probably changing
500 -- the system state at the same time.
502 cmLoadModules :: CmState
505 -> IO (CmState, -- new state
506 Bool, -- was successful
507 [String]) -- list of modules loaded
509 cmLoadModules cmstate1 dflags mg2unsorted
510 = do -- version 1's are the original, before downsweep
511 let pls1 = pls cmstate1
512 let pcs1 = pcs cmstate1
513 let hst1 = hst cmstate1
514 let hit1 = hit cmstate1
515 -- similarly, ui1 is the (complete) set of linkables from
516 -- the previous pass, if any.
517 let ui1 = ui cmstate1
519 let ghci_mode = gmode cmstate1 -- this never changes
521 -- Do the downsweep to reestablish the module graph
522 let verb = verbosity dflags
524 -- Find out if we have a Main module
526 = any ((=="Main").moduleNameUserString.modSummaryName)
529 let mg2unsorted_names = map modSummaryName mg2unsorted
531 -- reachable_from follows source as well as normal imports
532 let reachable_from :: ModuleName -> [ModuleName]
533 reachable_from = downwards_closure_of_module mg2unsorted
535 -- should be cycle free; ignores 'import source's
536 let mg2 = topological_sort False mg2unsorted
537 -- ... whereas this takes them into account. Used for
538 -- backing out partially complete cycles following a failed
539 -- upsweep, and for removing from hst/hit all the modules
540 -- not in strict downwards closure, during calls to compile.
541 let mg2_with_srcimps = topological_sort True mg2unsorted
543 -- Sort out which linkables we wish to keep in the unlinked image.
544 -- See getValidLinkables below for details.
545 (valid_old_linkables, new_linkables)
546 <- getValidLinkables ghci_mode ui1
547 mg2unsorted_names mg2_with_srcimps
549 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
551 -- uniq of ModuleName is the same as Module, fortunately...
552 let hit2 = delListFromUFM hit1 (map linkableModName new_linkables)
554 -- When (verb >= 2) $
555 -- putStrLn (showSDoc (text "Valid linkables:"
556 -- <+> ppr valid_linkables))
558 -- Figure out a stable set of modules which can be retained
559 -- the top level envs, to avoid upsweeping them. Goes to a
560 -- bit of trouble to avoid upsweeping module cycles.
562 -- Construct a set S of stable modules like this:
563 -- Travel upwards, over the sccified graph. For each scc
564 -- of modules ms, add ms to S only if:
565 -- 1. All home imports of ms are either in ms or S
566 -- 2. A valid old linkable exists for each module in ms
568 stable_mods <- preUpsweep valid_old_linkables
569 mg2unsorted_names [] mg2_with_srcimps
572 = concatMap (findInSummaries mg2unsorted) stable_mods
575 = filter (\m -> linkableModName m `elem` stable_mods)
579 putStrLn (showSDoc (text "Stable modules:"
580 <+> sep (map (text.moduleNameUserString) stable_mods)))
582 -- unload any modules which are going to be re-linked this
584 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
586 -- we can now glom together our linkable sets
587 let valid_linkables = valid_old_linkables ++ new_linkables
589 -- We could at this point detect cycles which aren't broken by
590 -- a source-import, and complain immediately, but it seems better
591 -- to let upsweep_mods do this, so at least some useful work gets
592 -- done before the upsweep is abandoned.
594 = filter (\scc -> any (`notElem` stable_mods)
595 (map modSummaryName (flattenSCC scc)))
598 --hPutStrLn stderr "after tsort:\n"
599 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
601 -- Because we don't take into account source imports when doing
602 -- the topological sort, there shouldn't be any cycles in mg2.
603 -- If there is, we complain and give up -- the user needs to
604 -- break the cycle using a boot file.
606 -- Now do the upsweep, calling compile for each module in
607 -- turn. Final result is version 3 of everything.
609 let threaded2 = CmThreaded pcs1 hst1 hit2
611 -- clean up between compilations
612 let cleanup = cleanTempFilesExcept verb
613 (ppFilesFromSummaries (flattenSCCs upsweep_these))
615 (upsweep_complete_success, threaded3, modsUpswept, newLis)
616 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
617 threaded2 cleanup upsweep_these
619 let ui3 = add_to_ui valid_linkables newLis
620 let (CmThreaded pcs3 hst3 hit3) = threaded3
622 -- At this point, modsUpswept and newLis should have the same
623 -- length, so there is one new (or old) linkable for each
624 -- mod which was processed (passed to compile).
626 -- Make modsDone be the summaries for each home module now
627 -- available; this should equal the domains of hst3 and hit3.
628 -- (NOT STRICTLY TRUE if an interactive session was started
629 -- with some object on disk ???)
630 -- Get in in a roughly top .. bottom order (hence reverse).
632 let modsDone = reverse modsUpswept ++ stable_summaries
634 -- Try and do linking in some form, depending on whether the
635 -- upsweep was completely or only partially successful.
637 if upsweep_complete_success
640 -- Easy; just relink it all.
641 do when (verb >= 2) $
642 hPutStrLn stderr "Upsweep completely successful."
644 -- clean up after ourselves
645 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
647 -- issue a warning for the confusing case where the user said '-o foo'
648 -- but we're not going to do any linking.
649 ofile <- readIORef v_Output_file
650 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
652 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
654 -- link everything together
655 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
657 cmLoadFinish True linkresult
658 hst3 hit3 ui3 modsDone ghci_mode pcs3
661 -- Tricky. We need to back out the effects of compiling any
662 -- half-done cycles, both so as to clean up the top level envs
663 -- and to avoid telling the interactive linker to link them.
664 do when (verb >= 2) $
665 hPutStrLn stderr "Upsweep partially successful."
668 = map modSummaryName modsDone
669 let mods_to_zap_names
670 = findPartiallyCompletedCycles modsDone_names
673 = filter ((`notElem` mods_to_zap_names).modSummaryName)
676 let (hst4, hit4, ui4)
677 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
680 -- clean up after ourselves
681 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
683 -- link everything together
684 linkresult <- link ghci_mode dflags False ui4 pls2
686 cmLoadFinish False linkresult
687 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
690 -- Finish up after a cmLoad.
692 -- If the link failed, unload everything and return.
693 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
694 dflags <- getDynFlags
695 new_pls <- CmLink.unload ghci_mode dflags [] pls
696 new_state <- cmInit ghci_mode
697 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
699 -- Empty the interactive context and set the module context to the topmost
700 -- newly loaded module, or the Prelude if none were loaded.
701 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
702 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
703 gmode=ghci_mode, pcs=pcs, pls=pls,
704 ic = emptyInteractiveContext }
705 mods_loaded = map (moduleNameUserString.modSummaryName) mods
707 return (new_cmstate, ok, mods_loaded)
709 -- used to fish out the preprocess output files for the purposes
711 ppFilesFromSummaries summaries
712 = [ fn | Just fn <- map toPpFile summaries ]
715 | hspp /= ml_hs_file loc = hspp
716 | otherwise = Nothing
718 loc = ms_location sum
719 hspp = ml_hspp_file loc
722 -----------------------------------------------------------------------------
725 -- For each module (or SCC of modules), we take:
727 -- - an on-disk linkable, if this is the first time around and one
730 -- - the old linkable, otherwise (and if one is available).
732 -- and we throw away the linkable if it is older than the source file.
733 -- In interactive mode, we also ignore the on-disk linkables unless
734 -- all of the dependents of this SCC also have on-disk linkables (we
735 -- can't have dynamically loaded objects that depend on interpreted
738 -- If a module has a valid linkable, then it may be STABLE (see below),
739 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
742 -- ToDo: this pass could be merged with the preUpsweep.
746 -> [Linkable] -- old linkables
747 -> [ModuleName] -- all home modules
748 -> [SCC ModSummary] -- all modules in the program, dependency order
749 -> IO ( [Linkable], -- still-valid linkables
750 [Linkable] -- new linkables we just found
753 getValidLinkables mode old_linkables all_home_mods module_graph = do
754 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
756 return (partition_it ls [] [])
758 partition_it [] valid new = (valid,new)
759 partition_it ((l,b):ls) valid new
760 | b = partition_it ls valid (l:new)
761 | otherwise = partition_it ls (l:valid) new
764 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
766 scc = flattenSCC scc0
767 scc_names = map modSummaryName scc
768 home_module m = m `elem` all_home_mods && m `notElem` scc_names
769 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
770 -- NB. ms_imps, not ms_allimps above. We don't want to
771 -- force a module's SOURCE imports to be already compiled for
772 -- its object linkable to be valid.
775 case findModuleLinkable_maybe (map fst new_linkables) m of
777 Just l -> isObjectLinkable l
779 objects_allowed = mode == Batch || all has_object scc_allhomeimps
783 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
785 -- since an scc can contain only all objects or no objects at all,
786 -- we have to check whether we got all objects or not, and re-do
787 -- the linkable check if not.
790 && not (all isObjectLinkable (map fst new_linkables'))
791 then foldM (getValidLinkable old_linkables False) [] scc
792 else return new_linkables'
794 return (new_linkables ++ new_linkables')
797 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
798 -> IO [(Linkable,Bool)]
799 -- True <=> linkable is new
800 getValidLinkable old_linkables objects_allowed new_linkables summary
801 = do let mod_name = modSummaryName summary
804 <- if (not objects_allowed)
807 else case ml_obj_file (ms_location summary) of
808 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
809 Nothing -> return Nothing
811 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
814 case (old_linkable, maybe_disk_linkable) of
815 (Nothing, Nothing) -> []
817 -- new object linkable just appeared
818 (Nothing, Just l) -> up_to_date l True
821 | isObjectLinkable l -> []
822 -- object linkable disappeared! In case we need to
823 -- relink the module, disregard the old linkable and
824 -- just interpret the module from now on.
825 | otherwise -> up_to_date l False
826 -- old byte code linkable
829 | not (isObjectLinkable l) -> up_to_date l False
830 -- if the previous linkable was interpreted, then we
831 -- ignore a newly compiled version, because the version
832 -- numbers in the interface file will be out-of-sync with
833 -- our internal ones.
834 | linkableTime l' > linkableTime l -> up_to_date l' True
835 | linkableTime l' == linkableTime l -> up_to_date l False
837 -- on-disk linkable has been replaced by an older one!
838 -- again, disregard the previous one.
841 | linkableTime l < ms_hs_date summary = []
842 | otherwise = [(l,b)]
843 -- why '<' rather than '<=' above? If the filesystem stores
844 -- times to the nearset second, we may occasionally find that
845 -- the object & source have the same modification time,
846 -- especially if the source was automatically generated
847 -- and compiled. Using >= is slightly unsafe, but it matches
850 return (new_linkables' ++ new_linkables)
853 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
854 maybe_getFileLinkable mod obj_fn
855 = do obj_exist <- doesFileExist obj_fn
859 do let stub_fn = case splitFilename3 obj_fn of
860 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
861 stub_exist <- doesFileExist stub_fn
862 obj_time <- getModificationTime obj_fn
864 then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
865 else return (Just (LM obj_time mod [DotO obj_fn]))
868 -----------------------------------------------------------------------------
869 -- Do a pre-upsweep without use of "compile", to establish a
870 -- (downward-closed) set of stable modules for which we won't call compile.
873 -- * has a valid linkable (see getValidLinkables above)
874 -- * depends only on stable modules
875 -- * has an interface in the HIT (interactive mode only)
877 preUpsweep :: [Linkable] -- new valid linkables
878 -> [ModuleName] -- names of all mods encountered in downsweep
879 -> [ModuleName] -- accumulating stable modules
880 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
881 -> IO [ModuleName] -- stable modules
883 preUpsweep valid_lis all_home_mods stable [] = return stable
884 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
885 = do let scc = flattenSCC scc0
886 scc_allhomeimps :: [ModuleName]
888 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
889 all_imports_in_scc_or_stable
890 = all in_stable_or_scc scc_allhomeimps
892 = map modSummaryName scc
894 = m `elem` scc_names || m `elem` stable
896 -- now we check for valid linkables: each module in the SCC must
897 -- have a valid linkable (see getValidLinkables above).
898 has_valid_linkable new_summary
899 = isJust (findModuleLinkable_maybe valid_lis modname)
900 where modname = modSummaryName new_summary
902 scc_is_stable = all_imports_in_scc_or_stable
903 && all has_valid_linkable scc
906 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
907 else preUpsweep valid_lis all_home_mods stable sccs
910 -- Helper for preUpsweep. Assuming that new_summary's imports are all
911 -- stable (in the sense of preUpsweep), determine if new_summary is itself
912 -- stable, and, if so, in batch mode, return its linkable.
913 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
914 findInSummaries old_summaries mod_name
915 = [s | s <- old_summaries, modSummaryName s == mod_name]
917 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
918 findModInSummaries old_summaries mod
919 = case [s | s <- old_summaries, ms_mod s == mod] of
923 -- Return (names of) all those in modsDone who are part of a cycle
924 -- as defined by theGraph.
925 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
926 findPartiallyCompletedCycles modsDone theGraph
930 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
931 chew ((CyclicSCC vs):rest)
932 = let names_in_this_cycle = nub (map modSummaryName vs)
934 = nub ([done | done <- modsDone,
935 done `elem` names_in_this_cycle])
936 chewed_rest = chew rest
938 if notNull mods_in_this_cycle
939 && length mods_in_this_cycle < length names_in_this_cycle
940 then mods_in_this_cycle ++ chewed_rest
944 -- Add the given (LM-form) Linkables to the UI, overwriting previous
945 -- versions if they exist.
946 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
948 = filter (not_in lis) ui ++ lis
950 not_in :: [Linkable] -> Linkable -> Bool
952 = all (\l -> linkableModName l /= mod) lis
953 where mod = linkableModName li
956 data CmThreaded -- stuff threaded through individual module compilations
957 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
960 -- Compile multiple modules, stopping as soon as an error appears.
961 -- There better had not be any cyclic groups here -- we check for them.
962 upsweep_mods :: GhciMode
964 -> UnlinkedImage -- valid linkables
965 -> (ModuleName -> [ModuleName]) -- to construct downward closures
966 -> CmThreaded -- PCS & HST & HIT
967 -> IO () -- how to clean up unwanted tmp files
968 -> [SCC ModSummary] -- mods to do (the worklist)
969 -- ...... RETURNING ......
970 -> IO (Bool{-complete success?-},
972 [ModSummary], -- mods which succeeded
973 [Linkable]) -- new linkables
975 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
977 = return (True, threaded, [], [])
979 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
981 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
982 unwords (map (moduleNameUserString.modSummaryName) ms))
983 return (False, threaded, [], [])
985 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
986 ((AcyclicSCC mod):mods)
987 = do --case threaded of
988 -- CmThreaded pcsz hstz hitz
989 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
991 (threaded1, maybe_linkable)
992 <- upsweep_mod ghci_mode dflags oldUI threaded mod
993 (reachable_from (modSummaryName mod))
995 -- remove unwanted tmp files between compilations
998 case maybe_linkable of
1000 -> -- No errors; do the rest
1001 do (restOK, threaded2, modOKs, linkables)
1002 <- upsweep_mods ghci_mode dflags oldUI reachable_from
1003 threaded1 cleanup mods
1004 return (restOK, threaded2, mod:modOKs, linkable:linkables)
1005 Nothing -- we got a compilation error; give up now
1006 -> return (False, threaded1, [], [])
1009 -- Compile a single module. Always produce a Linkable for it if
1010 -- successful. If no compilation happened, return the old Linkable.
1011 upsweep_mod :: GhciMode
1017 -> IO (CmThreaded, Maybe Linkable)
1019 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1021 let mod_name = modSummaryName summary1
1023 let (CmThreaded pcs1 hst1 hit1) = threaded1
1024 let old_iface = lookupUFM hit1 mod_name
1026 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1028 source_unchanged = isJust maybe_old_linkable
1030 reachable_only = filter (/= (modSummaryName summary1))
1033 -- in interactive mode, all home modules below us *must* have an
1034 -- interface in the HIT. We never demand-load home interfaces in
1035 -- interactive mode.
1036 (hst1_strictDC, hit1_strictDC, [])
1037 = ASSERT(ghci_mode == Batch ||
1038 all (`elemUFM` hit1) reachable_only)
1039 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1042 = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1045 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1048 compresult <- compile ghci_mode summary1 source_unchanged
1049 have_object old_iface hst1_strictDC hit1_strictDC pcs1
1053 -- Compilation "succeeded", and may or may not have returned a new
1054 -- linkable (depending on whether compilation was actually performed
1056 CompOK pcs2 new_details new_iface maybe_new_linkable
1057 -> do let hst2 = addToUFM hst1 mod_name new_details
1058 hit2 = addToUFM hit1 mod_name new_iface
1059 threaded2 = CmThreaded pcs2 hst2 hit2
1061 return (threaded2, if isJust maybe_new_linkable
1062 then maybe_new_linkable
1063 else Just old_linkable)
1065 -- Compilation failed. compile may still have updated
1068 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1069 return (threaded2, Nothing)
1071 -- Filter modules in the top level envs (HST, HIT, UI).
1072 retainInTopLevelEnvs :: [ModuleName]
1073 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1074 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1075 retainInTopLevelEnvs keep_these (hst, hit, ui)
1076 = (retainInUFM hst keep_these,
1077 retainInUFM hit keep_these,
1078 filterModuleLinkables (`elem` keep_these) ui
1081 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1082 retainInUFM ufm keys_to_keep
1083 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1084 maybeLookupUFM ufm u
1085 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1087 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1088 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1089 downwards_closure_of_module summaries root
1090 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1091 toEdge summ = (modSummaryName summ,
1092 filter (`elem` all_mods) (ms_allimps summ))
1094 all_mods = map modSummaryName summaries
1096 res = simple_transitive_closure (map toEdge summaries) [root]
1098 -- trace (showSDoc (text "DC of mod" <+> ppr root
1099 -- <+> text "=" <+> ppr res)) $
1102 -- Calculate transitive closures from a set of roots given an adjacency list
1103 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1104 simple_transitive_closure graph set
1105 = let set2 = nub (concatMap dsts set ++ set)
1106 dsts node = fromMaybe [] (lookup node graph)
1108 if length set == length set2
1110 else simple_transitive_closure graph set2
1113 -- Calculate SCCs of the module graph, with or without taking into
1114 -- account source imports.
1115 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1116 topological_sort include_source_imports summaries
1118 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1120 = (summ, modSummaryName summ,
1121 (if include_source_imports
1122 then ms_srcimps summ else []) ++ ms_imps summ)
1124 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1125 mash_edge (summ, m, m_imports)
1126 = case lookup m key_map of
1127 Nothing -> panic "reverse_topological_sort"
1128 Just mk -> (summ, mk,
1129 -- ignore imports not from the home package
1130 catMaybes (map (flip lookup key_map) m_imports))
1132 edges = map toEdge summaries
1133 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1134 scc_input = map mash_edge edges
1135 sccs = stronglyConnComp scc_input
1140 -----------------------------------------------------------------------------
1141 -- Downsweep (dependency analysis)
1143 -- Chase downwards from the specified root set, returning summaries
1144 -- for all home modules encountered. Only follow source-import
1147 -- We pass in the previous collection of summaries, which is used as a
1148 -- cache to avoid recalculating a module summary if the source is
1151 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1152 downsweep roots old_summaries
1153 = do rootSummaries <- mapM getRootSummary roots
1155 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1156 (ms_imps m)) rootSummaries))
1157 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1158 let mod = ms_mod s, isHomeModule mod
1160 return all_summaries
1162 getRootSummary :: FilePath -> IO ModSummary
1164 | haskellish_src_file file
1165 = do exists <- doesFileExist file
1166 if exists then summariseFile file else do
1167 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1169 = do exists <- doesFileExist hs_file
1170 if exists then summariseFile hs_file else do
1171 exists <- doesFileExist lhs_file
1172 if exists then summariseFile lhs_file else do
1173 let mod_name = mkModuleName file
1174 maybe_summary <- getSummary (file, mod_name)
1175 case maybe_summary of
1176 Nothing -> packageModErr mod_name
1179 hs_file = file ++ ".hs"
1180 lhs_file = file ++ ".lhs"
1182 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1183 getSummary (currentMod,nm)
1184 = do found <- findModule nm
1186 Just (mod, location) -> do
1187 let old_summary = findModInSummaries old_summaries mod
1188 summarise mod location old_summary
1191 throwDyn (CmdLineError
1192 ("can't find module `"
1193 ++ showSDoc (ppr nm) ++ "' (while processing "
1194 ++ show currentMod ++ ")"))
1196 -- loop invariant: env doesn't contain package modules
1197 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1198 loop [] env = return (moduleEnvElts env)
1200 = do -- imports for modules we don't already have
1201 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1204 needed_summaries <- mapM getSummary needed_imps
1206 -- get just the "home" modules
1207 let new_home_summaries = [ s | Just s <- needed_summaries ]
1209 -- loop, checking the new imports
1210 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1211 (ms_imps m)) new_home_summaries)
1212 loop new_imps (extendModuleEnvList env
1213 [ (ms_mod s, s) | s <- new_home_summaries ])
1215 -----------------------------------------------------------------------------
1216 -- Summarising modules
1218 -- We have two types of summarisation:
1220 -- * Summarise a file. This is used for the root module(s) passed to
1221 -- cmLoadModules. The file is read, and used to determine the root
1222 -- module name. The module name may differ from the filename.
1224 -- * Summarise a module. We are given a module name, and must provide
1225 -- a summary. The finder is used to locate the file in which the module
1228 summariseFile :: FilePath -> IO ModSummary
1230 = do hspp_fn <- preprocess file
1231 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1233 let (path, basename, _ext) = splitFilename3 file
1234 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1235 the_imps = filter (/= gHC_PRIM_Name) imps
1238 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1241 <- case ml_hs_file location of
1242 Nothing -> noHsFileErr mod_name
1243 Just src_fn -> getModificationTime src_fn
1245 return (ModSummary mod
1246 location{ml_hspp_file=Just hspp_fn}
1247 srcimps the_imps src_timestamp)
1249 -- Summarise a module, and pick up source and timestamp.
1250 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1251 -> IO (Maybe ModSummary)
1252 summarise mod location old_summary
1253 | not (isHomeModule mod) = return Nothing
1255 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1257 case ml_hs_file location of {
1258 Nothing -> noHsFileErr mod;
1261 src_timestamp <- getModificationTime src_fn
1263 -- return the cached summary if the source didn't change
1264 case old_summary of {
1265 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1268 hspp_fn <- preprocess hs_fn
1269 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1271 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1272 the_imps = filter (/= gHC_PRIM_Name) imps
1274 when (mod_name /= moduleName mod) $
1275 throwDyn (ProgramError
1276 (showSDoc (text hs_fn
1277 <> text ": file name does not match module name"
1278 <+> quotes (ppr (moduleName mod)))))
1280 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1281 srcimps the_imps src_timestamp))
1287 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1290 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1291 quotes (ppr mod) <+>
1292 text "is a package module")))