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 -> 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)
40 cmCompileExpr, -- :: CmState -> DynFlags -> String
41 -- -> IO (CmState, Maybe HValue)
46 #include "HsVersions.h"
51 import DriverState ( v_Output_file )
56 import HscMain ( initPersistentCompilerState, hscThing )
58 import HscMain ( initPersistentCompilerState )
61 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
63 import Rename ( mkGlobalContext )
64 import RdrName ( emptyRdrEnv )
68 import Unique ( Uniquable )
69 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
70 import ErrUtils ( showPass )
71 import SysTools ( cleanTempFilesExcept )
75 import CmdLineOpts ( DynFlags(..), getDynFlags )
80 import RdrName ( lookupRdrEnv )
81 import Id ( idType, idName )
83 import Type ( tidyType )
84 import VarEnv ( emptyTidyEnv )
85 import BasicTypes ( Fixity, defaultFixity )
86 import Interpreter ( HValue )
87 import HscMain ( hscStmt )
88 import PrelGHC ( unsafeCoerce# )
92 import Exception ( Exception, try )
96 import Exception ( throwDyn )
99 import Directory ( getModificationTime, doesFileExist )
108 -- Persistent state for the entire system
111 hst :: HomeSymbolTable, -- home symbol table
112 hit :: HomeIfaceTable, -- home interface table
113 ui :: UnlinkedImage, -- the unlinked images
114 mg :: ModuleGraph, -- the module graph
115 gmode :: GhciMode, -- NEVER CHANGES
116 ic :: InteractiveContext, -- command-line binding info
118 pcs :: PersistentCompilerState, -- compile's persistent state
119 pls :: PersistentLinkerState -- link's persistent state
122 emptyCmState :: GhciMode -> IO CmState
124 = do pcs <- initPersistentCompilerState
126 return (CmState { hst = emptySymbolTable,
127 hit = emptyIfaceTable,
131 ic = emptyInteractiveContext,
135 emptyInteractiveContext
136 = InteractiveContext { ic_toplev_scope = [],
138 ic_rn_gbl_env = emptyRdrEnv,
139 ic_print_unqual = alwaysQualify,
140 ic_rn_local_env = emptyRdrEnv,
141 ic_type_env = emptyTypeEnv }
144 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
145 emptyUI :: UnlinkedImage
148 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
149 emptyMG :: ModuleGraph
152 -----------------------------------------------------------------------------
153 -- Produce an initial CmState.
155 cmInit :: GhciMode -> IO CmState
156 cmInit mode = emptyCmState mode
158 -----------------------------------------------------------------------------
159 -- Setting the context doesn't throw away any bindings; the bindings
160 -- we've built up in the InteractiveContext simply move to the new
161 -- module. They always shadow anything in scope in the current context.
164 :: CmState -> DynFlags
165 -> [String] -- take the top-level scopes of these modules
166 -> [String] -- and the just the exports from these
168 cmSetContext cmstate dflags toplevs exports = do
169 let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
171 toplev_mods <- mapM (getTopLevModule hit) (map mkModuleName toplevs)
172 export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
174 (new_pcs, print_unqual, maybe_env)
175 <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
178 Nothing -> return cmstate
179 Just env -> return cmstate{ pcs = new_pcs,
180 ic = old_ic{ ic_toplev_scope = toplev_mods,
181 ic_exports = export_mods,
183 ic_print_unqual = print_unqual } }
185 getTopLevModule hit mn =
186 case lookupModuleEnvByName hit mn of
188 | Just _ <- mi_globals iface -> return (mi_module iface)
189 _other -> throwDyn (CmdLineError (
190 "cannot enter the top-level scope of a compiled module (module `" ++
191 moduleNameUserString mn ++ "')"))
193 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
194 moduleNameToModule hit mn = do
195 case lookupModuleEnvByName hit mn of
196 Just iface -> return (mi_module iface)
197 _not_a_home_module -> do
198 maybe_stuff <- findModule mn
200 Nothing -> throwDyn (CmdLineError ("can't find module `"
201 ++ moduleNameUserString mn ++ "'"))
202 Just (m,_) -> return m
204 cmGetContext :: CmState -> IO ([String],[String])
205 cmGetContext CmState{ic=ic} =
206 return (map moduleUserString (ic_toplev_scope ic),
207 map moduleUserString (ic_exports ic))
209 cmModuleIsInterpreted :: CmState -> String -> IO Bool
210 cmModuleIsInterpreted cmstate str
211 = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
212 Just iface -> return (not (isNothing (mi_globals iface)))
213 _not_a_home_module -> return False
215 -----------------------------------------------------------------------------
216 -- cmInfoThing: convert a String to a TyThing
218 -- A string may refer to more than one TyThing (eg. a constructor,
219 -- and type constructor), so we return a list of all the possible TyThings.
222 cmInfoThing :: CmState -> DynFlags -> String
223 -> IO (CmState, PrintUnqualified, [(TyThing,Fixity)])
224 cmInfoThing cmstate dflags id
225 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
226 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
227 return (cmstate{ pcs=new_pcs }, unqual, pairs)
229 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
230 unqual = ic_print_unqual icontext
232 getFixity :: PersistentCompilerState -> Name -> Fixity
234 | Just iface <- lookupModuleEnv iface_table (nameModule name),
235 Just fixity <- lookupNameEnv (mi_fixities iface) name
239 where iface_table | isHomePackageName name = hit
240 | otherwise = pcs_PIT pcs
243 -----------------------------------------------------------------------------
244 -- cmRunStmt: Run a statement/expr.
248 = CmRunOk [Name] -- names bound by this evaluation
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
294 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
295 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
300 return ( cmstate{ pcs=new_pcs, ic=new_ic },
303 -- Get the newly bound things, and bind them.
304 -- Don't forget to delete any shadowed bindings from the
305 -- closure_env, lest we end up with a space leak.
306 pls <- delListFromClosureEnv pls shadowed
307 new_pls <- addListToClosureEnv pls (zip names hvals)
309 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
312 -- We run the statement in a "sandbox", which amounts to calling into
313 -- the RTS to request a new main thread. The main benefit is that
314 -- there's no danger that exceptions raised by the expression can
315 -- affect the interpreter.
317 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
319 st_thing <- newStablePtr (Exception.try thing)
320 alloca $ \ p_st_result -> do
321 stat <- rts_evalStableIO st_thing p_st_result
322 freeStablePtr st_thing
324 then do st_result <- peek p_st_result
325 result <- deRefStablePtr st_result
326 freeStablePtr st_result
327 return (Right result)
329 return (Left (fromIntegral stat))
331 foreign import "rts_evalStableIO" {- safe -}
332 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
333 -- more informative than the C type!
336 -----------------------------------------------------------------------------
337 -- cmTypeOfExpr: returns a string representing the type of an expression
340 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
341 cmTypeOfExpr cmstate dflags expr
342 = do (new_pcs, maybe_stuff)
343 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
345 let new_cmstate = cmstate{pcs = new_pcs}
348 Nothing -> return (new_cmstate, Nothing)
349 Just (_, ty, _) -> return (new_cmstate, Just str)
351 str = showSDocForUser unqual (ppr tidy_ty)
352 unqual = ic_print_unqual ic
353 tidy_ty = tidyType emptyTidyEnv ty
355 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
358 -----------------------------------------------------------------------------
359 -- cmTypeOfName: returns a string representing the type of a name.
362 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
363 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
364 = case lookupNameEnv (ic_type_env ic) name of
365 Nothing -> return Nothing
366 Just (AnId id) -> return (Just str)
368 unqual = ic_print_unqual ic
369 ty = tidyType emptyTidyEnv (idType id)
370 str = showSDocForUser unqual (ppr ty)
372 _ -> panic "cmTypeOfName"
375 -----------------------------------------------------------------------------
376 -- cmCompileExpr: compile an expression and deliver an HValue
379 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
380 cmCompileExpr cmstate dflags expr
382 let InteractiveContext {
383 ic_rn_local_env = rn_env,
384 ic_type_env = type_env } = icontext
386 (new_pcs, maybe_stuff)
387 <- hscStmt dflags hst hit pcs icontext
388 ("let __cmCompileExpr = "++expr) False{-stmt-}
391 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
392 Just (ids, _, bcos) -> do
395 hval <- linkExpr pls bcos
398 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
399 hvals <- thing_to_run
402 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
403 _ -> panic "cmCompileExpr"
406 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
409 -----------------------------------------------------------------------------
410 -- Unload the compilation manager's state: everything it knows about the
411 -- current collection of modules in the Home package.
413 cmUnload :: CmState -> DynFlags -> IO CmState
414 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
415 = do -- Throw away the old home dir cache
418 -- Unload everything the linker knows about
419 new_pls <- CmLink.unload mode dflags [] pls
421 -- Start with a fresh CmState, but keep the PersistentCompilerState
422 new_state <- cmInit mode
423 return new_state{ pcs=pcs, pls=new_pls }
426 -----------------------------------------------------------------------------
427 -- Trace dependency graph
429 -- This is a seperate pass so that the caller can back off and keep
430 -- the current state if the downsweep fails.
432 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
433 cmDepAnal cmstate dflags rootnames
434 = do showPass dflags "Chasing dependencies"
435 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
436 hPutStrLn stderr (showSDoc (hcat [
437 text progName, text ": chasing modules from: ",
438 hcat (punctuate comma (map text rootnames))]))
439 downsweep rootnames (mg cmstate)
441 -----------------------------------------------------------------------------
442 -- The real business of the compilation manager: given a system state and
443 -- a module name, try and bring the module up to date, probably changing
444 -- the system state at the same time.
446 cmLoadModules :: CmState
449 -> IO (CmState, -- new state
450 Bool, -- was successful
451 [String]) -- list of modules loaded
453 cmLoadModules cmstate1 dflags mg2unsorted
454 = do -- version 1's are the original, before downsweep
455 let pls1 = pls cmstate1
456 let pcs1 = pcs cmstate1
457 let hst1 = hst cmstate1
458 let hit1 = hit cmstate1
459 -- similarly, ui1 is the (complete) set of linkables from
460 -- the previous pass, if any.
461 let ui1 = ui cmstate1
463 let ghci_mode = gmode cmstate1 -- this never changes
465 -- Do the downsweep to reestablish the module graph
466 let verb = verbosity dflags
468 -- Find out if we have a Main module
470 = any ((=="Main").moduleNameUserString.name_of_summary)
473 let mg2unsorted_names = map name_of_summary mg2unsorted
475 -- reachable_from follows source as well as normal imports
476 let reachable_from :: ModuleName -> [ModuleName]
477 reachable_from = downwards_closure_of_module mg2unsorted
479 -- should be cycle free; ignores 'import source's
480 let mg2 = topological_sort False mg2unsorted
481 -- ... whereas this takes them into account. Used for
482 -- backing out partially complete cycles following a failed
483 -- upsweep, and for removing from hst/hit all the modules
484 -- not in strict downwards closure, during calls to compile.
485 let mg2_with_srcimps = topological_sort True mg2unsorted
487 -- Sort out which linkables we wish to keep in the unlinked image.
488 -- See getValidLinkables below for details.
489 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
491 -- when (verb >= 2) $
492 -- putStrLn (showSDoc (text "Valid linkables:"
493 -- <+> ppr valid_linkables))
495 -- Figure out a stable set of modules which can be retained
496 -- the top level envs, to avoid upsweeping them. Goes to a
497 -- bit of trouble to avoid upsweeping module cycles.
499 -- Construct a set S of stable modules like this:
500 -- Travel upwards, over the sccified graph. For each scc
501 -- of modules ms, add ms to S only if:
502 -- 1. All home imports of ms are either in ms or S
503 -- 2. A valid linkable exists for each module in ms
505 stable_mods <- preUpsweep valid_linkables hit1
506 mg2unsorted_names [] mg2_with_srcimps
509 = concatMap (findInSummaries mg2unsorted) stable_mods
512 = filter (\m -> linkableModName m `elem` stable_mods)
516 putStrLn (showSDoc (text "Stable modules:"
517 <+> sep (map (text.moduleNameUserString) stable_mods)))
519 -- unload any modules which aren't going to be re-linked this
521 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
523 -- We could at this point detect cycles which aren't broken by
524 -- a source-import, and complain immediately, but it seems better
525 -- to let upsweep_mods do this, so at least some useful work gets
526 -- done before the upsweep is abandoned.
528 = filter (\scc -> any (`notElem` stable_mods)
529 (map name_of_summary (flattenSCC scc)))
532 --hPutStrLn stderr "after tsort:\n"
533 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
535 -- Because we don't take into account source imports when doing
536 -- the topological sort, there shouldn't be any cycles in mg2.
537 -- If there is, we complain and give up -- the user needs to
538 -- break the cycle using a boot file.
540 -- Now do the upsweep, calling compile for each module in
541 -- turn. Final result is version 3 of everything.
543 let threaded2 = CmThreaded pcs1 hst1 hit1
545 -- clean up between compilations
546 let cleanup = cleanTempFilesExcept verb
547 (ppFilesFromSummaries (flattenSCCs upsweep_these))
549 (upsweep_complete_success, threaded3, modsUpswept, newLis)
550 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
551 threaded2 cleanup upsweep_these
553 let ui3 = add_to_ui valid_linkables newLis
554 let (CmThreaded pcs3 hst3 hit3) = threaded3
556 -- At this point, modsUpswept and newLis should have the same
557 -- length, so there is one new (or old) linkable for each
558 -- mod which was processed (passed to compile).
560 -- Make modsDone be the summaries for each home module now
561 -- available; this should equal the domains of hst3 and hit3.
562 -- (NOT STRICTLY TRUE if an interactive session was started
563 -- with some object on disk ???)
564 -- Get in in a roughly top .. bottom order (hence reverse).
566 let modsDone = reverse modsUpswept ++ stable_summaries
568 -- Try and do linking in some form, depending on whether the
569 -- upsweep was completely or only partially successful.
571 if upsweep_complete_success
574 -- Easy; just relink it all.
575 do when (verb >= 2) $
576 hPutStrLn stderr "Upsweep completely successful."
578 -- clean up after ourselves
579 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
581 -- issue a warning for the confusing case where the user said '-o foo'
582 -- but we're not going to do any linking.
583 ofile <- readIORef v_Output_file
584 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
586 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
588 -- link everything together
589 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
591 cmLoadFinish True linkresult
592 hst3 hit3 ui3 modsDone ghci_mode pcs3
595 -- Tricky. We need to back out the effects of compiling any
596 -- half-done cycles, both so as to clean up the top level envs
597 -- and to avoid telling the interactive linker to link them.
598 do when (verb >= 2) $
599 hPutStrLn stderr "Upsweep partially successful."
602 = map name_of_summary modsDone
603 let mods_to_zap_names
604 = findPartiallyCompletedCycles modsDone_names
607 = filter ((`notElem` mods_to_zap_names).name_of_summary)
610 let (hst4, hit4, ui4)
611 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
614 -- clean up after ourselves
615 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
617 -- link everything together
618 linkresult <- link ghci_mode dflags False ui4 pls2
620 cmLoadFinish False linkresult
621 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
624 -- Finish up after a cmLoad.
626 -- If the link failed, unload everything and return.
627 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
628 dflags <- getDynFlags
629 new_pls <- CmLink.unload ghci_mode dflags [] pls
630 new_state <- cmInit ghci_mode
631 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
633 -- Empty the interactive context and set the module context to the topmost
634 -- newly loaded module, or the Prelude if none were loaded.
635 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
636 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
637 gmode=ghci_mode, pcs=pcs, pls=pls,
638 ic = emptyInteractiveContext }
639 mods_loaded = map (moduleNameUserString.name_of_summary) mods
641 return (new_cmstate, ok, mods_loaded)
643 -- used to fish out the preprocess output files for the purposes
645 ppFilesFromSummaries summaries
646 = [ fn | Just fn <- map toPpFile summaries ]
649 | hspp /= ml_hs_file loc = hspp
650 | otherwise = Nothing
652 loc = ms_location sum
653 hspp = ml_hspp_file loc
656 -----------------------------------------------------------------------------
659 -- For each module (or SCC of modules), we take:
661 -- - an on-disk linkable, if this is the first time around and one
664 -- - the old linkable, otherwise (and if one is available).
666 -- and we throw away the linkable if it is older than the source
667 -- file. We ignore the on-disk linkables unless all of the dependents
668 -- of this SCC also have on-disk linkables.
670 -- If a module has a valid linkable, then it may be STABLE (see below),
671 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
674 -- ToDo: this pass could be merged with the preUpsweep.
677 :: [Linkable] -- old linkables
678 -> [ModuleName] -- all home modules
679 -> [SCC ModSummary] -- all modules in the program, dependency order
680 -> IO [Linkable] -- still-valid linkables
682 getValidLinkables old_linkables all_home_mods module_graph
683 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
685 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
687 scc = flattenSCC scc0
688 scc_names = map name_of_summary scc
689 home_module m = m `elem` all_home_mods && m `notElem` scc_names
690 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
691 -- NOTE: ms_imps, not ms_allimps above. We don't want to
692 -- force a module's SOURCE imports to be already compiled for
693 -- its object linkable to be valid.
695 has_object m = case findModuleLinkable_maybe new_linkables m of
697 Just l -> isObjectLinkable l
699 objects_allowed = all has_object scc_allhomeimps
703 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
705 -- since an scc can contain only all objects or no objects at all,
706 -- we have to check whether we got all objects or not, and re-do
707 -- the linkable check if not.
709 <- if objects_allowed && not (all isObjectLinkable these_linkables)
710 then foldM (getValidLinkable old_linkables False) [] scc
711 else return these_linkables
713 return (adjusted_linkables ++ new_linkables)
716 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
718 getValidLinkable old_linkables objects_allowed new_linkables summary
719 = do let mod_name = name_of_summary summary
722 <- if (not objects_allowed)
724 else case ml_obj_file (ms_location summary) of
725 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
726 Nothing -> return Nothing
728 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
731 Just l | not (isObjectLinkable l) || stillThere l
733 -- ToDo: emit a warning if not (stillThere l)
736 -- make sure that if we had an old disk linkable around, that it's
737 -- still there on the disk (in case we need to re-link it).
739 case maybe_disk_linkable of
741 Just l_disk -> linkableTime l == linkableTime l_disk
743 -- we only look for objects on disk the first time around;
744 -- if the user compiles a module on the side during a GHCi session,
745 -- it won't be picked up until the next ":load". This is what the
746 -- "null old_linkables" test below is.
747 linkable | null old_linkables = maybeToList maybe_disk_linkable
748 | otherwise = maybeToList maybe_old_linkable
750 -- only linkables newer than the source code are valid
751 src_date = ms_hs_date summary
754 = filter (\l -> linkableTime l >= src_date) linkable
755 -- why '>=' rather than '>' above? If the filesystem stores
756 -- times to the nearset second, we may occasionally find that
757 -- the object & source have the same modification time,
758 -- especially if the source was automatically generated
759 -- and compiled. Using >= is slightly unsafe, but it matches
762 return (valid_linkable ++ new_linkables)
765 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
766 maybe_getFileLinkable mod_name obj_fn
767 = do obj_exist <- doesFileExist obj_fn
771 do let stub_fn = case splitFilename3 obj_fn of
772 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
773 stub_exist <- doesFileExist stub_fn
774 obj_time <- getModificationTime obj_fn
776 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
777 else return (Just (LM obj_time mod_name [DotO obj_fn]))
780 -----------------------------------------------------------------------------
781 -- Do a pre-upsweep without use of "compile", to establish a
782 -- (downward-closed) set of stable modules for which we won't call compile.
785 -- * has a valid linkable (see getValidLinkables above)
786 -- * depends only on stable modules
787 -- * has an interface in the HIT (interactive mode only)
789 preUpsweep :: [Linkable] -- new valid linkables
791 -> [ModuleName] -- names of all mods encountered in downsweep
792 -> [ModuleName] -- accumulating stable modules
793 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
794 -> IO [ModuleName] -- stable modules
796 preUpsweep valid_lis hit all_home_mods stable [] = return stable
797 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
798 = do let scc = flattenSCC scc0
799 scc_allhomeimps :: [ModuleName]
801 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
802 all_imports_in_scc_or_stable
803 = all in_stable_or_scc scc_allhomeimps
805 = map name_of_summary scc
807 = m `elem` scc_names || m `elem` stable
809 -- now we check for valid linkables: each module in the SCC must
810 -- have a valid linkable (see getValidLinkables above).
811 has_valid_linkable new_summary
812 = isJust (findModuleLinkable_maybe valid_lis modname)
813 where modname = name_of_summary new_summary
815 has_interface summary = ms_mod summary `elemUFM` hit
817 scc_is_stable = all_imports_in_scc_or_stable
818 && all has_valid_linkable scc
819 && all has_interface scc
822 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
823 else preUpsweep valid_lis hit all_home_mods stable sccs
826 -- Helper for preUpsweep. Assuming that new_summary's imports are all
827 -- stable (in the sense of preUpsweep), determine if new_summary is itself
828 -- stable, and, if so, in batch mode, return its linkable.
829 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
830 findInSummaries old_summaries mod_name
831 = [s | s <- old_summaries, name_of_summary s == mod_name]
833 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
834 findModInSummaries old_summaries mod
835 = case [s | s <- old_summaries, ms_mod s == mod] of
839 -- Return (names of) all those in modsDone who are part of a cycle
840 -- as defined by theGraph.
841 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
842 findPartiallyCompletedCycles modsDone theGraph
846 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
847 chew ((CyclicSCC vs):rest)
848 = let names_in_this_cycle = nub (map name_of_summary vs)
850 = nub ([done | done <- modsDone,
851 done `elem` names_in_this_cycle])
852 chewed_rest = chew rest
854 if not (null mods_in_this_cycle)
855 && length mods_in_this_cycle < length names_in_this_cycle
856 then mods_in_this_cycle ++ chewed_rest
860 -- Add the given (LM-form) Linkables to the UI, overwriting previous
861 -- versions if they exist.
862 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
864 = filter (not_in lis) ui ++ lis
866 not_in :: [Linkable] -> Linkable -> Bool
868 = all (\l -> linkableModName l /= mod) lis
869 where mod = linkableModName li
872 data CmThreaded -- stuff threaded through individual module compilations
873 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
876 -- Compile multiple modules, stopping as soon as an error appears.
877 -- There better had not be any cyclic groups here -- we check for them.
878 upsweep_mods :: GhciMode
880 -> UnlinkedImage -- valid linkables
881 -> (ModuleName -> [ModuleName]) -- to construct downward closures
882 -> CmThreaded -- PCS & HST & HIT
883 -> IO () -- how to clean up unwanted tmp files
884 -> [SCC ModSummary] -- mods to do (the worklist)
885 -- ...... RETURNING ......
886 -> IO (Bool{-complete success?-},
888 [ModSummary], -- mods which succeeded
889 [Linkable]) -- new linkables
891 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
893 = return (True, threaded, [], [])
895 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
897 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
898 unwords (map (moduleNameUserString.name_of_summary) ms))
899 return (False, threaded, [], [])
901 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
902 ((AcyclicSCC mod):mods)
903 = do --case threaded of
904 -- CmThreaded pcsz hstz hitz
905 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
907 (threaded1, maybe_linkable)
908 <- upsweep_mod ghci_mode dflags oldUI threaded mod
909 (reachable_from (name_of_summary mod))
911 -- remove unwanted tmp files between compilations
914 case maybe_linkable of
916 -> -- No errors; do the rest
917 do (restOK, threaded2, modOKs, linkables)
918 <- upsweep_mods ghci_mode dflags oldUI reachable_from
919 threaded1 cleanup mods
920 return (restOK, threaded2, mod:modOKs, linkable:linkables)
921 Nothing -- we got a compilation error; give up now
922 -> return (False, threaded1, [], [])
925 -- Compile a single module. Always produce a Linkable for it if
926 -- successful. If no compilation happened, return the old Linkable.
927 upsweep_mod :: GhciMode
933 -> IO (CmThreaded, Maybe Linkable)
935 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
937 let mod_name = name_of_summary summary1
939 let (CmThreaded pcs1 hst1 hit1) = threaded1
940 let old_iface = lookupUFM hit1 mod_name
942 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
944 source_unchanged = isJust maybe_old_linkable
946 reachable_only = filter (/= (name_of_summary summary1))
949 -- in interactive mode, all home modules below us *must* have an
950 -- interface in the HIT. We never demand-load home interfaces in
952 (hst1_strictDC, hit1_strictDC, [])
953 = ASSERT(ghci_mode == Batch ||
954 all (`elemUFM` hit1) reachable_only)
955 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
958 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
961 | Just l <- maybe_old_linkable, isObjectLinkable l = True
964 compresult <- compile ghci_mode summary1 source_unchanged
965 have_object old_iface hst1_strictDC hit1_strictDC pcs1
969 -- Compilation "succeeded", and may or may not have returned a new
970 -- linkable (depending on whether compilation was actually performed
972 CompOK pcs2 new_details new_iface maybe_new_linkable
973 -> do let hst2 = addToUFM hst1 mod_name new_details
974 hit2 = addToUFM hit1 mod_name new_iface
975 threaded2 = CmThreaded pcs2 hst2 hit2
977 return (threaded2, if isJust maybe_new_linkable
978 then maybe_new_linkable
979 else Just old_linkable)
981 -- Compilation failed. compile may still have updated
984 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
985 return (threaded2, Nothing)
987 -- Filter modules in the top level envs (HST, HIT, UI).
988 retainInTopLevelEnvs :: [ModuleName]
989 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
990 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
991 retainInTopLevelEnvs keep_these (hst, hit, ui)
992 = (retainInUFM hst keep_these,
993 retainInUFM hit keep_these,
994 filterModuleLinkables (`elem` keep_these) ui
997 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
998 retainInUFM ufm keys_to_keep
999 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1000 maybeLookupUFM ufm u
1001 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1003 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1004 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1005 downwards_closure_of_module summaries root
1006 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1007 toEdge summ = (name_of_summary summ,
1008 filter (`elem` all_mods) (ms_allimps summ))
1010 all_mods = map name_of_summary summaries
1012 res = simple_transitive_closure (map toEdge summaries) [root]
1014 -- trace (showSDoc (text "DC of mod" <+> ppr root
1015 -- <+> text "=" <+> ppr res)) $
1018 -- Calculate transitive closures from a set of roots given an adjacency list
1019 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1020 simple_transitive_closure graph set
1021 = let set2 = nub (concatMap dsts set ++ set)
1022 dsts node = fromMaybe [] (lookup node graph)
1024 if length set == length set2
1026 else simple_transitive_closure graph set2
1029 -- Calculate SCCs of the module graph, with or without taking into
1030 -- account source imports.
1031 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1032 topological_sort include_source_imports summaries
1034 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1036 = (summ, name_of_summary summ,
1037 (if include_source_imports
1038 then ms_srcimps summ else []) ++ ms_imps summ)
1040 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1041 mash_edge (summ, m, m_imports)
1042 = case lookup m key_map of
1043 Nothing -> panic "reverse_topological_sort"
1044 Just mk -> (summ, mk,
1045 -- ignore imports not from the home package
1046 catMaybes (map (flip lookup key_map) m_imports))
1048 edges = map toEdge summaries
1049 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1050 scc_input = map mash_edge edges
1051 sccs = stronglyConnComp scc_input
1056 -----------------------------------------------------------------------------
1057 -- Downsweep (dependency analysis)
1059 -- Chase downwards from the specified root set, returning summaries
1060 -- for all home modules encountered. Only follow source-import
1063 -- We pass in the previous collection of summaries, which is used as a
1064 -- cache to avoid recalculating a module summary if the source is
1067 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1068 downsweep roots old_summaries
1069 = do rootSummaries <- mapM getRootSummary roots
1071 <- loop (concat (map ms_imps rootSummaries))
1072 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1073 let mod = ms_mod s, isHomeModule mod
1075 return all_summaries
1077 getRootSummary :: FilePath -> IO ModSummary
1079 | haskellish_src_file file
1080 = do exists <- doesFileExist file
1081 if exists then summariseFile file else do
1082 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1084 = do exists <- doesFileExist hs_file
1085 if exists then summariseFile hs_file else do
1086 exists <- doesFileExist lhs_file
1087 if exists then summariseFile lhs_file else do
1088 let mod_name = mkModuleName file
1089 maybe_summary <- getSummary mod_name
1090 case maybe_summary of
1091 Nothing -> packageModErr mod_name
1094 hs_file = file ++ ".hs"
1095 lhs_file = file ++ ".lhs"
1097 getSummary :: ModuleName -> IO (Maybe ModSummary)
1099 = do found <- findModule nm
1101 Just (mod, location) -> do
1102 let old_summary = findModInSummaries old_summaries mod
1103 summarise mod location old_summary
1105 Nothing -> throwDyn (CmdLineError
1106 ("can't find module `"
1107 ++ showSDoc (ppr nm) ++ "'"))
1109 -- loop invariant: env doesn't contain package modules
1110 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1111 loop [] env = return (moduleEnvElts env)
1113 = do -- imports for modules we don't already have
1114 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1117 needed_summaries <- mapM getSummary needed_imps
1119 -- get just the "home" modules
1120 let new_home_summaries = [ s | Just s <- needed_summaries ]
1122 -- loop, checking the new imports
1123 let new_imps = concat (map ms_imps new_home_summaries)
1124 loop new_imps (extendModuleEnvList env
1125 [ (ms_mod s, s) | s <- new_home_summaries ])
1127 -----------------------------------------------------------------------------
1128 -- Summarising modules
1130 -- We have two types of summarisation:
1132 -- * Summarise a file. This is used for the root module(s) passed to
1133 -- cmLoadModules. The file is read, and used to determine the root
1134 -- module name. The module name may differ from the filename.
1136 -- * Summarise a module. We are given a module name, and must provide
1137 -- a summary. The finder is used to locate the file in which the module
1140 summariseFile :: FilePath -> IO ModSummary
1142 = do hspp_fn <- preprocess file
1143 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1145 let (path, basename, _ext) = splitFilename3 file
1148 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1151 <- case ml_hs_file location of
1152 Nothing -> noHsFileErr mod_name
1153 Just src_fn -> getModificationTime src_fn
1155 return (ModSummary mod
1156 location{ml_hspp_file=Just hspp_fn}
1157 srcimps imps src_timestamp)
1159 -- Summarise a module, and pick up source and timestamp.
1160 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1161 -> IO (Maybe ModSummary)
1162 summarise mod location old_summary
1163 | not (isHomeModule mod) = return Nothing
1165 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1167 case ml_hs_file location of {
1168 Nothing -> noHsFileErr mod;
1171 src_timestamp <- getModificationTime src_fn
1173 -- return the cached summary if the source didn't change
1174 case old_summary of {
1175 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1178 hspp_fn <- preprocess hs_fn
1179 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1181 when (mod_name /= moduleName mod) $
1182 throwDyn (ProgramError
1183 (showSDoc (text hs_fn
1184 <> text ": file name does not match module name"
1185 <+> quotes (ppr (moduleName mod)))))
1187 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1188 srcimps imps src_timestamp))
1194 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1197 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1198 quotes (ppr mod) <+>
1199 text "is a package module")))