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
22 cmSetContext, -- :: CmState -> String -> IO CmState
24 cmGetContext, -- :: CmState -> IO String
27 cmInfoThing, -- :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
30 cmRunStmt, -- :: CmState -> DynFlags -> String
31 -- -> IO (CmState, CmRunResult)
33 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
34 -- -> IO (CmState, Maybe String)
36 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
38 cmCompileExpr, -- :: CmState -> DynFlags -> String
39 -- -> IO (CmState, Maybe HValue)#endif
44 #include "HsVersions.h"
49 import DriverState ( v_Output_file )
54 import HscMain ( initPersistentCompilerState, hscThing )
56 import HscMain ( initPersistentCompilerState )
59 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
61 import RdrName ( emptyRdrEnv )
65 import Unique ( Uniquable )
66 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
67 import ErrUtils ( showPass )
68 import SysTools ( cleanTempFilesExcept )
72 import CmdLineOpts ( DynFlags(..), getDynFlags )
77 import RdrName ( lookupRdrEnv )
78 import Id ( idType, idName )
80 import Type ( tidyType )
81 import VarEnv ( emptyTidyEnv )
82 import RnEnv ( unQualInScope, mkIfaceGlobalRdrEnv )
83 import BasicTypes ( Fixity, defaultFixity )
84 import Interpreter ( HValue )
85 import HscMain ( hscStmt )
86 import PrelGHC ( unsafeCoerce# )
90 import Exception ( Exception, try )
94 import Exception ( throwDyn )
97 import Directory ( getModificationTime, doesFileExist )
106 -- Persistent state for the entire system
109 hst :: HomeSymbolTable, -- home symbol table
110 hit :: HomeIfaceTable, -- home interface table
111 ui :: UnlinkedImage, -- the unlinked images
112 mg :: ModuleGraph, -- the module graph
113 gmode :: GhciMode, -- NEVER CHANGES
114 ic :: InteractiveContext, -- command-line binding info
116 pcs :: PersistentCompilerState, -- compile's persistent state
117 pls :: PersistentLinkerState -- link's persistent state
120 emptyCmState :: GhciMode -> Module -> IO CmState
121 emptyCmState gmode mod
122 = do pcs <- initPersistentCompilerState
124 return (CmState { hst = emptySymbolTable,
125 hit = emptyIfaceTable,
129 ic = emptyInteractiveContext mod,
133 emptyInteractiveContext mod
134 = InteractiveContext { ic_module = mod,
135 ic_rn_env = emptyRdrEnv,
136 ic_type_env = emptyTypeEnv }
138 defaultCurrentModuleName = mkModuleName "Prelude"
139 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
142 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
143 emptyUI :: UnlinkedImage
146 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
147 emptyMG :: ModuleGraph
150 -----------------------------------------------------------------------------
151 -- Produce an initial CmState.
153 cmInit :: GhciMode -> IO CmState
155 prel <- moduleNameToModule defaultCurrentModuleName
156 writeIORef defaultCurrentModule prel
157 emptyCmState mode prel
159 -----------------------------------------------------------------------------
160 -- Setting the context doesn't throw away any bindings; the bindings
161 -- we've built up in the InteractiveContext simply move to the new
162 -- module. They always shadow anything in scope in the current context.
164 cmSetContext :: CmState -> String -> IO CmState
165 cmSetContext cmstate str
166 = do let mn = mkModuleName str
167 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
169 m <- case lookup mn modules_loaded of
172 mod <- moduleNameToModule mn
174 then throwDyn (CmdLineError (showSDoc
175 (quotes (ppr (moduleName mod))
176 <+> text "is not currently loaded")))
179 return cmstate{ ic = (ic cmstate){ic_module=m} }
181 cmGetContext :: CmState -> IO String
182 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
184 moduleNameToModule :: ModuleName -> IO Module
185 moduleNameToModule mn
186 = do maybe_stuff <- findModule mn
188 Nothing -> throwDyn (CmdLineError ("can't find module `"
189 ++ moduleNameUserString mn ++ "'"))
190 Just (m,_) -> return m
192 -----------------------------------------------------------------------------
193 -- cmInfoThing: convert a String to a TyThing
195 -- A string may refer to more than one TyThing (eg. a constructor,
196 -- and type constructor), so we return a list of all the possible TyThings.
199 cmInfoThing :: CmState -> DynFlags -> String
200 -> IO (CmState, PrintUnqualified, [(TyThing,Fixity)])
201 cmInfoThing cmstate dflags id
202 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
203 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
204 return (cmstate{ pcs=new_pcs }, unqual, pairs)
206 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
207 unqual = getUnqual pcs hit icontext
209 getFixity :: PersistentCompilerState -> Name -> Fixity
211 | Just iface <- lookupModuleEnv iface_table (nameModule name),
212 Just fixity <- lookupNameEnv (mi_fixities iface) name
216 where iface_table | isHomePackageName name = hit
217 | otherwise = pcs_PIT pcs
220 -----------------------------------------------------------------------------
221 -- cmRunStmt: Run a statement/expr.
225 = CmRunOk [Name] -- names bound by this evaluation
227 | CmRunDeadlocked -- statement deadlocked
228 | CmRunException Exception -- statement raised an exception
230 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
231 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
234 let InteractiveContext {
236 ic_type_env = type_env } = icontext
238 (new_pcs, maybe_stuff)
239 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
242 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
243 Just (ids, _, bcos) -> do
245 -- update the interactive context
247 names = map idName ids
249 -- these names have just been shadowed
250 shadowed = [ n | r <- map nameRdrName names,
251 Just n <- [lookupRdrEnv rn_env r] ]
253 new_rn_env = extendLocalRdrEnv rn_env names
255 -- remove any shadowed bindings from the type_env
256 filtered_type_env = delListFromNameEnv type_env shadowed
258 new_type_env = extendNameEnvList filtered_type_env
259 [ (getName id, AnId id) | id <- ids]
261 new_ic = icontext { ic_rn_env = new_rn_env,
262 ic_type_env = new_type_env }
265 hval <- linkExpr pls bcos
268 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
269 either_hvals <- sandboxIO thing_to_run
273 -> return ( cmstate{ pcs=new_pcs, ic=new_ic },
276 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
277 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
282 return ( cmstate{ pcs=new_pcs, ic=new_ic },
285 -- Get the newly bound things, and bind them.
286 -- Don't forget to delete any shadowed bindings from the
287 -- closure_env, lest we end up with a space leak.
288 pls <- delListFromClosureEnv pls shadowed
289 new_pls <- addListToClosureEnv pls (zip names hvals)
291 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
294 -- We run the statement in a "sandbox", which amounts to calling into
295 -- the RTS to request a new main thread. The main benefit is that we
296 -- get to detect a deadlock this way, but also there's no danger that
297 -- exceptions raised by the expression can affect the interpreter.
299 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
301 st_thing <- newStablePtr (Exception.try thing)
302 alloca $ \ p_st_result -> do
303 stat <- rts_evalStableIO st_thing p_st_result
304 freeStablePtr st_thing
306 then do st_result <- peek p_st_result
307 result <- deRefStablePtr st_result
308 freeStablePtr st_result
309 return (Right result)
311 return (Left (fromIntegral stat))
313 -- ToDo: slurp this in from ghc/includes/RtsAPI.h somehow
314 dEADLOCKED = 4 :: Int
316 foreign import "rts_evalStableIO" {- safe -}
317 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
318 -- more informative than the C type!
321 -----------------------------------------------------------------------------
322 -- cmTypeOfExpr: returns a string representing the type of an expression
325 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
326 cmTypeOfExpr cmstate dflags expr
327 = do (new_pcs, maybe_stuff)
328 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
330 let new_cmstate = cmstate{pcs = new_pcs}
333 Nothing -> return (new_cmstate, Nothing)
334 Just (_, ty, _) -> return (new_cmstate, Just str)
336 str = showSDocForUser unqual (ppr tidy_ty)
337 unqual = getUnqual pcs hit ic
338 tidy_ty = tidyType emptyTidyEnv ty
340 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
343 = case lookupIfaceByModName hit pit modname of
344 Nothing -> alwaysQualify
346 case mi_globals iface of
347 Just env -> unQualInScope env
348 Nothing -> unQualInScope (mkIfaceGlobalRdrEnv (mi_exports iface))
351 modname = moduleName (ic_module ic)
354 -----------------------------------------------------------------------------
355 -- cmTypeOfName: returns a string representing the type of a name.
358 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
359 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
360 = case lookupNameEnv (ic_type_env ic) name of
361 Nothing -> return Nothing
362 Just (AnId id) -> return (Just str)
364 unqual = getUnqual pcs hit ic
365 ty = tidyType emptyTidyEnv (idType id)
366 str = showSDocForUser unqual (ppr ty)
368 _ -> panic "cmTypeOfName"
371 -----------------------------------------------------------------------------
372 -- cmCompileExpr: compile an expression and deliver an HValue
375 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
376 cmCompileExpr cmstate dflags expr
378 let InteractiveContext {
380 ic_type_env = type_env,
381 ic_module = this_mod } = icontext
383 (new_pcs, maybe_stuff)
384 <- hscStmt dflags hst hit pcs icontext
385 ("let __cmCompileExpr = "++expr) False{-stmt-}
388 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
389 Just (ids, _, bcos) -> do
392 hval <- linkExpr pls bcos
395 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
396 hvals <- thing_to_run
399 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
400 _ -> panic "cmCompileExpr"
403 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
406 -----------------------------------------------------------------------------
407 -- Unload the compilation manager's state: everything it knows about the
408 -- current collection of modules in the Home package.
410 cmUnload :: CmState -> DynFlags -> IO CmState
411 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
412 = do -- Throw away the old home dir cache
415 -- Unload everything the linker knows about
416 new_pls <- CmLink.unload mode dflags [] pls
418 -- Start with a fresh CmState, but keep the PersistentCompilerState
419 new_state <- cmInit mode
420 return new_state{ pcs=pcs, pls=new_pls }
423 -----------------------------------------------------------------------------
424 -- Trace dependency graph
426 -- This is a seperate pass so that the caller can back off and keep
427 -- the current state if the downsweep fails.
429 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
430 cmDepAnal cmstate dflags rootnames
431 = do showPass dflags "Chasing dependencies"
432 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
433 hPutStrLn stderr (showSDoc (hcat [
434 text progName, text ": chasing modules from: ",
435 hcat (punctuate comma (map text rootnames))]))
436 downsweep rootnames (mg cmstate)
438 -----------------------------------------------------------------------------
439 -- The real business of the compilation manager: given a system state and
440 -- a module name, try and bring the module up to date, probably changing
441 -- the system state at the same time.
443 cmLoadModules :: CmState
446 -> IO (CmState, -- new state
447 Bool, -- was successful
448 [String]) -- list of modules loaded
450 cmLoadModules cmstate1 dflags mg2unsorted
451 = do -- version 1's are the original, before downsweep
452 let pls1 = pls cmstate1
453 let pcs1 = pcs cmstate1
454 let hst1 = hst cmstate1
455 let hit1 = hit cmstate1
456 -- similarly, ui1 is the (complete) set of linkables from
457 -- the previous pass, if any.
458 let ui1 = ui cmstate1
460 let ghci_mode = gmode cmstate1 -- this never changes
462 -- Do the downsweep to reestablish the module graph
463 let verb = verbosity dflags
465 -- Find out if we have a Main module
467 = any ((=="Main").moduleNameUserString.name_of_summary)
470 let mg2unsorted_names = map name_of_summary mg2unsorted
472 -- reachable_from follows source as well as normal imports
473 let reachable_from :: ModuleName -> [ModuleName]
474 reachable_from = downwards_closure_of_module mg2unsorted
476 -- should be cycle free; ignores 'import source's
477 let mg2 = topological_sort False mg2unsorted
478 -- ... whereas this takes them into account. Used for
479 -- backing out partially complete cycles following a failed
480 -- upsweep, and for removing from hst/hit all the modules
481 -- not in strict downwards closure, during calls to compile.
482 let mg2_with_srcimps = topological_sort True mg2unsorted
484 -- Sort out which linkables we wish to keep in the unlinked image.
485 -- See getValidLinkables below for details.
486 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
488 -- when (verb >= 2) $
489 -- putStrLn (showSDoc (text "Valid linkables:"
490 -- <+> ppr valid_linkables))
492 -- Figure out a stable set of modules which can be retained
493 -- the top level envs, to avoid upsweeping them. Goes to a
494 -- bit of trouble to avoid upsweeping module cycles.
496 -- Construct a set S of stable modules like this:
497 -- Travel upwards, over the sccified graph. For each scc
498 -- of modules ms, add ms to S only if:
499 -- 1. All home imports of ms are either in ms or S
500 -- 2. A valid linkable exists for each module in ms
502 stable_mods <- preUpsweep valid_linkables hit1
503 mg2unsorted_names [] mg2_with_srcimps
506 = concatMap (findInSummaries mg2unsorted) stable_mods
509 = filter (\m -> linkableModName m `elem` stable_mods)
513 putStrLn (showSDoc (text "Stable modules:"
514 <+> sep (map (text.moduleNameUserString) stable_mods)))
516 -- unload any modules which aren't going to be re-linked this
518 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
520 -- We could at this point detect cycles which aren't broken by
521 -- a source-import, and complain immediately, but it seems better
522 -- to let upsweep_mods do this, so at least some useful work gets
523 -- done before the upsweep is abandoned.
525 = filter (\scc -> any (`notElem` stable_mods)
526 (map name_of_summary (flattenSCC scc)))
529 --hPutStrLn stderr "after tsort:\n"
530 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
532 -- Because we don't take into account source imports when doing
533 -- the topological sort, there shouldn't be any cycles in mg2.
534 -- If there is, we complain and give up -- the user needs to
535 -- break the cycle using a boot file.
537 -- Now do the upsweep, calling compile for each module in
538 -- turn. Final result is version 3 of everything.
540 let threaded2 = CmThreaded pcs1 hst1 hit1
542 -- clean up between compilations
543 let cleanup = cleanTempFilesExcept verb
544 (ppFilesFromSummaries (flattenSCCs upsweep_these))
546 (upsweep_complete_success, threaded3, modsUpswept, newLis)
547 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
548 threaded2 cleanup upsweep_these
550 let ui3 = add_to_ui valid_linkables newLis
551 let (CmThreaded pcs3 hst3 hit3) = threaded3
553 -- At this point, modsUpswept and newLis should have the same
554 -- length, so there is one new (or old) linkable for each
555 -- mod which was processed (passed to compile).
557 -- Make modsDone be the summaries for each home module now
558 -- available; this should equal the domains of hst3 and hit3.
559 -- (NOT STRICTLY TRUE if an interactive session was started
560 -- with some object on disk ???)
561 -- Get in in a roughly top .. bottom order (hence reverse).
563 let modsDone = reverse modsUpswept ++ stable_summaries
565 -- Try and do linking in some form, depending on whether the
566 -- upsweep was completely or only partially successful.
568 if upsweep_complete_success
571 -- Easy; just relink it all.
572 do when (verb >= 2) $
573 hPutStrLn stderr "Upsweep completely successful."
575 -- clean up after ourselves
576 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
578 -- issue a warning for the confusing case where the user said '-o foo'
579 -- but we're not going to do any linking.
580 ofile <- readIORef v_Output_file
581 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
583 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
585 -- link everything together
586 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
588 cmLoadFinish True linkresult
589 hst3 hit3 ui3 modsDone ghci_mode pcs3
592 -- Tricky. We need to back out the effects of compiling any
593 -- half-done cycles, both so as to clean up the top level envs
594 -- and to avoid telling the interactive linker to link them.
595 do when (verb >= 2) $
596 hPutStrLn stderr "Upsweep partially successful."
599 = map name_of_summary modsDone
600 let mods_to_zap_names
601 = findPartiallyCompletedCycles modsDone_names
604 = filter ((`notElem` mods_to_zap_names).name_of_summary)
607 let (hst4, hit4, ui4)
608 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
611 -- clean up after ourselves
612 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
614 -- link everything together
615 linkresult <- link ghci_mode dflags False ui4 pls2
617 cmLoadFinish False linkresult
618 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
621 -- Finish up after a cmLoad.
623 -- If the link failed, unload everything and return.
624 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
625 dflags <- getDynFlags
626 new_pls <- CmLink.unload ghci_mode dflags [] pls
627 new_state <- cmInit ghci_mode
628 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
630 -- Empty the interactive context and set the module context to the topmost
631 -- newly loaded module, or the Prelude if none were loaded.
632 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
633 = do def_mod <- readIORef defaultCurrentModule
634 let current_mod = case mods of
638 new_ic = emptyInteractiveContext current_mod
640 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
641 gmode=ghci_mode, pcs=pcs, pls=pls,
643 mods_loaded = map (moduleNameUserString.name_of_summary) mods
645 return (new_cmstate, ok, mods_loaded)
647 -- used to fish out the preprocess output files for the purposes
649 ppFilesFromSummaries summaries
650 = [ fn | Just fn <- map toPpFile summaries ]
653 | hspp /= ml_hs_file loc = hspp
654 | otherwise = Nothing
656 loc = ms_location sum
657 hspp = ml_hspp_file loc
660 -----------------------------------------------------------------------------
663 -- For each module (or SCC of modules), we take:
665 -- - an on-disk linkable, if this is the first time around and one
668 -- - the old linkable, otherwise (and if one is available).
670 -- and we throw away the linkable if it is older than the source
671 -- file. We ignore the on-disk linkables unless all of the dependents
672 -- of this SCC also have on-disk linkables.
674 -- If a module has a valid linkable, then it may be STABLE (see below),
675 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
678 -- ToDo: this pass could be merged with the preUpsweep.
681 :: [Linkable] -- old linkables
682 -> [ModuleName] -- all home modules
683 -> [SCC ModSummary] -- all modules in the program, dependency order
684 -> IO [Linkable] -- still-valid linkables
686 getValidLinkables old_linkables all_home_mods module_graph
687 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
689 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
691 scc = flattenSCC scc0
692 scc_names = map name_of_summary scc
693 home_module m = m `elem` all_home_mods && m `notElem` scc_names
694 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
695 -- NOTE: ms_imps, not ms_allimps above. We don't want to
696 -- force a module's SOURCE imports to be already compiled for
697 -- its object linkable to be valid.
699 has_object m = case findModuleLinkable_maybe new_linkables m of
701 Just l -> isObjectLinkable l
703 objects_allowed = all has_object scc_allhomeimps
707 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
709 -- since an scc can contain only all objects or no objects at all,
710 -- we have to check whether we got all objects or not, and re-do
711 -- the linkable check if not.
713 <- if objects_allowed && not (all isObjectLinkable these_linkables)
714 then foldM (getValidLinkable old_linkables False) [] scc
715 else return these_linkables
717 return (adjusted_linkables ++ new_linkables)
720 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
722 getValidLinkable old_linkables objects_allowed new_linkables summary
723 = do let mod_name = name_of_summary summary
726 <- if (not objects_allowed)
728 else case ml_obj_file (ms_location summary) of
729 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
730 Nothing -> return Nothing
732 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
735 Just l | not (isObjectLinkable l) || stillThere l
737 -- ToDo: emit a warning if not (stillThere l)
740 -- make sure that if we had an old disk linkable around, that it's
741 -- still there on the disk (in case we need to re-link it).
743 case maybe_disk_linkable of
745 Just l_disk -> linkableTime l == linkableTime l_disk
747 -- we only look for objects on disk the first time around;
748 -- if the user compiles a module on the side during a GHCi session,
749 -- it won't be picked up until the next ":load". This is what the
750 -- "null old_linkables" test below is.
751 linkable | null old_linkables = maybeToList maybe_disk_linkable
752 | otherwise = maybeToList maybe_old_linkable
754 -- only linkables newer than the source code are valid
755 src_date = ms_hs_date summary
758 = filter (\l -> linkableTime l >= src_date) linkable
759 -- why '>=' rather than '>' above? If the filesystem stores
760 -- times to the nearset second, we may occasionally find that
761 -- the object & source have the same modification time,
762 -- especially if the source was automatically generated
763 -- and compiled. Using >= is slightly unsafe, but it matches
766 return (valid_linkable ++ new_linkables)
769 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
770 maybe_getFileLinkable mod_name obj_fn
771 = do obj_exist <- doesFileExist obj_fn
775 do let stub_fn = case splitFilename3 obj_fn of
776 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
777 stub_exist <- doesFileExist stub_fn
778 obj_time <- getModificationTime obj_fn
780 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
781 else return (Just (LM obj_time mod_name [DotO obj_fn]))
784 -----------------------------------------------------------------------------
785 -- Do a pre-upsweep without use of "compile", to establish a
786 -- (downward-closed) set of stable modules for which we won't call compile.
789 -- * has a valid linkable (see getValidLinkables above)
790 -- * depends only on stable modules
791 -- * has an interface in the HIT (interactive mode only)
793 preUpsweep :: [Linkable] -- new valid linkables
795 -> [ModuleName] -- names of all mods encountered in downsweep
796 -> [ModuleName] -- accumulating stable modules
797 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
798 -> IO [ModuleName] -- stable modules
800 preUpsweep valid_lis hit all_home_mods stable [] = return stable
801 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
802 = do let scc = flattenSCC scc0
803 scc_allhomeimps :: [ModuleName]
805 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
806 all_imports_in_scc_or_stable
807 = all in_stable_or_scc scc_allhomeimps
809 = map name_of_summary scc
811 = m `elem` scc_names || m `elem` stable
813 -- now we check for valid linkables: each module in the SCC must
814 -- have a valid linkable (see getValidLinkables above).
815 has_valid_linkable new_summary
816 = isJust (findModuleLinkable_maybe valid_lis modname)
817 where modname = name_of_summary new_summary
819 has_interface summary = ms_mod summary `elemUFM` hit
821 scc_is_stable = all_imports_in_scc_or_stable
822 && all has_valid_linkable scc
823 && all has_interface scc
826 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
827 else preUpsweep valid_lis hit all_home_mods stable sccs
830 -- Helper for preUpsweep. Assuming that new_summary's imports are all
831 -- stable (in the sense of preUpsweep), determine if new_summary is itself
832 -- stable, and, if so, in batch mode, return its linkable.
833 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
834 findInSummaries old_summaries mod_name
835 = [s | s <- old_summaries, name_of_summary s == mod_name]
837 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
838 findModInSummaries old_summaries mod
839 = case [s | s <- old_summaries, ms_mod s == mod] of
843 -- Return (names of) all those in modsDone who are part of a cycle
844 -- as defined by theGraph.
845 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
846 findPartiallyCompletedCycles modsDone theGraph
850 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
851 chew ((CyclicSCC vs):rest)
852 = let names_in_this_cycle = nub (map name_of_summary vs)
854 = nub ([done | done <- modsDone,
855 done `elem` names_in_this_cycle])
856 chewed_rest = chew rest
858 if not (null mods_in_this_cycle)
859 && length mods_in_this_cycle < length names_in_this_cycle
860 then mods_in_this_cycle ++ chewed_rest
864 -- Add the given (LM-form) Linkables to the UI, overwriting previous
865 -- versions if they exist.
866 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
868 = filter (not_in lis) ui ++ lis
870 not_in :: [Linkable] -> Linkable -> Bool
872 = all (\l -> linkableModName l /= mod) lis
873 where mod = linkableModName li
876 data CmThreaded -- stuff threaded through individual module compilations
877 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
880 -- Compile multiple modules, stopping as soon as an error appears.
881 -- There better had not be any cyclic groups here -- we check for them.
882 upsweep_mods :: GhciMode
884 -> UnlinkedImage -- valid linkables
885 -> (ModuleName -> [ModuleName]) -- to construct downward closures
886 -> CmThreaded -- PCS & HST & HIT
887 -> IO () -- how to clean up unwanted tmp files
888 -> [SCC ModSummary] -- mods to do (the worklist)
889 -- ...... RETURNING ......
890 -> IO (Bool{-complete success?-},
892 [ModSummary], -- mods which succeeded
893 [Linkable]) -- new linkables
895 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
897 = return (True, threaded, [], [])
899 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
901 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
902 unwords (map (moduleNameUserString.name_of_summary) ms))
903 return (False, threaded, [], [])
905 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
906 ((AcyclicSCC mod):mods)
907 = do --case threaded of
908 -- CmThreaded pcsz hstz hitz
909 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
911 (threaded1, maybe_linkable)
912 <- upsweep_mod ghci_mode dflags oldUI threaded mod
913 (reachable_from (name_of_summary mod))
915 -- remove unwanted tmp files between compilations
918 case maybe_linkable of
920 -> -- No errors; do the rest
921 do (restOK, threaded2, modOKs, linkables)
922 <- upsweep_mods ghci_mode dflags oldUI reachable_from
923 threaded1 cleanup mods
924 return (restOK, threaded2, mod:modOKs, linkable:linkables)
925 Nothing -- we got a compilation error; give up now
926 -> return (False, threaded1, [], [])
929 -- Compile a single module. Always produce a Linkable for it if
930 -- successful. If no compilation happened, return the old Linkable.
931 upsweep_mod :: GhciMode
937 -> IO (CmThreaded, Maybe Linkable)
939 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
941 let mod_name = name_of_summary summary1
943 let (CmThreaded pcs1 hst1 hit1) = threaded1
944 let old_iface = lookupUFM hit1 mod_name
946 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
948 source_unchanged = isJust maybe_old_linkable
950 reachable_only = filter (/= (name_of_summary summary1))
953 -- in interactive mode, all home modules below us *must* have an
954 -- interface in the HIT. We never demand-load home interfaces in
956 (hst1_strictDC, hit1_strictDC, [])
957 = ASSERT(ghci_mode == Batch ||
958 all (`elemUFM` hit1) reachable_only)
959 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
962 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
965 | Just l <- maybe_old_linkable, isObjectLinkable l = True
968 compresult <- compile ghci_mode summary1 source_unchanged
969 have_object old_iface hst1_strictDC hit1_strictDC pcs1
973 -- Compilation "succeeded", and may or may not have returned a new
974 -- linkable (depending on whether compilation was actually performed
976 CompOK pcs2 new_details new_iface maybe_new_linkable
977 -> do let hst2 = addToUFM hst1 mod_name new_details
978 hit2 = addToUFM hit1 mod_name new_iface
979 threaded2 = CmThreaded pcs2 hst2 hit2
981 return (threaded2, if isJust maybe_new_linkable
982 then maybe_new_linkable
983 else Just old_linkable)
985 -- Compilation failed. compile may still have updated
988 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
989 return (threaded2, Nothing)
991 -- Filter modules in the top level envs (HST, HIT, UI).
992 retainInTopLevelEnvs :: [ModuleName]
993 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
994 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
995 retainInTopLevelEnvs keep_these (hst, hit, ui)
996 = (retainInUFM hst keep_these,
997 retainInUFM hit keep_these,
998 filterModuleLinkables (`elem` keep_these) ui
1001 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1002 retainInUFM ufm keys_to_keep
1003 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1004 maybeLookupUFM ufm u
1005 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1007 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1008 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1009 downwards_closure_of_module summaries root
1010 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1011 toEdge summ = (name_of_summary summ,
1012 filter (`elem` all_mods) (ms_allimps summ))
1014 all_mods = map name_of_summary summaries
1016 res = simple_transitive_closure (map toEdge summaries) [root]
1018 -- trace (showSDoc (text "DC of mod" <+> ppr root
1019 -- <+> text "=" <+> ppr res)) $
1022 -- Calculate transitive closures from a set of roots given an adjacency list
1023 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1024 simple_transitive_closure graph set
1025 = let set2 = nub (concatMap dsts set ++ set)
1026 dsts node = fromMaybe [] (lookup node graph)
1028 if length set == length set2
1030 else simple_transitive_closure graph set2
1033 -- Calculate SCCs of the module graph, with or without taking into
1034 -- account source imports.
1035 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1036 topological_sort include_source_imports summaries
1038 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1040 = (summ, name_of_summary summ,
1041 (if include_source_imports
1042 then ms_srcimps summ else []) ++ ms_imps summ)
1044 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1045 mash_edge (summ, m, m_imports)
1046 = case lookup m key_map of
1047 Nothing -> panic "reverse_topological_sort"
1048 Just mk -> (summ, mk,
1049 -- ignore imports not from the home package
1050 catMaybes (map (flip lookup key_map) m_imports))
1052 edges = map toEdge summaries
1053 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1054 scc_input = map mash_edge edges
1055 sccs = stronglyConnComp scc_input
1060 -----------------------------------------------------------------------------
1061 -- Downsweep (dependency analysis)
1063 -- Chase downwards from the specified root set, returning summaries
1064 -- for all home modules encountered. Only follow source-import
1067 -- We pass in the previous collection of summaries, which is used as a
1068 -- cache to avoid recalculating a module summary if the source is
1071 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1072 downsweep roots old_summaries
1073 = do rootSummaries <- mapM getRootSummary roots
1075 <- loop (concat (map ms_imps rootSummaries))
1076 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1077 let mod = ms_mod s, isHomeModule mod
1079 return all_summaries
1081 getRootSummary :: FilePath -> IO ModSummary
1083 | haskellish_src_file file
1084 = do exists <- doesFileExist file
1085 if exists then summariseFile file else do
1086 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1088 = do exists <- doesFileExist hs_file
1089 if exists then summariseFile hs_file else do
1090 exists <- doesFileExist lhs_file
1091 if exists then summariseFile lhs_file else do
1092 let mod_name = mkModuleName file
1093 maybe_summary <- getSummary mod_name
1094 case maybe_summary of
1095 Nothing -> packageModErr mod_name
1098 hs_file = file ++ ".hs"
1099 lhs_file = file ++ ".lhs"
1101 getSummary :: ModuleName -> IO (Maybe ModSummary)
1103 = do found <- findModule nm
1105 Just (mod, location) -> do
1106 let old_summary = findModInSummaries old_summaries mod
1107 summarise mod location old_summary
1109 Nothing -> throwDyn (CmdLineError
1110 ("can't find module `"
1111 ++ showSDoc (ppr nm) ++ "'"))
1113 -- loop invariant: env doesn't contain package modules
1114 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1115 loop [] env = return (moduleEnvElts env)
1117 = do -- imports for modules we don't already have
1118 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1121 needed_summaries <- mapM getSummary needed_imps
1123 -- get just the "home" modules
1124 let new_home_summaries = [ s | Just s <- needed_summaries ]
1126 -- loop, checking the new imports
1127 let new_imps = concat (map ms_imps new_home_summaries)
1128 loop new_imps (extendModuleEnvList env
1129 [ (ms_mod s, s) | s <- new_home_summaries ])
1131 -----------------------------------------------------------------------------
1132 -- Summarising modules
1134 -- We have two types of summarisation:
1136 -- * Summarise a file. This is used for the root module(s) passed to
1137 -- cmLoadModules. The file is read, and used to determine the root
1138 -- module name. The module name may differ from the filename.
1140 -- * Summarise a module. We are given a module name, and must provide
1141 -- a summary. The finder is used to locate the file in which the module
1144 summariseFile :: FilePath -> IO ModSummary
1146 = do hspp_fn <- preprocess file
1147 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1149 let (path, basename, _ext) = splitFilename3 file
1152 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1155 <- case ml_hs_file location of
1156 Nothing -> noHsFileErr mod_name
1157 Just src_fn -> getModificationTime src_fn
1159 return (ModSummary mod
1160 location{ml_hspp_file=Just hspp_fn}
1161 srcimps imps src_timestamp)
1163 -- Summarise a module, and pick up source and timestamp.
1164 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1165 -> IO (Maybe ModSummary)
1166 summarise mod location old_summary
1167 | not (isHomeModule mod) = return Nothing
1169 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1171 case ml_hs_file location of {
1172 Nothing -> noHsFileErr mod;
1175 src_timestamp <- getModificationTime src_fn
1177 -- return the cached summary if the source didn't change
1178 case old_summary of {
1179 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1182 hspp_fn <- preprocess hs_fn
1183 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1185 when (mod_name /= moduleName mod) $
1186 throwDyn (ProgramError
1187 (showSDoc (text hs_fn
1188 <> text ": file name does not match module name"
1189 <+> quotes (ppr (moduleName mod)))))
1191 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1192 srcimps imps src_timestamp))
1198 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1201 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1202 quotes (ppr mod) <+>
1203 text "is a package module")))