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"
63 import DriverState ( v_Output_file )
68 import HscMain ( initPersistentCompilerState, hscThing,
71 import HscMain ( initPersistentCompilerState )
73 import HscTypes hiding ( moduleNameToModule )
74 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
75 isHomePackageName, isExternalName )
77 import PrelNames ( gHC_PRIM_Name )
78 import Rename ( mkGlobalContext )
79 import RdrName ( emptyRdrEnv )
83 import Unique ( Uniquable )
84 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
85 import ErrUtils ( showPass )
86 import SysTools ( cleanTempFilesExcept )
90 import CmdLineOpts ( DynFlags(..), getDynFlags )
91 import Maybes ( expectJust )
96 import RdrName ( lookupRdrEnv )
97 import Id ( idType, idName )
98 import Type ( tidyType )
99 import VarEnv ( emptyTidyEnv )
100 import BasicTypes ( Fixity, defaultFixity )
101 import Interpreter ( HValue )
102 import HscMain ( hscStmt )
103 import GlaExts ( unsafeCoerce# )
106 import Exception ( Exception, try )
110 import Exception ( throwDyn )
113 import Directory ( getModificationTime, doesFileExist )
122 -- Persistent state for the entire system
125 hst :: HomeSymbolTable, -- home symbol table
126 hit :: HomeIfaceTable, -- home interface table
127 ui :: UnlinkedImage, -- the unlinked images
128 mg :: ModuleGraph, -- the module graph
129 gmode :: GhciMode, -- NEVER CHANGES
130 ic :: InteractiveContext, -- command-line binding info
132 pcs :: PersistentCompilerState, -- compile's persistent state
133 pls :: PersistentLinkerState -- link's persistent state
136 emptyCmState :: GhciMode -> IO CmState
138 = do pcs <- initPersistentCompilerState
140 return (CmState { hst = emptySymbolTable,
141 hit = emptyIfaceTable,
145 ic = emptyInteractiveContext,
149 emptyInteractiveContext
150 = InteractiveContext { ic_toplev_scope = [],
152 ic_rn_gbl_env = emptyRdrEnv,
153 ic_print_unqual = alwaysQualify,
154 ic_rn_local_env = emptyRdrEnv,
155 ic_type_env = emptyTypeEnv }
158 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
159 emptyUI :: UnlinkedImage
162 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
163 emptyMG :: ModuleGraph
166 -----------------------------------------------------------------------------
167 -- Produce an initial CmState.
169 cmInit :: GhciMode -> IO CmState
170 cmInit mode = emptyCmState mode
172 -----------------------------------------------------------------------------
173 -- Grab information from the CmState
175 cmGetModuleGraph = mg
178 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
179 cmGetPrintUnqual cmstate = ic_print_unqual (ic cmstate)
181 -----------------------------------------------------------------------------
182 -- Setting the context doesn't throw away any bindings; the bindings
183 -- we've built up in the InteractiveContext simply move to the new
184 -- module. They always shadow anything in scope in the current context.
187 :: CmState -> DynFlags
188 -> [String] -- take the top-level scopes of these modules
189 -> [String] -- and the just the exports from these
191 cmSetContext cmstate dflags toplevs exports = do
192 let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
194 toplev_mods <- mapM (getTopLevModule hit) (map mkModuleName toplevs)
195 export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
197 (new_pcs, print_unqual, maybe_env)
198 <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
201 Nothing -> return cmstate
202 Just env -> return cmstate{ pcs = new_pcs,
203 ic = old_ic{ ic_toplev_scope = toplev_mods,
204 ic_exports = export_mods,
206 ic_print_unqual = print_unqual } }
208 getTopLevModule hit mn =
209 case lookupModuleEnvByName hit mn of
211 | Just _ <- mi_globals iface -> return (mi_module iface)
212 _other -> throwDyn (CmdLineError (
213 "cannot enter the top-level scope of a compiled module (module `" ++
214 moduleNameUserString mn ++ "')"))
216 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
217 moduleNameToModule hit mn = do
218 case lookupModuleEnvByName hit mn of
219 Just iface -> return (mi_module iface)
220 _not_a_home_module -> do
221 maybe_stuff <- findModule mn
223 Nothing -> throwDyn (CmdLineError ("can't find module `"
224 ++ moduleNameUserString mn ++ "'"))
225 Just (m,_) -> return m
227 cmGetContext :: CmState -> IO ([String],[String])
228 cmGetContext CmState{ic=ic} =
229 return (map moduleUserString (ic_toplev_scope ic),
230 map moduleUserString (ic_exports ic))
232 cmModuleIsInterpreted :: CmState -> String -> IO Bool
233 cmModuleIsInterpreted cmstate str
234 = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
235 Just iface -> return (not (isNothing (mi_globals iface)))
236 _not_a_home_module -> return False
238 -----------------------------------------------------------------------------
239 -- cmInfoThing: convert a String to a TyThing
241 -- A string may refer to more than one TyThing (eg. a constructor,
242 -- and type constructor), so we return a list of all the possible TyThings.
245 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
246 cmInfoThing cmstate dflags id
247 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
248 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
249 return (cmstate{ pcs=new_pcs }, pairs)
251 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
253 getFixity :: PersistentCompilerState -> Name -> Fixity
255 | isExternalName name,
256 Just iface <- lookupModuleEnv iface_table (nameModule name),
257 Just fixity <- lookupNameEnv (mi_fixities iface) name
261 where iface_table | isHomePackageName name = hit
262 | otherwise = pcs_PIT pcs
265 -- ---------------------------------------------------------------------------
266 -- cmBrowseModule: get all the TyThings defined in a module
269 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
270 -> IO (CmState, [TyThing])
271 cmBrowseModule cmstate dflags str exports_only = do
272 let mn = mkModuleName str
273 mod <- moduleNameToModule hit mn
274 (pcs1, maybe_ty_things)
275 <- hscModuleContents dflags hst hit pcs mod exports_only
276 case maybe_ty_things of
277 Nothing -> return (cmstate{pcs=pcs1}, [])
278 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
280 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
283 -----------------------------------------------------------------------------
284 -- cmRunStmt: Run a statement/expr.
288 = CmRunOk [Name] -- names bound by this evaluation
290 | CmRunException Exception -- statement raised an exception
292 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
293 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
296 let InteractiveContext {
297 ic_rn_local_env = rn_env,
298 ic_type_env = type_env } = icontext
300 (new_pcs, maybe_stuff)
301 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
304 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
305 Just (ids, _, bcos) -> do
307 -- update the interactive context
309 names = map idName ids
311 -- these names have just been shadowed
312 shadowed = [ n | r <- map nameRdrName names,
313 Just n <- [lookupRdrEnv rn_env r] ]
315 new_rn_env = extendLocalRdrEnv rn_env names
317 -- remove any shadowed bindings from the type_env
318 filtered_type_env = delListFromNameEnv type_env shadowed
320 new_type_env = extendNameEnvList filtered_type_env
321 [ (getName id, AnId id) | id <- ids]
323 new_ic = icontext { ic_rn_local_env = new_rn_env,
324 ic_type_env = new_type_env }
327 hval <- linkExpr pls bcos
330 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
331 either_hvals <- sandboxIO thing_to_run
334 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
335 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
340 return ( cmstate{ pcs=new_pcs, ic=new_ic },
343 -- Get the newly bound things, and bind them.
344 -- Don't forget to delete any shadowed bindings from the
345 -- closure_env, lest we end up with a space leak.
346 pls <- delListFromClosureEnv pls shadowed
347 new_pls <- addListToClosureEnv pls (zip names hvals)
349 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
353 -- We run the statement in a "sandbox" to protect the rest of the
354 -- system from anything the expression might do. For now, this
355 -- consists of just wrapping it in an exception handler, but see below
356 -- for another version.
358 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
360 r <- Exception.try thing
364 -- This version of sandboxIO runs the expression in a completely new
365 -- RTS main thread. It is disabled for now because ^C exceptions
366 -- won't be delivered to the new thread, instead they'll be delivered
367 -- to the (blocked) GHCi main thread.
369 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
371 st_thing <- newStablePtr (Exception.try thing)
372 alloca $ \ p_st_result -> do
373 stat <- rts_evalStableIO st_thing p_st_result
374 freeStablePtr st_thing
376 then do st_result <- peek p_st_result
377 result <- deRefStablePtr st_result
378 freeStablePtr st_result
379 return (Right result)
381 return (Left (fromIntegral stat))
383 foreign import "rts_evalStableIO" {- safe -}
384 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
385 -- more informative than the C type!
389 -----------------------------------------------------------------------------
390 -- cmTypeOfExpr: returns a string representing the type of an expression
393 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
394 cmTypeOfExpr cmstate dflags expr
395 = do (new_pcs, maybe_stuff)
396 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
398 let new_cmstate = cmstate{pcs = new_pcs}
401 Nothing -> return (new_cmstate, Nothing)
402 Just (_, ty, _) -> return (new_cmstate, Just str)
404 str = showSDocForUser unqual (ppr tidy_ty)
405 unqual = ic_print_unqual ic
406 tidy_ty = tidyType emptyTidyEnv ty
408 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
411 -----------------------------------------------------------------------------
412 -- cmTypeOfName: returns a string representing the type of a name.
415 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
416 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
417 = case lookupNameEnv (ic_type_env ic) name of
418 Nothing -> return Nothing
419 Just (AnId id) -> return (Just str)
421 unqual = ic_print_unqual ic
422 ty = tidyType emptyTidyEnv (idType id)
423 str = showSDocForUser unqual (ppr ty)
425 _ -> panic "cmTypeOfName"
428 -----------------------------------------------------------------------------
429 -- cmCompileExpr: compile an expression and deliver an HValue
432 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
433 cmCompileExpr cmstate dflags expr
435 let InteractiveContext {
436 ic_rn_local_env = rn_env,
437 ic_type_env = type_env } = icontext
439 (new_pcs, maybe_stuff)
440 <- hscStmt dflags hst hit pcs icontext
441 ("let __cmCompileExpr = "++expr) False{-stmt-}
444 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
445 Just (ids, _, bcos) -> do
448 hval <- linkExpr pls bcos
451 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
452 hvals <- thing_to_run
455 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
456 _ -> panic "cmCompileExpr"
459 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
462 -----------------------------------------------------------------------------
463 -- Unload the compilation manager's state: everything it knows about the
464 -- current collection of modules in the Home package.
466 cmUnload :: CmState -> DynFlags -> IO CmState
467 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
468 = do -- Throw away the old home dir cache
471 -- Unload everything the linker knows about
472 new_pls <- CmLink.unload mode dflags [] pls
474 -- Start with a fresh CmState, but keep the PersistentCompilerState
475 new_state <- cmInit mode
476 return new_state{ pcs=pcs, pls=new_pls }
479 -----------------------------------------------------------------------------
480 -- Trace dependency graph
482 -- This is a seperate pass so that the caller can back off and keep
483 -- the current state if the downsweep fails.
485 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
486 cmDepAnal cmstate dflags rootnames
487 = do showPass dflags "Chasing dependencies"
488 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
489 hPutStrLn stderr (showSDoc (hcat [
490 text progName, text ": chasing modules from: ",
491 hcat (punctuate comma (map text rootnames))]))
492 downsweep rootnames (mg cmstate)
494 -----------------------------------------------------------------------------
495 -- The real business of the compilation manager: given a system state and
496 -- a module name, try and bring the module up to date, probably changing
497 -- the system state at the same time.
499 cmLoadModules :: CmState
502 -> IO (CmState, -- new state
503 Bool, -- was successful
504 [String]) -- list of modules loaded
506 cmLoadModules cmstate1 dflags mg2unsorted
507 = do -- version 1's are the original, before downsweep
508 let pls1 = pls cmstate1
509 let pcs1 = pcs cmstate1
510 let hst1 = hst cmstate1
511 let hit1 = hit cmstate1
512 -- similarly, ui1 is the (complete) set of linkables from
513 -- the previous pass, if any.
514 let ui1 = ui cmstate1
516 let ghci_mode = gmode cmstate1 -- this never changes
518 -- Do the downsweep to reestablish the module graph
519 let verb = verbosity dflags
521 -- Find out if we have a Main module
523 = any ((=="Main").moduleNameUserString.modSummaryName)
526 let mg2unsorted_names = map modSummaryName mg2unsorted
528 -- reachable_from follows source as well as normal imports
529 let reachable_from :: ModuleName -> [ModuleName]
530 reachable_from = downwards_closure_of_module mg2unsorted
532 -- should be cycle free; ignores 'import source's
533 let mg2 = topological_sort False mg2unsorted
534 -- ... whereas this takes them into account. Used for
535 -- backing out partially complete cycles following a failed
536 -- upsweep, and for removing from hst/hit all the modules
537 -- not in strict downwards closure, during calls to compile.
538 let mg2_with_srcimps = topological_sort True mg2unsorted
540 -- Sort out which linkables we wish to keep in the unlinked image.
541 -- See getValidLinkables below for details.
542 (valid_old_linkables, new_linkables)
543 <- getValidLinkables ghci_mode ui1
544 mg2unsorted_names mg2_with_srcimps
546 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
548 -- uniq of ModuleName is the same as Module, fortunately...
549 let hit2 = delListFromUFM hit1 (map linkableModName new_linkables)
551 -- When (verb >= 2) $
552 -- putStrLn (showSDoc (text "Valid linkables:"
553 -- <+> ppr valid_linkables))
555 -- Figure out a stable set of modules which can be retained
556 -- the top level envs, to avoid upsweeping them. Goes to a
557 -- bit of trouble to avoid upsweeping module cycles.
559 -- Construct a set S of stable modules like this:
560 -- Travel upwards, over the sccified graph. For each scc
561 -- of modules ms, add ms to S only if:
562 -- 1. All home imports of ms are either in ms or S
563 -- 2. A valid old linkable exists for each module in ms
565 stable_mods <- preUpsweep valid_old_linkables
566 mg2unsorted_names [] mg2_with_srcimps
569 = concatMap (findInSummaries mg2unsorted) stable_mods
572 = filter (\m -> linkableModName m `elem` stable_mods)
576 putStrLn (showSDoc (text "Stable modules:"
577 <+> sep (map (text.moduleNameUserString) stable_mods)))
579 -- unload any modules which are going to be re-linked this
581 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
583 -- we can now glom together our linkable sets
584 let valid_linkables = valid_old_linkables ++ new_linkables
586 -- We could at this point detect cycles which aren't broken by
587 -- a source-import, and complain immediately, but it seems better
588 -- to let upsweep_mods do this, so at least some useful work gets
589 -- done before the upsweep is abandoned.
591 = filter (\scc -> any (`notElem` stable_mods)
592 (map modSummaryName (flattenSCC scc)))
595 --hPutStrLn stderr "after tsort:\n"
596 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
598 -- Because we don't take into account source imports when doing
599 -- the topological sort, there shouldn't be any cycles in mg2.
600 -- If there is, we complain and give up -- the user needs to
601 -- break the cycle using a boot file.
603 -- Now do the upsweep, calling compile for each module in
604 -- turn. Final result is version 3 of everything.
606 let threaded2 = CmThreaded pcs1 hst1 hit2
608 -- clean up between compilations
609 let cleanup = cleanTempFilesExcept verb
610 (ppFilesFromSummaries (flattenSCCs mg2))
612 (upsweep_complete_success, threaded3, modsUpswept, newLis)
613 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
614 threaded2 cleanup upsweep_these
616 let ui3 = add_to_ui valid_linkables newLis
617 let (CmThreaded pcs3 hst3 hit3) = threaded3
619 -- At this point, modsUpswept and newLis should have the same
620 -- length, so there is one new (or old) linkable for each
621 -- mod which was processed (passed to compile).
623 -- Make modsDone be the summaries for each home module now
624 -- available; this should equal the domains of hst3 and hit3.
625 -- (NOT STRICTLY TRUE if an interactive session was started
626 -- with some object on disk ???)
627 -- Get in in a roughly top .. bottom order (hence reverse).
629 let modsDone = reverse modsUpswept ++ stable_summaries
631 -- Try and do linking in some form, depending on whether the
632 -- upsweep was completely or only partially successful.
634 if upsweep_complete_success
637 -- Easy; just relink it all.
638 do when (verb >= 2) $
639 hPutStrLn stderr "Upsweep completely successful."
641 -- clean up after ourselves
642 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
644 -- issue a warning for the confusing case where the user said '-o foo'
645 -- but we're not going to do any linking.
646 ofile <- readIORef v_Output_file
647 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
649 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
651 -- link everything together
652 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
654 cmLoadFinish True linkresult
655 hst3 hit3 ui3 modsDone ghci_mode pcs3
658 -- Tricky. We need to back out the effects of compiling any
659 -- half-done cycles, both so as to clean up the top level envs
660 -- and to avoid telling the interactive linker to link them.
661 do when (verb >= 2) $
662 hPutStrLn stderr "Upsweep partially successful."
665 = map modSummaryName modsDone
666 let mods_to_zap_names
667 = findPartiallyCompletedCycles modsDone_names
670 = filter ((`notElem` mods_to_zap_names).modSummaryName)
673 let (hst4, hit4, ui4)
674 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
677 -- clean up after ourselves
678 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
680 -- link everything together
681 linkresult <- link ghci_mode dflags False ui4 pls2
683 cmLoadFinish False linkresult
684 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
687 -- Finish up after a cmLoad.
689 -- If the link failed, unload everything and return.
690 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
691 dflags <- getDynFlags
692 new_pls <- CmLink.unload ghci_mode dflags [] pls
693 new_state <- cmInit ghci_mode
694 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
696 -- Empty the interactive context and set the module context to the topmost
697 -- newly loaded module, or the Prelude if none were loaded.
698 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
699 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
700 gmode=ghci_mode, pcs=pcs, pls=pls,
701 ic = emptyInteractiveContext }
702 mods_loaded = map (moduleNameUserString.modSummaryName) mods
704 return (new_cmstate, ok, mods_loaded)
706 -- used to fish out the preprocess output files for the purposes
708 ppFilesFromSummaries summaries
709 = [ fn | Just fn <- map toPpFile summaries ]
712 | hspp /= ml_hs_file loc = hspp
713 | otherwise = Nothing
715 loc = ms_location sum
716 hspp = ml_hspp_file loc
719 -----------------------------------------------------------------------------
722 -- For each module (or SCC of modules), we take:
724 -- - an on-disk linkable, if this is the first time around and one
727 -- - the old linkable, otherwise (and if one is available).
729 -- and we throw away the linkable if it is older than the source file.
730 -- In interactive mode, we also ignore the on-disk linkables unless
731 -- all of the dependents of this SCC also have on-disk linkables (we
732 -- can't have dynamically loaded objects that depend on interpreted
735 -- If a module has a valid linkable, then it may be STABLE (see below),
736 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
739 -- ToDo: this pass could be merged with the preUpsweep.
743 -> [Linkable] -- old linkables
744 -> [ModuleName] -- all home modules
745 -> [SCC ModSummary] -- all modules in the program, dependency order
746 -> IO ( [Linkable], -- still-valid linkables
747 [Linkable] -- new linkables we just found
750 getValidLinkables mode old_linkables all_home_mods module_graph = do
751 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
753 return (partition_it ls [] [])
755 partition_it [] valid new = (valid,new)
756 partition_it ((l,b):ls) valid new
757 | b = partition_it ls valid (l:new)
758 | otherwise = partition_it ls (l:valid) new
761 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
763 scc = flattenSCC scc0
764 scc_names = map modSummaryName scc
765 home_module m = m `elem` all_home_mods && m `notElem` scc_names
766 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
767 -- NB. ms_imps, not ms_allimps above. We don't want to
768 -- force a module's SOURCE imports to be already compiled for
769 -- its object linkable to be valid.
772 case findModuleLinkable_maybe (map fst new_linkables) m of
774 Just l -> isObjectLinkable l
776 objects_allowed = mode == Batch || all has_object scc_allhomeimps
780 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
782 -- since an scc can contain only all objects or no objects at all,
783 -- we have to check whether we got all objects or not, and re-do
784 -- the linkable check if not.
787 && not (all isObjectLinkable (map fst new_linkables'))
788 then foldM (getValidLinkable old_linkables False) [] scc
789 else return new_linkables'
791 return (new_linkables ++ new_linkables')
794 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
795 -> IO [(Linkable,Bool)]
796 -- True <=> linkable is new
797 getValidLinkable old_linkables objects_allowed new_linkables summary
798 = do let mod_name = modSummaryName summary
801 <- if (not objects_allowed)
804 else case ml_obj_file (ms_location summary) of
805 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
806 Nothing -> return Nothing
808 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
811 case (old_linkable, maybe_disk_linkable) of
812 (Nothing, Nothing) -> []
814 -- new object linkable just appeared
815 (Nothing, Just l) -> up_to_date l True
818 | isObjectLinkable l -> []
819 -- object linkable disappeared! In case we need to
820 -- relink the module, disregard the old linkable and
821 -- just interpret the module from now on.
822 | otherwise -> up_to_date l False
823 -- old byte code linkable
826 | not (isObjectLinkable l) -> up_to_date l False
827 -- if the previous linkable was interpreted, then we
828 -- ignore a newly compiled version, because the version
829 -- numbers in the interface file will be out-of-sync with
830 -- our internal ones.
831 | linkableTime l' > linkableTime l -> up_to_date l' True
832 | linkableTime l' == linkableTime l -> up_to_date l False
834 -- on-disk linkable has been replaced by an older one!
835 -- again, disregard the previous one.
838 | linkableTime l < ms_hs_date summary = []
839 | otherwise = [(l,b)]
840 -- why '<' rather than '<=' above? If the filesystem stores
841 -- times to the nearset second, we may occasionally find that
842 -- the object & source have the same modification time,
843 -- especially if the source was automatically generated
844 -- and compiled. Using >= is slightly unsafe, but it matches
847 return (new_linkables' ++ new_linkables)
850 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
851 maybe_getFileLinkable mod obj_fn
852 = do obj_exist <- doesFileExist obj_fn
856 do let stub_fn = case splitFilename3 obj_fn of
857 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
858 stub_exist <- doesFileExist stub_fn
859 obj_time <- getModificationTime obj_fn
861 then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
862 else return (Just (LM obj_time mod [DotO obj_fn]))
865 -----------------------------------------------------------------------------
866 -- Do a pre-upsweep without use of "compile", to establish a
867 -- (downward-closed) set of stable modules for which we won't call compile.
870 -- * has a valid linkable (see getValidLinkables above)
871 -- * depends only on stable modules
872 -- * has an interface in the HIT (interactive mode only)
874 preUpsweep :: [Linkable] -- new valid linkables
875 -> [ModuleName] -- names of all mods encountered in downsweep
876 -> [ModuleName] -- accumulating stable modules
877 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
878 -> IO [ModuleName] -- stable modules
880 preUpsweep valid_lis all_home_mods stable [] = return stable
881 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
882 = do let scc = flattenSCC scc0
883 scc_allhomeimps :: [ModuleName]
885 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
886 all_imports_in_scc_or_stable
887 = all in_stable_or_scc scc_allhomeimps
889 = map modSummaryName scc
891 = m `elem` scc_names || m `elem` stable
893 -- now we check for valid linkables: each module in the SCC must
894 -- have a valid linkable (see getValidLinkables above).
895 has_valid_linkable new_summary
896 = isJust (findModuleLinkable_maybe valid_lis modname)
897 where modname = modSummaryName new_summary
899 scc_is_stable = all_imports_in_scc_or_stable
900 && all has_valid_linkable scc
903 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
904 else preUpsweep valid_lis all_home_mods stable sccs
907 -- Helper for preUpsweep. Assuming that new_summary's imports are all
908 -- stable (in the sense of preUpsweep), determine if new_summary is itself
909 -- stable, and, if so, in batch mode, return its linkable.
910 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
911 findInSummaries old_summaries mod_name
912 = [s | s <- old_summaries, modSummaryName s == mod_name]
914 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
915 findModInSummaries old_summaries mod
916 = case [s | s <- old_summaries, ms_mod s == mod] of
920 -- Return (names of) all those in modsDone who are part of a cycle
921 -- as defined by theGraph.
922 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
923 findPartiallyCompletedCycles modsDone theGraph
927 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
928 chew ((CyclicSCC vs):rest)
929 = let names_in_this_cycle = nub (map modSummaryName vs)
931 = nub ([done | done <- modsDone,
932 done `elem` names_in_this_cycle])
933 chewed_rest = chew rest
935 if notNull mods_in_this_cycle
936 && length mods_in_this_cycle < length names_in_this_cycle
937 then mods_in_this_cycle ++ chewed_rest
941 -- Add the given (LM-form) Linkables to the UI, overwriting previous
942 -- versions if they exist.
943 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
945 = filter (not_in lis) ui ++ lis
947 not_in :: [Linkable] -> Linkable -> Bool
949 = all (\l -> linkableModName l /= mod) lis
950 where mod = linkableModName li
953 data CmThreaded -- stuff threaded through individual module compilations
954 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
957 -- Compile multiple modules, stopping as soon as an error appears.
958 -- There better had not be any cyclic groups here -- we check for them.
959 upsweep_mods :: GhciMode
961 -> UnlinkedImage -- valid linkables
962 -> (ModuleName -> [ModuleName]) -- to construct downward closures
963 -> CmThreaded -- PCS & HST & HIT
964 -> IO () -- how to clean up unwanted tmp files
965 -> [SCC ModSummary] -- mods to do (the worklist)
966 -- ...... RETURNING ......
967 -> IO (Bool{-complete success?-},
969 [ModSummary], -- mods which succeeded
970 [Linkable]) -- new linkables
972 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
974 = return (True, threaded, [], [])
976 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
978 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
979 unwords (map (moduleNameUserString.modSummaryName) ms))
980 return (False, threaded, [], [])
982 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
983 ((AcyclicSCC mod):mods)
984 = do --case threaded of
985 -- CmThreaded pcsz hstz hitz
986 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
988 (threaded1, maybe_linkable)
989 <- upsweep_mod ghci_mode dflags oldUI threaded mod
990 (reachable_from (modSummaryName mod))
992 -- remove unwanted tmp files between compilations
995 case maybe_linkable of
997 -> -- No errors; do the rest
998 do (restOK, threaded2, modOKs, linkables)
999 <- upsweep_mods ghci_mode dflags oldUI reachable_from
1000 threaded1 cleanup mods
1001 return (restOK, threaded2, mod:modOKs, linkable:linkables)
1002 Nothing -- we got a compilation error; give up now
1003 -> return (False, threaded1, [], [])
1006 -- Compile a single module. Always produce a Linkable for it if
1007 -- successful. If no compilation happened, return the old Linkable.
1008 upsweep_mod :: GhciMode
1014 -> IO (CmThreaded, Maybe Linkable)
1016 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1018 let mod_name = modSummaryName summary1
1020 let (CmThreaded pcs1 hst1 hit1) = threaded1
1021 let old_iface = lookupUFM hit1 mod_name
1023 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1025 source_unchanged = isJust maybe_old_linkable
1027 reachable_only = filter (/= (modSummaryName summary1))
1030 -- in interactive mode, all home modules below us *must* have an
1031 -- interface in the HIT. We never demand-load home interfaces in
1032 -- interactive mode.
1033 (hst1_strictDC, hit1_strictDC, [])
1034 = ASSERT(ghci_mode == Batch ||
1035 all (`elemUFM` hit1) reachable_only)
1036 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1039 = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1042 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1045 compresult <- compile ghci_mode summary1 source_unchanged
1046 have_object old_iface hst1_strictDC hit1_strictDC pcs1
1050 -- Compilation "succeeded", and may or may not have returned a new
1051 -- linkable (depending on whether compilation was actually performed
1053 CompOK pcs2 new_details new_iface maybe_new_linkable
1054 -> do let hst2 = addToUFM hst1 mod_name new_details
1055 hit2 = addToUFM hit1 mod_name new_iface
1056 threaded2 = CmThreaded pcs2 hst2 hit2
1058 return (threaded2, if isJust maybe_new_linkable
1059 then maybe_new_linkable
1060 else Just old_linkable)
1062 -- Compilation failed. compile may still have updated
1065 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1066 return (threaded2, Nothing)
1068 -- Filter modules in the top level envs (HST, HIT, UI).
1069 retainInTopLevelEnvs :: [ModuleName]
1070 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1071 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1072 retainInTopLevelEnvs keep_these (hst, hit, ui)
1073 = (retainInUFM hst keep_these,
1074 retainInUFM hit keep_these,
1075 filterModuleLinkables (`elem` keep_these) ui
1078 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1079 retainInUFM ufm keys_to_keep
1080 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1081 maybeLookupUFM ufm u
1082 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1084 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1085 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1086 downwards_closure_of_module summaries root
1087 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1088 toEdge summ = (modSummaryName summ,
1089 filter (`elem` all_mods) (ms_allimps summ))
1091 all_mods = map modSummaryName summaries
1093 res = simple_transitive_closure (map toEdge summaries) [root]
1095 -- trace (showSDoc (text "DC of mod" <+> ppr root
1096 -- <+> text "=" <+> ppr res)) $
1099 -- Calculate transitive closures from a set of roots given an adjacency list
1100 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1101 simple_transitive_closure graph set
1102 = let set2 = nub (concatMap dsts set ++ set)
1103 dsts node = fromMaybe [] (lookup node graph)
1105 if length set == length set2
1107 else simple_transitive_closure graph set2
1110 -- Calculate SCCs of the module graph, with or without taking into
1111 -- account source imports.
1112 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1113 topological_sort include_source_imports summaries
1115 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1117 = (summ, modSummaryName summ,
1118 (if include_source_imports
1119 then ms_srcimps summ else []) ++ ms_imps summ)
1121 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1122 mash_edge (summ, m, m_imports)
1123 = case lookup m key_map of
1124 Nothing -> panic "reverse_topological_sort"
1125 Just mk -> (summ, mk,
1126 -- ignore imports not from the home package
1127 catMaybes (map (flip lookup key_map) m_imports))
1129 edges = map toEdge summaries
1130 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1131 scc_input = map mash_edge edges
1132 sccs = stronglyConnComp scc_input
1137 -----------------------------------------------------------------------------
1138 -- Downsweep (dependency analysis)
1140 -- Chase downwards from the specified root set, returning summaries
1141 -- for all home modules encountered. Only follow source-import
1144 -- We pass in the previous collection of summaries, which is used as a
1145 -- cache to avoid recalculating a module summary if the source is
1148 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1149 downsweep roots old_summaries
1150 = do rootSummaries <- mapM getRootSummary roots
1151 checkDuplicates rootSummaries
1153 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1154 (ms_imps m)) rootSummaries))
1155 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1156 let mod = ms_mod s, isHomeModule mod
1158 return all_summaries
1160 getRootSummary :: FilePath -> IO ModSummary
1162 | haskellish_src_file file
1163 = do exists <- doesFileExist file
1164 if exists then summariseFile file else do
1165 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1167 = do exists <- doesFileExist hs_file
1168 if exists then summariseFile hs_file else do
1169 exists <- doesFileExist lhs_file
1170 if exists then summariseFile lhs_file else do
1171 let mod_name = mkModuleName file
1172 maybe_summary <- getSummary (file, mod_name)
1173 case maybe_summary of
1174 Nothing -> packageModErr mod_name
1177 hs_file = file ++ ".hs"
1178 lhs_file = file ++ ".lhs"
1180 -- In a root module, the filename is allowed to diverge from the module
1181 -- name, so we have to check that there aren't multiple root files
1182 -- defining the same module (otherwise the duplicates will be silently
1183 -- ignored, leading to confusing behaviour).
1184 checkDuplicates :: [ModSummary] -> IO ()
1185 checkDuplicates summaries = mapM_ check summaries
1189 files -> multiRootsErr modl files
1190 where modl = ms_mod summ
1192 [ fromJust (ml_hs_file (ms_location summ'))
1193 | summ' <- summaries, ms_mod summ' == modl ]
1195 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1196 getSummary (currentMod,nm)
1197 = do found <- findModule nm
1199 Just (mod, location) -> do
1200 let old_summary = findModInSummaries old_summaries mod
1201 summarise mod location old_summary
1204 throwDyn (CmdLineError
1205 ("can't find module `"
1206 ++ showSDoc (ppr nm) ++ "' (while processing "
1207 ++ show currentMod ++ ")"))
1209 -- loop invariant: env doesn't contain package modules
1210 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1211 loop [] env = return (moduleEnvElts env)
1213 = do -- imports for modules we don't already have
1214 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1217 needed_summaries <- mapM getSummary needed_imps
1219 -- get just the "home" modules
1220 let new_home_summaries = [ s | Just s <- needed_summaries ]
1222 -- loop, checking the new imports
1223 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1224 (ms_imps m)) new_home_summaries)
1225 loop new_imps (extendModuleEnvList env
1226 [ (ms_mod s, s) | s <- new_home_summaries ])
1228 -----------------------------------------------------------------------------
1229 -- Summarising modules
1231 -- We have two types of summarisation:
1233 -- * Summarise a file. This is used for the root module(s) passed to
1234 -- cmLoadModules. The file is read, and used to determine the root
1235 -- module name. The module name may differ from the filename.
1237 -- * Summarise a module. We are given a module name, and must provide
1238 -- a summary. The finder is used to locate the file in which the module
1241 summariseFile :: FilePath -> IO ModSummary
1243 = do hspp_fn <- preprocess file
1244 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1246 let (path, basename, _ext) = splitFilename3 file
1247 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1248 the_imps = filter (/= gHC_PRIM_Name) imps
1251 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1254 <- case ml_hs_file location of
1255 Nothing -> noHsFileErr mod_name
1256 Just src_fn -> getModificationTime src_fn
1258 return (ModSummary mod
1259 location{ml_hspp_file=Just hspp_fn}
1260 srcimps the_imps src_timestamp)
1262 -- Summarise a module, and pick up source and timestamp.
1263 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1264 -> IO (Maybe ModSummary)
1265 summarise mod location old_summary
1266 | not (isHomeModule mod) = return Nothing
1268 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1270 case ml_hs_file location of {
1271 Nothing -> noHsFileErr mod;
1274 src_timestamp <- getModificationTime src_fn
1276 -- return the cached summary if the source didn't change
1277 case old_summary of {
1278 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1281 hspp_fn <- preprocess hs_fn
1282 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1284 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1285 the_imps = filter (/= gHC_PRIM_Name) imps
1287 when (mod_name /= moduleName mod) $
1288 throwDyn (ProgramError
1289 (showSDoc (text hs_fn
1290 <> text ": file name does not match module name"
1291 <+> quotes (ppr (moduleName mod)))))
1293 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1294 srcimps the_imps src_timestamp))
1300 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1303 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1304 quotes (ppr mod) <+>
1305 text "is a package module")))
1307 multiRootsErr mod files
1308 = throwDyn (ProgramError (showSDoc (
1309 text "module" <+> quotes (ppr mod) <+>
1310 text "is defined in multiple files:" <+>
1311 sep (map text files))))