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, [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 )
77 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
78 isHomePackageName, isGlobalName )
80 import Rename ( mkGlobalContext )
81 import RdrName ( emptyRdrEnv )
85 import Unique ( Uniquable )
86 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
87 import ErrUtils ( showPass )
88 import SysTools ( cleanTempFilesExcept )
92 import CmdLineOpts ( DynFlags(..), getDynFlags )
97 import RdrName ( lookupRdrEnv )
98 import Id ( idType, idName )
99 import Type ( tidyType )
100 import VarEnv ( emptyTidyEnv )
101 import BasicTypes ( Fixity, defaultFixity )
102 import Interpreter ( HValue )
103 import HscMain ( hscStmt )
104 import PrelGHC ( unsafeCoerce# )
108 import Exception ( Exception, try )
112 import Exception ( throwDyn )
115 import Directory ( getModificationTime, doesFileExist )
124 -- Persistent state for the entire system
127 hst :: HomeSymbolTable, -- home symbol table
128 hit :: HomeIfaceTable, -- home interface table
129 ui :: UnlinkedImage, -- the unlinked images
130 mg :: ModuleGraph, -- the module graph
131 gmode :: GhciMode, -- NEVER CHANGES
132 ic :: InteractiveContext, -- command-line binding info
134 pcs :: PersistentCompilerState, -- compile's persistent state
135 pls :: PersistentLinkerState -- link's persistent state
138 emptyCmState :: GhciMode -> IO CmState
140 = do pcs <- initPersistentCompilerState
142 return (CmState { hst = emptySymbolTable,
143 hit = emptyIfaceTable,
147 ic = emptyInteractiveContext,
151 emptyInteractiveContext
152 = InteractiveContext { ic_toplev_scope = [],
154 ic_rn_gbl_env = emptyRdrEnv,
155 ic_print_unqual = alwaysQualify,
156 ic_rn_local_env = emptyRdrEnv,
157 ic_type_env = emptyTypeEnv }
160 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
161 emptyUI :: UnlinkedImage
164 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
165 emptyMG :: ModuleGraph
168 -----------------------------------------------------------------------------
169 -- Produce an initial CmState.
171 cmInit :: GhciMode -> IO CmState
172 cmInit mode = emptyCmState mode
174 -----------------------------------------------------------------------------
175 -- Grab information from the CmState
177 cmGetModuleGraph = mg
180 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
181 cmGetPrintUnqual cmstate = ic_print_unqual (ic cmstate)
183 -----------------------------------------------------------------------------
184 -- Setting the context doesn't throw away any bindings; the bindings
185 -- we've built up in the InteractiveContext simply move to the new
186 -- module. They always shadow anything in scope in the current context.
189 :: CmState -> DynFlags
190 -> [String] -- take the top-level scopes of these modules
191 -> [String] -- and the just the exports from these
193 cmSetContext cmstate dflags toplevs exports = do
194 let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
196 toplev_mods <- mapM (getTopLevModule hit) (map mkModuleName toplevs)
197 export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
199 (new_pcs, print_unqual, maybe_env)
200 <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
203 Nothing -> return cmstate
204 Just env -> return cmstate{ pcs = new_pcs,
205 ic = old_ic{ ic_toplev_scope = toplev_mods,
206 ic_exports = export_mods,
208 ic_print_unqual = print_unqual } }
210 getTopLevModule hit mn =
211 case lookupModuleEnvByName hit mn of
213 | Just _ <- mi_globals iface -> return (mi_module iface)
214 _other -> throwDyn (CmdLineError (
215 "cannot enter the top-level scope of a compiled module (module `" ++
216 moduleNameUserString mn ++ "')"))
218 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
219 moduleNameToModule hit mn = do
220 case lookupModuleEnvByName hit mn of
221 Just iface -> return (mi_module iface)
222 _not_a_home_module -> do
223 maybe_stuff <- findModule mn
225 Nothing -> throwDyn (CmdLineError ("can't find module `"
226 ++ moduleNameUserString mn ++ "'"))
227 Just (m,_) -> return m
229 cmGetContext :: CmState -> IO ([String],[String])
230 cmGetContext CmState{ic=ic} =
231 return (map moduleUserString (ic_toplev_scope ic),
232 map moduleUserString (ic_exports ic))
234 cmModuleIsInterpreted :: CmState -> String -> IO Bool
235 cmModuleIsInterpreted cmstate str
236 = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
237 Just iface -> return (not (isNothing (mi_globals iface)))
238 _not_a_home_module -> return False
240 -----------------------------------------------------------------------------
241 -- cmInfoThing: convert a String to a TyThing
243 -- A string may refer to more than one TyThing (eg. a constructor,
244 -- and type constructor), so we return a list of all the possible TyThings.
247 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
248 cmInfoThing cmstate dflags id
249 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
250 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
251 return (cmstate{ pcs=new_pcs }, pairs)
253 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
255 getFixity :: PersistentCompilerState -> Name -> Fixity
258 Just iface <- lookupModuleEnv iface_table (nameModule name),
259 Just fixity <- lookupNameEnv (mi_fixities iface) name
263 where iface_table | isHomePackageName name = hit
264 | otherwise = pcs_PIT pcs
267 -- ---------------------------------------------------------------------------
268 -- cmBrowseModule: get all the TyThings defined in a module
271 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
272 -> IO (CmState, [TyThing])
273 cmBrowseModule cmstate dflags str exports_only = do
274 let mn = mkModuleName str
275 mod <- moduleNameToModule hit mn
276 (pcs1, maybe_ty_things)
277 <- hscModuleContents dflags hst hit pcs mod exports_only
278 case maybe_ty_things of
279 Nothing -> return (cmstate{pcs=pcs1}, [])
280 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
282 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
285 -----------------------------------------------------------------------------
286 -- cmRunStmt: Run a statement/expr.
290 = CmRunOk [Name] -- names bound by this evaluation
292 | CmRunException Exception -- statement raised an exception
294 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
295 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
298 let InteractiveContext {
299 ic_rn_local_env = rn_env,
300 ic_type_env = type_env } = icontext
302 (new_pcs, maybe_stuff)
303 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
306 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
307 Just (ids, _, bcos) -> do
309 -- update the interactive context
311 names = map idName ids
313 -- these names have just been shadowed
314 shadowed = [ n | r <- map nameRdrName names,
315 Just n <- [lookupRdrEnv rn_env r] ]
317 new_rn_env = extendLocalRdrEnv rn_env names
319 -- remove any shadowed bindings from the type_env
320 filtered_type_env = delListFromNameEnv type_env shadowed
322 new_type_env = extendNameEnvList filtered_type_env
323 [ (getName id, AnId id) | id <- ids]
325 new_ic = icontext { ic_rn_local_env = new_rn_env,
326 ic_type_env = new_type_env }
329 hval <- linkExpr pls bcos
332 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
333 either_hvals <- sandboxIO thing_to_run
336 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
337 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
342 return ( cmstate{ pcs=new_pcs, ic=new_ic },
345 -- Get the newly bound things, and bind them.
346 -- Don't forget to delete any shadowed bindings from the
347 -- closure_env, lest we end up with a space leak.
348 pls <- delListFromClosureEnv pls shadowed
349 new_pls <- addListToClosureEnv pls (zip names hvals)
351 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
355 -- We run the statement in a "sandbox" to protect the rest of the
356 -- system from anything the expression might do. For now, this
357 -- consists of just wrapping it in an exception handler, but see below
358 -- for another version.
360 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
362 r <- Exception.try thing
366 -- This version of sandboxIO runs the expression in a completely new
367 -- RTS main thread. It is disabled for now because ^C exceptions
368 -- won't be delivered to the new thread, instead they'll be delivered
369 -- to the (blocked) GHCi main thread.
371 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
373 st_thing <- newStablePtr (Exception.try thing)
374 alloca $ \ p_st_result -> do
375 stat <- rts_evalStableIO st_thing p_st_result
376 freeStablePtr st_thing
378 then do st_result <- peek p_st_result
379 result <- deRefStablePtr st_result
380 freeStablePtr st_result
381 return (Right result)
383 return (Left (fromIntegral stat))
385 foreign import "rts_evalStableIO" {- safe -}
386 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
387 -- more informative than the C type!
391 -----------------------------------------------------------------------------
392 -- cmTypeOfExpr: returns a string representing the type of an expression
395 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
396 cmTypeOfExpr cmstate dflags expr
397 = do (new_pcs, maybe_stuff)
398 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
400 let new_cmstate = cmstate{pcs = new_pcs}
403 Nothing -> return (new_cmstate, Nothing)
404 Just (_, ty, _) -> return (new_cmstate, Just str)
406 str = showSDocForUser unqual (ppr tidy_ty)
407 unqual = ic_print_unqual ic
408 tidy_ty = tidyType emptyTidyEnv ty
410 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
413 -----------------------------------------------------------------------------
414 -- cmTypeOfName: returns a string representing the type of a name.
417 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
418 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
419 = case lookupNameEnv (ic_type_env ic) name of
420 Nothing -> return Nothing
421 Just (AnId id) -> return (Just str)
423 unqual = ic_print_unqual ic
424 ty = tidyType emptyTidyEnv (idType id)
425 str = showSDocForUser unqual (ppr ty)
427 _ -> panic "cmTypeOfName"
430 -----------------------------------------------------------------------------
431 -- cmCompileExpr: compile an expression and deliver an HValue
434 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
435 cmCompileExpr cmstate dflags expr
437 let InteractiveContext {
438 ic_rn_local_env = rn_env,
439 ic_type_env = type_env } = icontext
441 (new_pcs, maybe_stuff)
442 <- hscStmt dflags hst hit pcs icontext
443 ("let __cmCompileExpr = "++expr) False{-stmt-}
446 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
447 Just (ids, _, bcos) -> do
450 hval <- linkExpr pls bcos
453 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
454 hvals <- thing_to_run
457 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
458 _ -> panic "cmCompileExpr"
461 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
464 -----------------------------------------------------------------------------
465 -- Unload the compilation manager's state: everything it knows about the
466 -- current collection of modules in the Home package.
468 cmUnload :: CmState -> DynFlags -> IO CmState
469 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
470 = do -- Throw away the old home dir cache
473 -- Unload everything the linker knows about
474 new_pls <- CmLink.unload mode dflags [] pls
476 -- Start with a fresh CmState, but keep the PersistentCompilerState
477 new_state <- cmInit mode
478 return new_state{ pcs=pcs, pls=new_pls }
481 -----------------------------------------------------------------------------
482 -- Trace dependency graph
484 -- This is a seperate pass so that the caller can back off and keep
485 -- the current state if the downsweep fails.
487 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
488 cmDepAnal cmstate dflags rootnames
489 = do showPass dflags "Chasing dependencies"
490 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
491 hPutStrLn stderr (showSDoc (hcat [
492 text progName, text ": chasing modules from: ",
493 hcat (punctuate comma (map text rootnames))]))
494 downsweep rootnames (mg cmstate)
496 -----------------------------------------------------------------------------
497 -- The real business of the compilation manager: given a system state and
498 -- a module name, try and bring the module up to date, probably changing
499 -- the system state at the same time.
501 cmLoadModules :: CmState
504 -> IO (CmState, -- new state
505 Bool, -- was successful
506 [String]) -- list of modules loaded
508 cmLoadModules cmstate1 dflags mg2unsorted
509 = do -- version 1's are the original, before downsweep
510 let pls1 = pls cmstate1
511 let pcs1 = pcs cmstate1
512 let hst1 = hst cmstate1
513 let hit1 = hit cmstate1
514 -- similarly, ui1 is the (complete) set of linkables from
515 -- the previous pass, if any.
516 let ui1 = ui cmstate1
518 let ghci_mode = gmode cmstate1 -- this never changes
520 -- Do the downsweep to reestablish the module graph
521 let verb = verbosity dflags
523 -- Find out if we have a Main module
525 = any ((=="Main").moduleNameUserString.name_of_summary)
528 let mg2unsorted_names = map name_of_summary mg2unsorted
530 -- reachable_from follows source as well as normal imports
531 let reachable_from :: ModuleName -> [ModuleName]
532 reachable_from = downwards_closure_of_module mg2unsorted
534 -- should be cycle free; ignores 'import source's
535 let mg2 = topological_sort False mg2unsorted
536 -- ... whereas this takes them into account. Used for
537 -- backing out partially complete cycles following a failed
538 -- upsweep, and for removing from hst/hit all the modules
539 -- not in strict downwards closure, during calls to compile.
540 let mg2_with_srcimps = topological_sort True mg2unsorted
542 -- Sort out which linkables we wish to keep in the unlinked image.
543 -- See getValidLinkables below for details.
544 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
546 -- when (verb >= 2) $
547 -- putStrLn (showSDoc (text "Valid linkables:"
548 -- <+> ppr valid_linkables))
550 -- Figure out a stable set of modules which can be retained
551 -- the top level envs, to avoid upsweeping them. Goes to a
552 -- bit of trouble to avoid upsweeping module cycles.
554 -- Construct a set S of stable modules like this:
555 -- Travel upwards, over the sccified graph. For each scc
556 -- of modules ms, add ms to S only if:
557 -- 1. All home imports of ms are either in ms or S
558 -- 2. A valid linkable exists for each module in ms
560 stable_mods <- preUpsweep valid_linkables hit1
561 mg2unsorted_names [] mg2_with_srcimps
564 = concatMap (findInSummaries mg2unsorted) stable_mods
567 = filter (\m -> linkableModName m `elem` stable_mods)
571 putStrLn (showSDoc (text "Stable modules:"
572 <+> sep (map (text.moduleNameUserString) stable_mods)))
574 -- unload any modules which aren't going to be re-linked this
576 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
578 -- We could at this point detect cycles which aren't broken by
579 -- a source-import, and complain immediately, but it seems better
580 -- to let upsweep_mods do this, so at least some useful work gets
581 -- done before the upsweep is abandoned.
583 = filter (\scc -> any (`notElem` stable_mods)
584 (map name_of_summary (flattenSCC scc)))
587 --hPutStrLn stderr "after tsort:\n"
588 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
590 -- Because we don't take into account source imports when doing
591 -- the topological sort, there shouldn't be any cycles in mg2.
592 -- If there is, we complain and give up -- the user needs to
593 -- break the cycle using a boot file.
595 -- Now do the upsweep, calling compile for each module in
596 -- turn. Final result is version 3 of everything.
598 let threaded2 = CmThreaded pcs1 hst1 hit1
600 -- clean up between compilations
601 let cleanup = cleanTempFilesExcept verb
602 (ppFilesFromSummaries (flattenSCCs upsweep_these))
604 (upsweep_complete_success, threaded3, modsUpswept, newLis)
605 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
606 threaded2 cleanup upsweep_these
608 let ui3 = add_to_ui valid_linkables newLis
609 let (CmThreaded pcs3 hst3 hit3) = threaded3
611 -- At this point, modsUpswept and newLis should have the same
612 -- length, so there is one new (or old) linkable for each
613 -- mod which was processed (passed to compile).
615 -- Make modsDone be the summaries for each home module now
616 -- available; this should equal the domains of hst3 and hit3.
617 -- (NOT STRICTLY TRUE if an interactive session was started
618 -- with some object on disk ???)
619 -- Get in in a roughly top .. bottom order (hence reverse).
621 let modsDone = reverse modsUpswept ++ stable_summaries
623 -- Try and do linking in some form, depending on whether the
624 -- upsweep was completely or only partially successful.
626 if upsweep_complete_success
629 -- Easy; just relink it all.
630 do when (verb >= 2) $
631 hPutStrLn stderr "Upsweep completely successful."
633 -- clean up after ourselves
634 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
636 -- issue a warning for the confusing case where the user said '-o foo'
637 -- but we're not going to do any linking.
638 ofile <- readIORef v_Output_file
639 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
641 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
643 -- link everything together
644 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
646 cmLoadFinish True linkresult
647 hst3 hit3 ui3 modsDone ghci_mode pcs3
650 -- Tricky. We need to back out the effects of compiling any
651 -- half-done cycles, both so as to clean up the top level envs
652 -- and to avoid telling the interactive linker to link them.
653 do when (verb >= 2) $
654 hPutStrLn stderr "Upsweep partially successful."
657 = map name_of_summary modsDone
658 let mods_to_zap_names
659 = findPartiallyCompletedCycles modsDone_names
662 = filter ((`notElem` mods_to_zap_names).name_of_summary)
665 let (hst4, hit4, ui4)
666 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
669 -- clean up after ourselves
670 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
672 -- link everything together
673 linkresult <- link ghci_mode dflags False ui4 pls2
675 cmLoadFinish False linkresult
676 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
679 -- Finish up after a cmLoad.
681 -- If the link failed, unload everything and return.
682 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
683 dflags <- getDynFlags
684 new_pls <- CmLink.unload ghci_mode dflags [] pls
685 new_state <- cmInit ghci_mode
686 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
688 -- Empty the interactive context and set the module context to the topmost
689 -- newly loaded module, or the Prelude if none were loaded.
690 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
691 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
692 gmode=ghci_mode, pcs=pcs, pls=pls,
693 ic = emptyInteractiveContext }
694 mods_loaded = map (moduleNameUserString.name_of_summary) mods
696 return (new_cmstate, ok, mods_loaded)
698 -- used to fish out the preprocess output files for the purposes
700 ppFilesFromSummaries summaries
701 = [ fn | Just fn <- map toPpFile summaries ]
704 | hspp /= ml_hs_file loc = hspp
705 | otherwise = Nothing
707 loc = ms_location sum
708 hspp = ml_hspp_file loc
711 -----------------------------------------------------------------------------
714 -- For each module (or SCC of modules), we take:
716 -- - an on-disk linkable, if this is the first time around and one
719 -- - the old linkable, otherwise (and if one is available).
721 -- and we throw away the linkable if it is older than the source
722 -- file. We ignore the on-disk linkables unless all of the dependents
723 -- of this SCC also have on-disk linkables.
725 -- If a module has a valid linkable, then it may be STABLE (see below),
726 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
729 -- ToDo: this pass could be merged with the preUpsweep.
732 :: [Linkable] -- old linkables
733 -> [ModuleName] -- all home modules
734 -> [SCC ModSummary] -- all modules in the program, dependency order
735 -> IO [Linkable] -- still-valid linkables
737 getValidLinkables old_linkables all_home_mods module_graph
738 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
740 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
742 scc = flattenSCC scc0
743 scc_names = map name_of_summary scc
744 home_module m = m `elem` all_home_mods && m `notElem` scc_names
745 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
746 -- NOTE: ms_imps, not ms_allimps above. We don't want to
747 -- force a module's SOURCE imports to be already compiled for
748 -- its object linkable to be valid.
750 has_object m = case findModuleLinkable_maybe new_linkables m of
752 Just l -> isObjectLinkable l
754 objects_allowed = all has_object scc_allhomeimps
758 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
760 -- since an scc can contain only all objects or no objects at all,
761 -- we have to check whether we got all objects or not, and re-do
762 -- the linkable check if not.
764 <- if objects_allowed && not (all isObjectLinkable these_linkables)
765 then foldM (getValidLinkable old_linkables False) [] scc
766 else return these_linkables
768 return (adjusted_linkables ++ new_linkables)
771 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
773 getValidLinkable old_linkables objects_allowed new_linkables summary
774 = do let mod_name = name_of_summary summary
777 <- if (not objects_allowed)
779 else case ml_obj_file (ms_location summary) of
780 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
781 Nothing -> return Nothing
783 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
786 Just l | not (isObjectLinkable l) || stillThere l
788 -- ToDo: emit a warning if not (stillThere l)
791 -- make sure that if we had an old disk linkable around, that it's
792 -- still there on the disk (in case we need to re-link it).
794 case maybe_disk_linkable of
796 Just l_disk -> linkableTime l == linkableTime l_disk
798 -- we only look for objects on disk the first time around;
799 -- if the user compiles a module on the side during a GHCi session,
800 -- it won't be picked up until the next ":load". This is what the
801 -- "null old_linkables" test below is.
802 linkable | null old_linkables = maybeToList maybe_disk_linkable
803 | otherwise = maybeToList maybe_old_linkable
805 -- only linkables newer than the source code are valid
806 src_date = ms_hs_date summary
809 = filter (\l -> linkableTime l >= src_date) linkable
810 -- why '>=' rather than '>' above? If the filesystem stores
811 -- times to the nearset second, we may occasionally find that
812 -- the object & source have the same modification time,
813 -- especially if the source was automatically generated
814 -- and compiled. Using >= is slightly unsafe, but it matches
817 return (valid_linkable ++ new_linkables)
820 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
821 maybe_getFileLinkable mod_name obj_fn
822 = do obj_exist <- doesFileExist obj_fn
826 do let stub_fn = case splitFilename3 obj_fn of
827 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
828 stub_exist <- doesFileExist stub_fn
829 obj_time <- getModificationTime obj_fn
831 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
832 else return (Just (LM obj_time mod_name [DotO obj_fn]))
835 -----------------------------------------------------------------------------
836 -- Do a pre-upsweep without use of "compile", to establish a
837 -- (downward-closed) set of stable modules for which we won't call compile.
840 -- * has a valid linkable (see getValidLinkables above)
841 -- * depends only on stable modules
842 -- * has an interface in the HIT (interactive mode only)
844 preUpsweep :: [Linkable] -- new valid linkables
846 -> [ModuleName] -- names of all mods encountered in downsweep
847 -> [ModuleName] -- accumulating stable modules
848 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
849 -> IO [ModuleName] -- stable modules
851 preUpsweep valid_lis hit all_home_mods stable [] = return stable
852 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
853 = do let scc = flattenSCC scc0
854 scc_allhomeimps :: [ModuleName]
856 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
857 all_imports_in_scc_or_stable
858 = all in_stable_or_scc scc_allhomeimps
860 = map name_of_summary scc
862 = m `elem` scc_names || m `elem` stable
864 -- now we check for valid linkables: each module in the SCC must
865 -- have a valid linkable (see getValidLinkables above).
866 has_valid_linkable new_summary
867 = isJust (findModuleLinkable_maybe valid_lis modname)
868 where modname = name_of_summary new_summary
870 has_interface summary = ms_mod summary `elemUFM` hit
872 scc_is_stable = all_imports_in_scc_or_stable
873 && all has_valid_linkable scc
874 && all has_interface scc
877 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
878 else preUpsweep valid_lis hit all_home_mods stable sccs
881 -- Helper for preUpsweep. Assuming that new_summary's imports are all
882 -- stable (in the sense of preUpsweep), determine if new_summary is itself
883 -- stable, and, if so, in batch mode, return its linkable.
884 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
885 findInSummaries old_summaries mod_name
886 = [s | s <- old_summaries, name_of_summary s == mod_name]
888 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
889 findModInSummaries old_summaries mod
890 = case [s | s <- old_summaries, ms_mod s == mod] of
894 -- Return (names of) all those in modsDone who are part of a cycle
895 -- as defined by theGraph.
896 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
897 findPartiallyCompletedCycles modsDone theGraph
901 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
902 chew ((CyclicSCC vs):rest)
903 = let names_in_this_cycle = nub (map name_of_summary vs)
905 = nub ([done | done <- modsDone,
906 done `elem` names_in_this_cycle])
907 chewed_rest = chew rest
909 if not (null mods_in_this_cycle)
910 && length mods_in_this_cycle < length names_in_this_cycle
911 then mods_in_this_cycle ++ chewed_rest
915 -- Add the given (LM-form) Linkables to the UI, overwriting previous
916 -- versions if they exist.
917 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
919 = filter (not_in lis) ui ++ lis
921 not_in :: [Linkable] -> Linkable -> Bool
923 = all (\l -> linkableModName l /= mod) lis
924 where mod = linkableModName li
927 data CmThreaded -- stuff threaded through individual module compilations
928 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
931 -- Compile multiple modules, stopping as soon as an error appears.
932 -- There better had not be any cyclic groups here -- we check for them.
933 upsweep_mods :: GhciMode
935 -> UnlinkedImage -- valid linkables
936 -> (ModuleName -> [ModuleName]) -- to construct downward closures
937 -> CmThreaded -- PCS & HST & HIT
938 -> IO () -- how to clean up unwanted tmp files
939 -> [SCC ModSummary] -- mods to do (the worklist)
940 -- ...... RETURNING ......
941 -> IO (Bool{-complete success?-},
943 [ModSummary], -- mods which succeeded
944 [Linkable]) -- new linkables
946 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
948 = return (True, threaded, [], [])
950 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
952 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
953 unwords (map (moduleNameUserString.name_of_summary) ms))
954 return (False, threaded, [], [])
956 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
957 ((AcyclicSCC mod):mods)
958 = do --case threaded of
959 -- CmThreaded pcsz hstz hitz
960 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
962 (threaded1, maybe_linkable)
963 <- upsweep_mod ghci_mode dflags oldUI threaded mod
964 (reachable_from (name_of_summary mod))
966 -- remove unwanted tmp files between compilations
969 case maybe_linkable of
971 -> -- No errors; do the rest
972 do (restOK, threaded2, modOKs, linkables)
973 <- upsweep_mods ghci_mode dflags oldUI reachable_from
974 threaded1 cleanup mods
975 return (restOK, threaded2, mod:modOKs, linkable:linkables)
976 Nothing -- we got a compilation error; give up now
977 -> return (False, threaded1, [], [])
980 -- Compile a single module. Always produce a Linkable for it if
981 -- successful. If no compilation happened, return the old Linkable.
982 upsweep_mod :: GhciMode
988 -> IO (CmThreaded, Maybe Linkable)
990 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
992 let mod_name = name_of_summary summary1
994 let (CmThreaded pcs1 hst1 hit1) = threaded1
995 let old_iface = lookupUFM hit1 mod_name
997 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
999 source_unchanged = isJust maybe_old_linkable
1001 reachable_only = filter (/= (name_of_summary summary1))
1004 -- in interactive mode, all home modules below us *must* have an
1005 -- interface in the HIT. We never demand-load home interfaces in
1006 -- interactive mode.
1007 (hst1_strictDC, hit1_strictDC, [])
1008 = ASSERT(ghci_mode == Batch ||
1009 all (`elemUFM` hit1) reachable_only)
1010 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1013 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
1016 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1019 compresult <- compile ghci_mode summary1 source_unchanged
1020 have_object old_iface hst1_strictDC hit1_strictDC pcs1
1024 -- Compilation "succeeded", and may or may not have returned a new
1025 -- linkable (depending on whether compilation was actually performed
1027 CompOK pcs2 new_details new_iface maybe_new_linkable
1028 -> do let hst2 = addToUFM hst1 mod_name new_details
1029 hit2 = addToUFM hit1 mod_name new_iface
1030 threaded2 = CmThreaded pcs2 hst2 hit2
1032 return (threaded2, if isJust maybe_new_linkable
1033 then maybe_new_linkable
1034 else Just old_linkable)
1036 -- Compilation failed. compile may still have updated
1039 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1040 return (threaded2, Nothing)
1042 -- Filter modules in the top level envs (HST, HIT, UI).
1043 retainInTopLevelEnvs :: [ModuleName]
1044 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1045 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1046 retainInTopLevelEnvs keep_these (hst, hit, ui)
1047 = (retainInUFM hst keep_these,
1048 retainInUFM hit keep_these,
1049 filterModuleLinkables (`elem` keep_these) ui
1052 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1053 retainInUFM ufm keys_to_keep
1054 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1055 maybeLookupUFM ufm u
1056 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1058 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1059 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1060 downwards_closure_of_module summaries root
1061 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1062 toEdge summ = (name_of_summary summ,
1063 filter (`elem` all_mods) (ms_allimps summ))
1065 all_mods = map name_of_summary summaries
1067 res = simple_transitive_closure (map toEdge summaries) [root]
1069 -- trace (showSDoc (text "DC of mod" <+> ppr root
1070 -- <+> text "=" <+> ppr res)) $
1073 -- Calculate transitive closures from a set of roots given an adjacency list
1074 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1075 simple_transitive_closure graph set
1076 = let set2 = nub (concatMap dsts set ++ set)
1077 dsts node = fromMaybe [] (lookup node graph)
1079 if length set == length set2
1081 else simple_transitive_closure graph set2
1084 -- Calculate SCCs of the module graph, with or without taking into
1085 -- account source imports.
1086 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1087 topological_sort include_source_imports summaries
1089 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1091 = (summ, name_of_summary summ,
1092 (if include_source_imports
1093 then ms_srcimps summ else []) ++ ms_imps summ)
1095 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1096 mash_edge (summ, m, m_imports)
1097 = case lookup m key_map of
1098 Nothing -> panic "reverse_topological_sort"
1099 Just mk -> (summ, mk,
1100 -- ignore imports not from the home package
1101 catMaybes (map (flip lookup key_map) m_imports))
1103 edges = map toEdge summaries
1104 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1105 scc_input = map mash_edge edges
1106 sccs = stronglyConnComp scc_input
1111 -----------------------------------------------------------------------------
1112 -- Downsweep (dependency analysis)
1114 -- Chase downwards from the specified root set, returning summaries
1115 -- for all home modules encountered. Only follow source-import
1118 -- We pass in the previous collection of summaries, which is used as a
1119 -- cache to avoid recalculating a module summary if the source is
1122 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1123 downsweep roots old_summaries
1124 = do rootSummaries <- mapM getRootSummary roots
1126 <- loop (concat (map ms_imps rootSummaries))
1127 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1128 let mod = ms_mod s, isHomeModule mod
1130 return all_summaries
1132 getRootSummary :: FilePath -> IO ModSummary
1134 | haskellish_src_file file
1135 = do exists <- doesFileExist file
1136 if exists then summariseFile file else do
1137 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1139 = do exists <- doesFileExist hs_file
1140 if exists then summariseFile hs_file else do
1141 exists <- doesFileExist lhs_file
1142 if exists then summariseFile lhs_file else do
1143 let mod_name = mkModuleName file
1144 maybe_summary <- getSummary mod_name
1145 case maybe_summary of
1146 Nothing -> packageModErr mod_name
1149 hs_file = file ++ ".hs"
1150 lhs_file = file ++ ".lhs"
1152 getSummary :: ModuleName -> IO (Maybe ModSummary)
1154 = do found <- findModule nm
1156 Just (mod, location) -> do
1157 let old_summary = findModInSummaries old_summaries mod
1158 summarise mod location old_summary
1160 Nothing -> throwDyn (CmdLineError
1161 ("can't find module `"
1162 ++ showSDoc (ppr nm) ++ "'"))
1164 -- loop invariant: env doesn't contain package modules
1165 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1166 loop [] env = return (moduleEnvElts env)
1168 = do -- imports for modules we don't already have
1169 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1172 needed_summaries <- mapM getSummary needed_imps
1174 -- get just the "home" modules
1175 let new_home_summaries = [ s | Just s <- needed_summaries ]
1177 -- loop, checking the new imports
1178 let new_imps = concat (map ms_imps new_home_summaries)
1179 loop new_imps (extendModuleEnvList env
1180 [ (ms_mod s, s) | s <- new_home_summaries ])
1182 -----------------------------------------------------------------------------
1183 -- Summarising modules
1185 -- We have two types of summarisation:
1187 -- * Summarise a file. This is used for the root module(s) passed to
1188 -- cmLoadModules. The file is read, and used to determine the root
1189 -- module name. The module name may differ from the filename.
1191 -- * Summarise a module. We are given a module name, and must provide
1192 -- a summary. The finder is used to locate the file in which the module
1195 summariseFile :: FilePath -> IO ModSummary
1197 = do hspp_fn <- preprocess file
1198 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1200 let (path, basename, _ext) = splitFilename3 file
1203 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1206 <- case ml_hs_file location of
1207 Nothing -> noHsFileErr mod_name
1208 Just src_fn -> getModificationTime src_fn
1210 return (ModSummary mod
1211 location{ml_hspp_file=Just hspp_fn}
1212 srcimps imps src_timestamp)
1214 -- Summarise a module, and pick up source and timestamp.
1215 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1216 -> IO (Maybe ModSummary)
1217 summarise mod location old_summary
1218 | not (isHomeModule mod) = return Nothing
1220 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1222 case ml_hs_file location of {
1223 Nothing -> noHsFileErr mod;
1226 src_timestamp <- getModificationTime src_fn
1228 -- return the cached summary if the source didn't change
1229 case old_summary of {
1230 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1233 hspp_fn <- preprocess hs_fn
1234 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1236 when (mod_name /= moduleName mod) $
1237 throwDyn (ProgramError
1238 (showSDoc (text hs_fn
1239 <> text ": file name does not match module name"
1240 <+> quotes (ppr (moduleName mod)))))
1242 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1243 srcimps imps src_timestamp))
1249 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1252 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1253 quotes (ppr mod) <+>
1254 text "is a package module")))