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 -> [String] -> [String] -> IO CmState
26 cmGetContext, -- :: CmState -> IO ([String],[String])
28 cmInfoThing, -- :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
31 cmRunStmt, -- :: CmState -> DynFlags -> String
32 -- -> IO (CmState, CmRunResult)
34 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
35 -- -> IO (CmState, Maybe String)
37 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
39 cmCompileExpr, -- :: CmState -> DynFlags -> String
40 -- -> IO (CmState, Maybe HValue)#endif
45 #include "HsVersions.h"
50 import DriverState ( v_Output_file )
55 import HscMain ( initPersistentCompilerState, hscThing )
57 import HscMain ( initPersistentCompilerState )
60 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
62 import Rename ( mkGlobalContext )
63 import RdrName ( emptyRdrEnv )
67 import Unique ( Uniquable )
68 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
69 import ErrUtils ( showPass )
70 import SysTools ( cleanTempFilesExcept )
74 import CmdLineOpts ( DynFlags(..), getDynFlags )
79 import RdrName ( lookupRdrEnv )
80 import Id ( idType, idName )
82 import Type ( tidyType )
83 import VarEnv ( emptyTidyEnv )
84 import BasicTypes ( Fixity, defaultFixity )
85 import Interpreter ( HValue )
86 import HscMain ( hscStmt )
87 import PrelGHC ( unsafeCoerce# )
91 import Exception ( Exception, try )
95 import Exception ( throwDyn )
98 import Directory ( getModificationTime, doesFileExist )
107 -- Persistent state for the entire system
110 hst :: HomeSymbolTable, -- home symbol table
111 hit :: HomeIfaceTable, -- home interface table
112 ui :: UnlinkedImage, -- the unlinked images
113 mg :: ModuleGraph, -- the module graph
114 gmode :: GhciMode, -- NEVER CHANGES
115 ic :: InteractiveContext, -- command-line binding info
117 pcs :: PersistentCompilerState, -- compile's persistent state
118 pls :: PersistentLinkerState -- link's persistent state
121 emptyCmState :: GhciMode -> IO CmState
123 = do pcs <- initPersistentCompilerState
125 return (CmState { hst = emptySymbolTable,
126 hit = emptyIfaceTable,
130 ic = emptyInteractiveContext,
134 emptyInteractiveContext
135 = InteractiveContext { ic_toplev_scope = [],
137 ic_rn_gbl_env = emptyRdrEnv,
138 ic_print_unqual = alwaysQualify,
139 ic_rn_local_env = emptyRdrEnv,
140 ic_type_env = emptyTypeEnv }
143 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
144 emptyUI :: UnlinkedImage
147 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
148 emptyMG :: ModuleGraph
151 -----------------------------------------------------------------------------
152 -- Produce an initial CmState.
154 cmInit :: GhciMode -> IO CmState
155 cmInit mode = emptyCmState mode
157 -----------------------------------------------------------------------------
158 -- Setting the context doesn't throw away any bindings; the bindings
159 -- we've built up in the InteractiveContext simply move to the new
160 -- module. They always shadow anything in scope in the current context.
163 :: CmState -> DynFlags
164 -> [String] -- take the top-level scopes of these modules
165 -> [String] -- and the just the exports from these
167 cmSetContext cmstate dflags toplevs exports = do
168 let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
170 toplev_mods <- mapM (getTopLevModule hit) (map mkModuleName toplevs)
171 export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
173 (new_pcs, print_unqual, maybe_env)
174 <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
177 Nothing -> return cmstate
178 Just env -> return cmstate{ pcs = new_pcs,
179 ic = old_ic{ ic_toplev_scope = toplev_mods,
180 ic_exports = export_mods,
182 ic_print_unqual = print_unqual } }
184 getTopLevModule hit mn =
185 case lookupModuleEnvByName hit mn of
187 | Just _ <- mi_globals iface -> return (mi_module iface)
188 _other -> throwDyn (CmdLineError (
189 "cannot enter the top-level scope of a compiled module (module `" ++
190 moduleNameUserString mn ++ "')"))
192 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
193 moduleNameToModule hit mn = do
194 case lookupModuleEnvByName hit mn of
195 Just iface -> return (mi_module iface)
196 _not_a_home_module -> do
197 maybe_stuff <- findModule mn
199 Nothing -> throwDyn (CmdLineError ("can't find module `"
200 ++ moduleNameUserString mn ++ "'"))
201 Just (m,_) -> return m
203 cmGetContext :: CmState -> IO ([String],[String])
204 cmGetContext CmState{ic=ic} =
205 return (map moduleUserString (ic_toplev_scope ic),
206 map moduleUserString (ic_exports ic))
208 cmModuleIsInterpreted :: CmState -> String -> IO Bool
209 cmModuleIsInterpreted cmstate str
210 = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
211 Just iface -> return (not (isNothing (mi_globals iface)))
212 _not_a_home_module -> return False
214 -----------------------------------------------------------------------------
215 -- cmInfoThing: convert a String to a TyThing
217 -- A string may refer to more than one TyThing (eg. a constructor,
218 -- and type constructor), so we return a list of all the possible TyThings.
221 cmInfoThing :: CmState -> DynFlags -> String
222 -> IO (CmState, PrintUnqualified, [(TyThing,Fixity)])
223 cmInfoThing cmstate dflags id
224 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
225 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
226 return (cmstate{ pcs=new_pcs }, unqual, pairs)
228 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
229 unqual = ic_print_unqual icontext
231 getFixity :: PersistentCompilerState -> Name -> Fixity
233 | Just iface <- lookupModuleEnv iface_table (nameModule name),
234 Just fixity <- lookupNameEnv (mi_fixities iface) name
238 where iface_table | isHomePackageName name = hit
239 | otherwise = pcs_PIT pcs
242 -----------------------------------------------------------------------------
243 -- cmRunStmt: Run a statement/expr.
247 = CmRunOk [Name] -- names bound by this evaluation
249 | CmRunDeadlocked -- statement deadlocked
250 | CmRunException Exception -- statement raised an exception
252 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
253 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
256 let InteractiveContext {
257 ic_rn_local_env = rn_env,
258 ic_type_env = type_env } = icontext
260 (new_pcs, maybe_stuff)
261 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
264 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
265 Just (ids, _, bcos) -> do
267 -- update the interactive context
269 names = map idName ids
271 -- these names have just been shadowed
272 shadowed = [ n | r <- map nameRdrName names,
273 Just n <- [lookupRdrEnv rn_env r] ]
275 new_rn_env = extendLocalRdrEnv rn_env names
277 -- remove any shadowed bindings from the type_env
278 filtered_type_env = delListFromNameEnv type_env shadowed
280 new_type_env = extendNameEnvList filtered_type_env
281 [ (getName id, AnId id) | id <- ids]
283 new_ic = icontext { ic_rn_local_env = new_rn_env,
284 ic_type_env = new_type_env }
287 hval <- linkExpr pls bcos
290 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
291 either_hvals <- sandboxIO thing_to_run
295 -> return ( cmstate{ pcs=new_pcs, ic=new_ic },
298 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
299 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
304 return ( cmstate{ pcs=new_pcs, ic=new_ic },
307 -- Get the newly bound things, and bind them.
308 -- Don't forget to delete any shadowed bindings from the
309 -- closure_env, lest we end up with a space leak.
310 pls <- delListFromClosureEnv pls shadowed
311 new_pls <- addListToClosureEnv pls (zip names hvals)
313 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
316 -- We run the statement in a "sandbox", which amounts to calling into
317 -- the RTS to request a new main thread. The main benefit is that we
318 -- get to detect a deadlock this way, but also there's no danger that
319 -- exceptions raised by the expression can affect the interpreter.
321 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
323 st_thing <- newStablePtr (Exception.try thing)
324 alloca $ \ p_st_result -> do
325 stat <- rts_evalStableIO st_thing p_st_result
326 freeStablePtr st_thing
328 then do st_result <- peek p_st_result
329 result <- deRefStablePtr st_result
330 freeStablePtr st_result
331 return (Right result)
333 return (Left (fromIntegral stat))
335 -- ToDo: slurp this in from ghc/includes/RtsAPI.h somehow
336 dEADLOCKED = 4 :: Int
338 foreign import "rts_evalStableIO" {- safe -}
339 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
340 -- more informative than the C type!
343 -----------------------------------------------------------------------------
344 -- cmTypeOfExpr: returns a string representing the type of an expression
347 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
348 cmTypeOfExpr cmstate dflags expr
349 = do (new_pcs, maybe_stuff)
350 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
352 let new_cmstate = cmstate{pcs = new_pcs}
355 Nothing -> return (new_cmstate, Nothing)
356 Just (_, ty, _) -> return (new_cmstate, Just str)
358 str = showSDocForUser unqual (ppr tidy_ty)
359 unqual = ic_print_unqual ic
360 tidy_ty = tidyType emptyTidyEnv ty
362 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
365 -----------------------------------------------------------------------------
366 -- cmTypeOfName: returns a string representing the type of a name.
369 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
370 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
371 = case lookupNameEnv (ic_type_env ic) name of
372 Nothing -> return Nothing
373 Just (AnId id) -> return (Just str)
375 unqual = ic_print_unqual ic
376 ty = tidyType emptyTidyEnv (idType id)
377 str = showSDocForUser unqual (ppr ty)
379 _ -> panic "cmTypeOfName"
382 -----------------------------------------------------------------------------
383 -- cmCompileExpr: compile an expression and deliver an HValue
386 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
387 cmCompileExpr cmstate dflags expr
389 let InteractiveContext {
390 ic_rn_local_env = rn_env,
391 ic_type_env = type_env } = icontext
393 (new_pcs, maybe_stuff)
394 <- hscStmt dflags hst hit pcs icontext
395 ("let __cmCompileExpr = "++expr) False{-stmt-}
398 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
399 Just (ids, _, bcos) -> do
402 hval <- linkExpr pls bcos
405 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
406 hvals <- thing_to_run
409 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
410 _ -> panic "cmCompileExpr"
413 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
416 -----------------------------------------------------------------------------
417 -- Unload the compilation manager's state: everything it knows about the
418 -- current collection of modules in the Home package.
420 cmUnload :: CmState -> DynFlags -> IO CmState
421 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
422 = do -- Throw away the old home dir cache
425 -- Unload everything the linker knows about
426 new_pls <- CmLink.unload mode dflags [] pls
428 -- Start with a fresh CmState, but keep the PersistentCompilerState
429 new_state <- cmInit mode
430 return new_state{ pcs=pcs, pls=new_pls }
433 -----------------------------------------------------------------------------
434 -- Trace dependency graph
436 -- This is a seperate pass so that the caller can back off and keep
437 -- the current state if the downsweep fails.
439 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
440 cmDepAnal cmstate dflags rootnames
441 = do showPass dflags "Chasing dependencies"
442 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
443 hPutStrLn stderr (showSDoc (hcat [
444 text progName, text ": chasing modules from: ",
445 hcat (punctuate comma (map text rootnames))]))
446 downsweep rootnames (mg cmstate)
448 -----------------------------------------------------------------------------
449 -- The real business of the compilation manager: given a system state and
450 -- a module name, try and bring the module up to date, probably changing
451 -- the system state at the same time.
453 cmLoadModules :: CmState
456 -> IO (CmState, -- new state
457 Bool, -- was successful
458 [String]) -- list of modules loaded
460 cmLoadModules cmstate1 dflags mg2unsorted
461 = do -- version 1's are the original, before downsweep
462 let pls1 = pls cmstate1
463 let pcs1 = pcs cmstate1
464 let hst1 = hst cmstate1
465 let hit1 = hit cmstate1
466 -- similarly, ui1 is the (complete) set of linkables from
467 -- the previous pass, if any.
468 let ui1 = ui cmstate1
470 let ghci_mode = gmode cmstate1 -- this never changes
472 -- Do the downsweep to reestablish the module graph
473 let verb = verbosity dflags
475 -- Find out if we have a Main module
477 = any ((=="Main").moduleNameUserString.name_of_summary)
480 let mg2unsorted_names = map name_of_summary mg2unsorted
482 -- reachable_from follows source as well as normal imports
483 let reachable_from :: ModuleName -> [ModuleName]
484 reachable_from = downwards_closure_of_module mg2unsorted
486 -- should be cycle free; ignores 'import source's
487 let mg2 = topological_sort False mg2unsorted
488 -- ... whereas this takes them into account. Used for
489 -- backing out partially complete cycles following a failed
490 -- upsweep, and for removing from hst/hit all the modules
491 -- not in strict downwards closure, during calls to compile.
492 let mg2_with_srcimps = topological_sort True mg2unsorted
494 -- Sort out which linkables we wish to keep in the unlinked image.
495 -- See getValidLinkables below for details.
496 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
498 -- when (verb >= 2) $
499 -- putStrLn (showSDoc (text "Valid linkables:"
500 -- <+> ppr valid_linkables))
502 -- Figure out a stable set of modules which can be retained
503 -- the top level envs, to avoid upsweeping them. Goes to a
504 -- bit of trouble to avoid upsweeping module cycles.
506 -- Construct a set S of stable modules like this:
507 -- Travel upwards, over the sccified graph. For each scc
508 -- of modules ms, add ms to S only if:
509 -- 1. All home imports of ms are either in ms or S
510 -- 2. A valid linkable exists for each module in ms
512 stable_mods <- preUpsweep valid_linkables hit1
513 mg2unsorted_names [] mg2_with_srcimps
516 = concatMap (findInSummaries mg2unsorted) stable_mods
519 = filter (\m -> linkableModName m `elem` stable_mods)
523 putStrLn (showSDoc (text "Stable modules:"
524 <+> sep (map (text.moduleNameUserString) stable_mods)))
526 -- unload any modules which aren't going to be re-linked this
528 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
530 -- We could at this point detect cycles which aren't broken by
531 -- a source-import, and complain immediately, but it seems better
532 -- to let upsweep_mods do this, so at least some useful work gets
533 -- done before the upsweep is abandoned.
535 = filter (\scc -> any (`notElem` stable_mods)
536 (map name_of_summary (flattenSCC scc)))
539 --hPutStrLn stderr "after tsort:\n"
540 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
542 -- Because we don't take into account source imports when doing
543 -- the topological sort, there shouldn't be any cycles in mg2.
544 -- If there is, we complain and give up -- the user needs to
545 -- break the cycle using a boot file.
547 -- Now do the upsweep, calling compile for each module in
548 -- turn. Final result is version 3 of everything.
550 let threaded2 = CmThreaded pcs1 hst1 hit1
552 -- clean up between compilations
553 let cleanup = cleanTempFilesExcept verb
554 (ppFilesFromSummaries (flattenSCCs upsweep_these))
556 (upsweep_complete_success, threaded3, modsUpswept, newLis)
557 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
558 threaded2 cleanup upsweep_these
560 let ui3 = add_to_ui valid_linkables newLis
561 let (CmThreaded pcs3 hst3 hit3) = threaded3
563 -- At this point, modsUpswept and newLis should have the same
564 -- length, so there is one new (or old) linkable for each
565 -- mod which was processed (passed to compile).
567 -- Make modsDone be the summaries for each home module now
568 -- available; this should equal the domains of hst3 and hit3.
569 -- (NOT STRICTLY TRUE if an interactive session was started
570 -- with some object on disk ???)
571 -- Get in in a roughly top .. bottom order (hence reverse).
573 let modsDone = reverse modsUpswept ++ stable_summaries
575 -- Try and do linking in some form, depending on whether the
576 -- upsweep was completely or only partially successful.
578 if upsweep_complete_success
581 -- Easy; just relink it all.
582 do when (verb >= 2) $
583 hPutStrLn stderr "Upsweep completely successful."
585 -- clean up after ourselves
586 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
588 -- issue a warning for the confusing case where the user said '-o foo'
589 -- but we're not going to do any linking.
590 ofile <- readIORef v_Output_file
591 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
593 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
595 -- link everything together
596 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
598 cmLoadFinish True linkresult
599 hst3 hit3 ui3 modsDone ghci_mode pcs3
602 -- Tricky. We need to back out the effects of compiling any
603 -- half-done cycles, both so as to clean up the top level envs
604 -- and to avoid telling the interactive linker to link them.
605 do when (verb >= 2) $
606 hPutStrLn stderr "Upsweep partially successful."
609 = map name_of_summary modsDone
610 let mods_to_zap_names
611 = findPartiallyCompletedCycles modsDone_names
614 = filter ((`notElem` mods_to_zap_names).name_of_summary)
617 let (hst4, hit4, ui4)
618 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
621 -- clean up after ourselves
622 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
624 -- link everything together
625 linkresult <- link ghci_mode dflags False ui4 pls2
627 cmLoadFinish False linkresult
628 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
631 -- Finish up after a cmLoad.
633 -- If the link failed, unload everything and return.
634 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
635 dflags <- getDynFlags
636 new_pls <- CmLink.unload ghci_mode dflags [] pls
637 new_state <- cmInit ghci_mode
638 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
640 -- Empty the interactive context and set the module context to the topmost
641 -- newly loaded module, or the Prelude if none were loaded.
642 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
643 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
644 gmode=ghci_mode, pcs=pcs, pls=pls,
645 ic = emptyInteractiveContext }
646 mods_loaded = map (moduleNameUserString.name_of_summary) mods
648 return (new_cmstate, ok, mods_loaded)
650 -- used to fish out the preprocess output files for the purposes
652 ppFilesFromSummaries summaries
653 = [ fn | Just fn <- map toPpFile summaries ]
656 | hspp /= ml_hs_file loc = hspp
657 | otherwise = Nothing
659 loc = ms_location sum
660 hspp = ml_hspp_file loc
663 -----------------------------------------------------------------------------
666 -- For each module (or SCC of modules), we take:
668 -- - an on-disk linkable, if this is the first time around and one
671 -- - the old linkable, otherwise (and if one is available).
673 -- and we throw away the linkable if it is older than the source
674 -- file. We ignore the on-disk linkables unless all of the dependents
675 -- of this SCC also have on-disk linkables.
677 -- If a module has a valid linkable, then it may be STABLE (see below),
678 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
681 -- ToDo: this pass could be merged with the preUpsweep.
684 :: [Linkable] -- old linkables
685 -> [ModuleName] -- all home modules
686 -> [SCC ModSummary] -- all modules in the program, dependency order
687 -> IO [Linkable] -- still-valid linkables
689 getValidLinkables old_linkables all_home_mods module_graph
690 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
692 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
694 scc = flattenSCC scc0
695 scc_names = map name_of_summary scc
696 home_module m = m `elem` all_home_mods && m `notElem` scc_names
697 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
698 -- NOTE: ms_imps, not ms_allimps above. We don't want to
699 -- force a module's SOURCE imports to be already compiled for
700 -- its object linkable to be valid.
702 has_object m = case findModuleLinkable_maybe new_linkables m of
704 Just l -> isObjectLinkable l
706 objects_allowed = all has_object scc_allhomeimps
710 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
712 -- since an scc can contain only all objects or no objects at all,
713 -- we have to check whether we got all objects or not, and re-do
714 -- the linkable check if not.
716 <- if objects_allowed && not (all isObjectLinkable these_linkables)
717 then foldM (getValidLinkable old_linkables False) [] scc
718 else return these_linkables
720 return (adjusted_linkables ++ new_linkables)
723 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
725 getValidLinkable old_linkables objects_allowed new_linkables summary
726 = do let mod_name = name_of_summary summary
729 <- if (not objects_allowed)
731 else case ml_obj_file (ms_location summary) of
732 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
733 Nothing -> return Nothing
735 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
738 Just l | not (isObjectLinkable l) || stillThere l
740 -- ToDo: emit a warning if not (stillThere l)
743 -- make sure that if we had an old disk linkable around, that it's
744 -- still there on the disk (in case we need to re-link it).
746 case maybe_disk_linkable of
748 Just l_disk -> linkableTime l == linkableTime l_disk
750 -- we only look for objects on disk the first time around;
751 -- if the user compiles a module on the side during a GHCi session,
752 -- it won't be picked up until the next ":load". This is what the
753 -- "null old_linkables" test below is.
754 linkable | null old_linkables = maybeToList maybe_disk_linkable
755 | otherwise = maybeToList maybe_old_linkable
757 -- only linkables newer than the source code are valid
758 src_date = ms_hs_date summary
761 = filter (\l -> linkableTime l >= src_date) linkable
762 -- why '>=' rather than '>' above? If the filesystem stores
763 -- times to the nearset second, we may occasionally find that
764 -- the object & source have the same modification time,
765 -- especially if the source was automatically generated
766 -- and compiled. Using >= is slightly unsafe, but it matches
769 return (valid_linkable ++ new_linkables)
772 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
773 maybe_getFileLinkable mod_name obj_fn
774 = do obj_exist <- doesFileExist obj_fn
778 do let stub_fn = case splitFilename3 obj_fn of
779 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
780 stub_exist <- doesFileExist stub_fn
781 obj_time <- getModificationTime obj_fn
783 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
784 else return (Just (LM obj_time mod_name [DotO obj_fn]))
787 -----------------------------------------------------------------------------
788 -- Do a pre-upsweep without use of "compile", to establish a
789 -- (downward-closed) set of stable modules for which we won't call compile.
792 -- * has a valid linkable (see getValidLinkables above)
793 -- * depends only on stable modules
794 -- * has an interface in the HIT (interactive mode only)
796 preUpsweep :: [Linkable] -- new valid linkables
798 -> [ModuleName] -- names of all mods encountered in downsweep
799 -> [ModuleName] -- accumulating stable modules
800 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
801 -> IO [ModuleName] -- stable modules
803 preUpsweep valid_lis hit all_home_mods stable [] = return stable
804 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
805 = do let scc = flattenSCC scc0
806 scc_allhomeimps :: [ModuleName]
808 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
809 all_imports_in_scc_or_stable
810 = all in_stable_or_scc scc_allhomeimps
812 = map name_of_summary scc
814 = m `elem` scc_names || m `elem` stable
816 -- now we check for valid linkables: each module in the SCC must
817 -- have a valid linkable (see getValidLinkables above).
818 has_valid_linkable new_summary
819 = isJust (findModuleLinkable_maybe valid_lis modname)
820 where modname = name_of_summary new_summary
822 has_interface summary = ms_mod summary `elemUFM` hit
824 scc_is_stable = all_imports_in_scc_or_stable
825 && all has_valid_linkable scc
826 && all has_interface scc
829 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
830 else preUpsweep valid_lis hit all_home_mods stable sccs
833 -- Helper for preUpsweep. Assuming that new_summary's imports are all
834 -- stable (in the sense of preUpsweep), determine if new_summary is itself
835 -- stable, and, if so, in batch mode, return its linkable.
836 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
837 findInSummaries old_summaries mod_name
838 = [s | s <- old_summaries, name_of_summary s == mod_name]
840 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
841 findModInSummaries old_summaries mod
842 = case [s | s <- old_summaries, ms_mod s == mod] of
846 -- Return (names of) all those in modsDone who are part of a cycle
847 -- as defined by theGraph.
848 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
849 findPartiallyCompletedCycles modsDone theGraph
853 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
854 chew ((CyclicSCC vs):rest)
855 = let names_in_this_cycle = nub (map name_of_summary vs)
857 = nub ([done | done <- modsDone,
858 done `elem` names_in_this_cycle])
859 chewed_rest = chew rest
861 if not (null mods_in_this_cycle)
862 && length mods_in_this_cycle < length names_in_this_cycle
863 then mods_in_this_cycle ++ chewed_rest
867 -- Add the given (LM-form) Linkables to the UI, overwriting previous
868 -- versions if they exist.
869 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
871 = filter (not_in lis) ui ++ lis
873 not_in :: [Linkable] -> Linkable -> Bool
875 = all (\l -> linkableModName l /= mod) lis
876 where mod = linkableModName li
879 data CmThreaded -- stuff threaded through individual module compilations
880 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
883 -- Compile multiple modules, stopping as soon as an error appears.
884 -- There better had not be any cyclic groups here -- we check for them.
885 upsweep_mods :: GhciMode
887 -> UnlinkedImage -- valid linkables
888 -> (ModuleName -> [ModuleName]) -- to construct downward closures
889 -> CmThreaded -- PCS & HST & HIT
890 -> IO () -- how to clean up unwanted tmp files
891 -> [SCC ModSummary] -- mods to do (the worklist)
892 -- ...... RETURNING ......
893 -> IO (Bool{-complete success?-},
895 [ModSummary], -- mods which succeeded
896 [Linkable]) -- new linkables
898 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
900 = return (True, threaded, [], [])
902 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
904 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
905 unwords (map (moduleNameUserString.name_of_summary) ms))
906 return (False, threaded, [], [])
908 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
909 ((AcyclicSCC mod):mods)
910 = do --case threaded of
911 -- CmThreaded pcsz hstz hitz
912 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
914 (threaded1, maybe_linkable)
915 <- upsweep_mod ghci_mode dflags oldUI threaded mod
916 (reachable_from (name_of_summary mod))
918 -- remove unwanted tmp files between compilations
921 case maybe_linkable of
923 -> -- No errors; do the rest
924 do (restOK, threaded2, modOKs, linkables)
925 <- upsweep_mods ghci_mode dflags oldUI reachable_from
926 threaded1 cleanup mods
927 return (restOK, threaded2, mod:modOKs, linkable:linkables)
928 Nothing -- we got a compilation error; give up now
929 -> return (False, threaded1, [], [])
932 -- Compile a single module. Always produce a Linkable for it if
933 -- successful. If no compilation happened, return the old Linkable.
934 upsweep_mod :: GhciMode
940 -> IO (CmThreaded, Maybe Linkable)
942 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
944 let mod_name = name_of_summary summary1
946 let (CmThreaded pcs1 hst1 hit1) = threaded1
947 let old_iface = lookupUFM hit1 mod_name
949 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
951 source_unchanged = isJust maybe_old_linkable
953 reachable_only = filter (/= (name_of_summary summary1))
956 -- in interactive mode, all home modules below us *must* have an
957 -- interface in the HIT. We never demand-load home interfaces in
959 (hst1_strictDC, hit1_strictDC, [])
960 = ASSERT(ghci_mode == Batch ||
961 all (`elemUFM` hit1) reachable_only)
962 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
965 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
968 | Just l <- maybe_old_linkable, isObjectLinkable l = True
971 compresult <- compile ghci_mode summary1 source_unchanged
972 have_object old_iface hst1_strictDC hit1_strictDC pcs1
976 -- Compilation "succeeded", and may or may not have returned a new
977 -- linkable (depending on whether compilation was actually performed
979 CompOK pcs2 new_details new_iface maybe_new_linkable
980 -> do let hst2 = addToUFM hst1 mod_name new_details
981 hit2 = addToUFM hit1 mod_name new_iface
982 threaded2 = CmThreaded pcs2 hst2 hit2
984 return (threaded2, if isJust maybe_new_linkable
985 then maybe_new_linkable
986 else Just old_linkable)
988 -- Compilation failed. compile may still have updated
991 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
992 return (threaded2, Nothing)
994 -- Filter modules in the top level envs (HST, HIT, UI).
995 retainInTopLevelEnvs :: [ModuleName]
996 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
997 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
998 retainInTopLevelEnvs keep_these (hst, hit, ui)
999 = (retainInUFM hst keep_these,
1000 retainInUFM hit keep_these,
1001 filterModuleLinkables (`elem` keep_these) ui
1004 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1005 retainInUFM ufm keys_to_keep
1006 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1007 maybeLookupUFM ufm u
1008 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1010 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1011 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1012 downwards_closure_of_module summaries root
1013 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1014 toEdge summ = (name_of_summary summ,
1015 filter (`elem` all_mods) (ms_allimps summ))
1017 all_mods = map name_of_summary summaries
1019 res = simple_transitive_closure (map toEdge summaries) [root]
1021 -- trace (showSDoc (text "DC of mod" <+> ppr root
1022 -- <+> text "=" <+> ppr res)) $
1025 -- Calculate transitive closures from a set of roots given an adjacency list
1026 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1027 simple_transitive_closure graph set
1028 = let set2 = nub (concatMap dsts set ++ set)
1029 dsts node = fromMaybe [] (lookup node graph)
1031 if length set == length set2
1033 else simple_transitive_closure graph set2
1036 -- Calculate SCCs of the module graph, with or without taking into
1037 -- account source imports.
1038 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1039 topological_sort include_source_imports summaries
1041 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1043 = (summ, name_of_summary summ,
1044 (if include_source_imports
1045 then ms_srcimps summ else []) ++ ms_imps summ)
1047 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1048 mash_edge (summ, m, m_imports)
1049 = case lookup m key_map of
1050 Nothing -> panic "reverse_topological_sort"
1051 Just mk -> (summ, mk,
1052 -- ignore imports not from the home package
1053 catMaybes (map (flip lookup key_map) m_imports))
1055 edges = map toEdge summaries
1056 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1057 scc_input = map mash_edge edges
1058 sccs = stronglyConnComp scc_input
1063 -----------------------------------------------------------------------------
1064 -- Downsweep (dependency analysis)
1066 -- Chase downwards from the specified root set, returning summaries
1067 -- for all home modules encountered. Only follow source-import
1070 -- We pass in the previous collection of summaries, which is used as a
1071 -- cache to avoid recalculating a module summary if the source is
1074 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1075 downsweep roots old_summaries
1076 = do rootSummaries <- mapM getRootSummary roots
1078 <- loop (concat (map ms_imps rootSummaries))
1079 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1080 let mod = ms_mod s, isHomeModule mod
1082 return all_summaries
1084 getRootSummary :: FilePath -> IO ModSummary
1086 | haskellish_src_file file
1087 = do exists <- doesFileExist file
1088 if exists then summariseFile file else do
1089 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1091 = do exists <- doesFileExist hs_file
1092 if exists then summariseFile hs_file else do
1093 exists <- doesFileExist lhs_file
1094 if exists then summariseFile lhs_file else do
1095 let mod_name = mkModuleName file
1096 maybe_summary <- getSummary mod_name
1097 case maybe_summary of
1098 Nothing -> packageModErr mod_name
1101 hs_file = file ++ ".hs"
1102 lhs_file = file ++ ".lhs"
1104 getSummary :: ModuleName -> IO (Maybe ModSummary)
1106 = do found <- findModule nm
1108 Just (mod, location) -> do
1109 let old_summary = findModInSummaries old_summaries mod
1110 summarise mod location old_summary
1112 Nothing -> throwDyn (CmdLineError
1113 ("can't find module `"
1114 ++ showSDoc (ppr nm) ++ "'"))
1116 -- loop invariant: env doesn't contain package modules
1117 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1118 loop [] env = return (moduleEnvElts env)
1120 = do -- imports for modules we don't already have
1121 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1124 needed_summaries <- mapM getSummary needed_imps
1126 -- get just the "home" modules
1127 let new_home_summaries = [ s | Just s <- needed_summaries ]
1129 -- loop, checking the new imports
1130 let new_imps = concat (map ms_imps new_home_summaries)
1131 loop new_imps (extendModuleEnvList env
1132 [ (ms_mod s, s) | s <- new_home_summaries ])
1134 -----------------------------------------------------------------------------
1135 -- Summarising modules
1137 -- We have two types of summarisation:
1139 -- * Summarise a file. This is used for the root module(s) passed to
1140 -- cmLoadModules. The file is read, and used to determine the root
1141 -- module name. The module name may differ from the filename.
1143 -- * Summarise a module. We are given a module name, and must provide
1144 -- a summary. The finder is used to locate the file in which the module
1147 summariseFile :: FilePath -> IO ModSummary
1149 = do hspp_fn <- preprocess file
1150 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1152 let (path, basename, _ext) = splitFilename3 file
1155 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1158 <- case ml_hs_file location of
1159 Nothing -> noHsFileErr mod_name
1160 Just src_fn -> getModificationTime src_fn
1162 return (ModSummary mod
1163 location{ml_hspp_file=Just hspp_fn}
1164 srcimps imps src_timestamp)
1166 -- Summarise a module, and pick up source and timestamp.
1167 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1168 -> IO (Maybe ModSummary)
1169 summarise mod location old_summary
1170 | not (isHomeModule mod) = return Nothing
1172 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1174 case ml_hs_file location of {
1175 Nothing -> noHsFileErr mod;
1178 src_timestamp <- getModificationTime src_fn
1180 -- return the cached summary if the source didn't change
1181 case old_summary of {
1182 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1185 hspp_fn <- preprocess hs_fn
1186 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1188 when (mod_name /= moduleName mod) $
1189 throwDyn (ProgramError
1190 (showSDoc (text hs_fn
1191 <> text ": file name does not match module name"
1192 <+> quotes (ppr (moduleName mod)))))
1194 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1195 srcimps imps src_timestamp))
1201 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1204 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1205 quotes (ppr mod) <+>
1206 text "is a package module")))