2 % (c) The University of Glasgow, 2000
4 \section[CompManager]{The Compilation Manager}
7 {-# OPTIONS -fvia-C #-}
9 cmInit, -- :: GhciMode -> IO CmState
11 cmLoadModule, -- :: CmState -> FilePath -> IO (CmState, [String])
13 cmUnload, -- :: CmState -> DynFlags -> IO CmState
15 cmSetContext, -- :: CmState -> String -> IO CmState
17 cmGetContext, -- :: CmState -> IO String
20 cmInfoThing, -- :: CmState -> DynFlags -> String -> IO (Maybe TyThing)
23 cmRunStmt, -- :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
25 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
26 -- -> IO (CmState, Maybe String)
28 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
30 cmCompileExpr,-- :: CmState -> DynFlags -> String
31 -- -> IO (CmState, Maybe HValue)#endif
33 CmState, emptyCmState -- abstract
37 #include "HsVersions.h"
42 import DriverFlags ( getDynFlags )
43 import DriverState ( v_Output_file )
48 import HscMain ( initPersistentCompilerState, hscThing )
50 import HscMain ( initPersistentCompilerState )
53 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
55 import RdrName ( lookupRdrEnv, emptyRdrEnv )
59 import Unique ( Uniquable )
60 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
61 import ErrUtils ( showPass )
62 import SysTools ( cleanTempFilesExcept )
66 import CmdLineOpts ( DynFlags(..) )
71 import Id ( idType, idName )
73 import Type ( tidyType )
74 import VarEnv ( emptyTidyEnv )
75 import RnEnv ( unQualInScope )
76 import BasicTypes ( Fixity, defaultFixity )
77 import Interpreter ( HValue )
78 import HscMain ( hscStmt )
79 import PrelGHC ( unsafeCoerce# )
83 import Exception ( Exception, try )
87 import Exception ( throwDyn )
90 import Directory ( getModificationTime, doesFileExist )
99 -- Persistent state for the entire system
102 hst :: HomeSymbolTable, -- home symbol table
103 hit :: HomeIfaceTable, -- home interface table
104 ui :: UnlinkedImage, -- the unlinked images
105 mg :: ModuleGraph, -- the module graph
106 gmode :: GhciMode, -- NEVER CHANGES
107 ic :: InteractiveContext, -- command-line binding info
109 pcs :: PersistentCompilerState, -- compile's persistent state
110 pls :: PersistentLinkerState -- link's persistent state
113 emptyCmState :: GhciMode -> Module -> IO CmState
114 emptyCmState gmode mod
115 = do pcs <- initPersistentCompilerState
117 return (CmState { hst = emptySymbolTable,
118 hit = emptyIfaceTable,
122 ic = emptyInteractiveContext mod,
126 emptyInteractiveContext mod
127 = InteractiveContext { ic_module = mod,
128 ic_rn_env = emptyRdrEnv,
129 ic_type_env = emptyTypeEnv }
131 defaultCurrentModuleName = mkModuleName "Prelude"
132 GLOBAL_VAR(defaultCurrentModule, error "no defaultCurrentModule", Module)
135 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
136 emptyUI :: UnlinkedImage
139 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
140 emptyMG :: ModuleGraph
143 -----------------------------------------------------------------------------
144 -- Produce an initial CmState.
146 cmInit :: GhciMode -> IO CmState
148 prel <- moduleNameToModule defaultCurrentModuleName
149 writeIORef defaultCurrentModule prel
150 emptyCmState mode prel
152 -----------------------------------------------------------------------------
153 -- Setting the context doesn't throw away any bindings; the bindings
154 -- we've built up in the InteractiveContext simply move to the new
155 -- module. They always shadow anything in scope in the current context.
157 cmSetContext :: CmState -> String -> IO CmState
158 cmSetContext cmstate str
159 = do let mn = mkModuleName str
160 modules_loaded = [ (name_of_summary s, ms_mod s) | s <- mg cmstate ]
162 m <- case lookup mn modules_loaded of
165 mod <- moduleNameToModule mn
167 then throwDyn (CmdLineError (showSDoc
168 (quotes (ppr (moduleName mod))
169 <+> text "is not currently loaded")))
172 return cmstate{ ic = (ic cmstate){ic_module=m} }
174 cmGetContext :: CmState -> IO String
175 cmGetContext cmstate = return (moduleUserString (ic_module (ic cmstate)))
177 moduleNameToModule :: ModuleName -> IO Module
178 moduleNameToModule mn
179 = do maybe_stuff <- findModule mn
181 Nothing -> throwDyn (CmdLineError ("can't find module `"
182 ++ moduleNameUserString mn ++ "'"))
183 Just (m,_) -> return m
185 -----------------------------------------------------------------------------
186 -- cmInfoThing: convert a String to a TyThing
188 -- A string may refer to more than one TyThing (eg. a constructor,
189 -- and type constructor), so we return a list of all the possible TyThings.
192 cmInfoThing :: CmState -> DynFlags -> String
193 -> IO (CmState, PrintUnqualified, [(TyThing,Fixity)])
194 cmInfoThing cmstate dflags id
195 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
196 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
197 return (cmstate{ pcs=new_pcs }, unqual, pairs)
199 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
200 unqual = getUnqual pcs hit icontext
202 getFixity :: PersistentCompilerState -> Name -> Fixity
204 | Just iface <- lookupModuleEnv iface_table (nameModule name),
205 Just fixity <- lookupNameEnv (mi_fixities iface) name
209 where iface_table | isHomePackageName name = hit
210 | otherwise = pcs_PIT pcs
213 -----------------------------------------------------------------------------
214 -- cmRunStmt: Run a statement/expr.
218 = CmRunOk [Name] -- names bound by this evaluation
220 | CmRunDeadlocked -- statement deadlocked
221 | CmRunException Exception -- statement raised an exception
223 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
224 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
227 let InteractiveContext {
229 ic_type_env = type_env,
230 ic_module = this_mod } = icontext
232 (new_pcs, maybe_stuff)
233 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
236 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
237 Just (ids, _, bcos) -> do
239 -- update the interactive context
241 names = map idName ids
243 -- these names have just been shadowed
244 shadowed = [ n | r <- map nameRdrName names,
245 Just n <- [lookupRdrEnv rn_env r] ]
247 new_rn_env = extendLocalRdrEnv rn_env names
249 -- remove any shadowed bindings from the type_env
250 filtered_type_env = delListFromNameEnv type_env shadowed
252 new_type_env = extendNameEnvList filtered_type_env
253 [ (getName id, AnId id) | id <- ids]
255 new_ic = icontext { ic_rn_env = new_rn_env,
256 ic_type_env = new_type_env }
259 hval <- linkExpr pls bcos
262 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
263 either_hvals <- sandboxIO thing_to_run
267 -> return ( cmstate{ pcs=new_pcs, ic=new_ic },
270 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
271 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
276 return ( cmstate{ pcs=new_pcs, ic=new_ic },
279 -- Get the newly bound things, and bind them.
280 -- Don't forget to delete any shadowed bindings from the
281 -- closure_env, lest we end up with a space leak.
282 pls <- delListFromClosureEnv pls shadowed
283 new_pls <- addListToClosureEnv pls (zip names hvals)
285 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
288 -- We run the statement in a "sandbox", which amounts to calling into
289 -- the RTS to request a new main thread. The main benefit is that we
290 -- get to detect a deadlock this way, but also there's no danger that
291 -- exceptions raised by the expression can affect the interpreter.
293 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
295 st_thing <- newStablePtr (Exception.try thing)
296 alloca $ \ p_st_result -> do
297 stat <- rts_evalStableIO st_thing p_st_result
298 freeStablePtr st_thing
300 then do st_result <- peek p_st_result
301 result <- deRefStablePtr st_result
302 freeStablePtr st_result
303 return (Right result)
305 return (Left (fromIntegral stat))
307 -- ToDo: slurp this in from ghc/includes/RtsAPI.h somehow
308 dEADLOCKED = 4 :: Int
310 foreign import "rts_evalStableIO" {- safe -}
311 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
312 -- more informative than the C type!
315 -----------------------------------------------------------------------------
316 -- cmTypeOfExpr: returns a string representing the type of an expression
319 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
320 cmTypeOfExpr cmstate dflags expr
321 = do (new_pcs, maybe_stuff)
322 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
324 let new_cmstate = cmstate{pcs = new_pcs}
327 Nothing -> return (new_cmstate, Nothing)
328 Just (_, ty, _) -> return (new_cmstate, Just str)
330 str = showSDocForUser unqual (ppr tidy_ty)
331 unqual = getUnqual pcs hit ic
332 tidy_ty = tidyType emptyTidyEnv ty
334 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
337 = case lookupIfaceByModName hit pit modname of
338 Nothing -> alwaysQualify
339 Just iface -> unQualInScope (mi_globals iface)
342 modname = moduleName (ic_module ic)
345 -----------------------------------------------------------------------------
346 -- cmTypeOfName: returns a string representing the type of a name.
349 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
350 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
351 = case lookupNameEnv (ic_type_env ic) name of
352 Nothing -> return Nothing
353 Just (AnId id) -> return (Just str)
355 unqual = getUnqual pcs hit ic
356 ty = tidyType emptyTidyEnv (idType id)
357 str = showSDocForUser unqual (ppr ty)
359 _ -> panic "cmTypeOfName"
362 -----------------------------------------------------------------------------
363 -- cmCompileExpr: compile an expression and deliver an HValue
366 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
367 cmCompileExpr cmstate dflags expr
369 let InteractiveContext {
371 ic_type_env = type_env,
372 ic_module = this_mod } = icontext
374 (new_pcs, maybe_stuff)
375 <- hscStmt dflags hst hit pcs icontext
376 ("let __cmCompileExpr = "++expr) False{-stmt-}
379 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
380 Just (ids, _, bcos) -> do
383 hval <- linkExpr pls bcos
386 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
387 hvals <- thing_to_run
390 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
391 _ -> panic "cmCompileExpr"
394 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
397 -----------------------------------------------------------------------------
398 -- Unload the compilation manager's state: everything it knows about the
399 -- current collection of modules in the Home package.
401 cmUnload :: CmState -> DynFlags -> IO CmState
402 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
403 = do -- Throw away the old home dir cache
406 -- Unload everything the linker knows about
407 new_pls <- CmLink.unload mode dflags [] pls
409 -- Start with a fresh CmState, but keep the PersistentCompilerState
410 new_state <- cmInit mode
411 return new_state{ pcs=pcs, pls=new_pls }
413 -----------------------------------------------------------------------------
414 -- The real business of the compilation manager: given a system state and
415 -- a module name, try and bring the module up to date, probably changing
416 -- the system state at the same time.
418 cmLoadModule :: CmState
420 -> IO (CmState, -- new state
421 Bool, -- was successful
422 [String]) -- list of modules loaded
424 cmLoadModule cmstate1 rootnames
425 = do -- version 1's are the original, before downsweep
426 let pls1 = pls cmstate1
427 let pcs1 = pcs cmstate1
428 let hst1 = hst cmstate1
429 let hit1 = hit cmstate1
430 -- similarly, ui1 is the (complete) set of linkables from
431 -- the previous pass, if any.
432 let ui1 = ui cmstate1
433 let mg1 = mg cmstate1
435 let ghci_mode = gmode cmstate1 -- this never changes
437 -- Do the downsweep to reestablish the module graph
438 dflags <- getDynFlags
439 let verb = verbosity dflags
441 showPass dflags "Chasing dependencies"
442 when (verb >= 1 && ghci_mode == Batch) $
443 hPutStrLn stderr (showSDoc (hcat [
444 text progName, text ": chasing modules from: ",
445 hcat (punctuate comma (map text rootnames))]))
447 (mg2unsorted, a_root_is_Main) <- downsweep rootnames mg1
448 let mg2unsorted_names = map name_of_summary mg2unsorted
450 -- reachable_from follows source as well as normal imports
451 let reachable_from :: ModuleName -> [ModuleName]
452 reachable_from = downwards_closure_of_module mg2unsorted
454 -- should be cycle free; ignores 'import source's
455 let mg2 = topological_sort False mg2unsorted
456 -- ... whereas this takes them into account. Used for
457 -- backing out partially complete cycles following a failed
458 -- upsweep, and for removing from hst/hit all the modules
459 -- not in strict downwards closure, during calls to compile.
460 let mg2_with_srcimps = topological_sort True mg2unsorted
462 -- Sort out which linkables we wish to keep in the unlinked image.
463 -- See getValidLinkables below for details.
464 valid_linkables <- getValidLinkables ui1 mg2unsorted_names
466 -- when (verb >= 2) $
467 -- putStrLn (showSDoc (text "Valid linkables:"
468 -- <+> ppr valid_linkables))
470 -- Figure out a stable set of modules which can be retained
471 -- the top level envs, to avoid upsweeping them. Goes to a
472 -- bit of trouble to avoid upsweeping module cycles.
474 -- Construct a set S of stable modules like this:
475 -- Travel upwards, over the sccified graph. For each scc
476 -- of modules ms, add ms to S only if:
477 -- 1. All home imports of ms are either in ms or S
478 -- 2. A valid linkable exists for each module in ms
480 stable_mods <- preUpsweep valid_linkables hit1
481 mg2unsorted_names [] mg2_with_srcimps
484 = concatMap (findInSummaries mg2unsorted) stable_mods
487 = filter (\m -> linkableModName m `elem` stable_mods)
491 putStrLn (showSDoc (text "Stable modules:"
492 <+> sep (map (text.moduleNameUserString) stable_mods)))
494 -- unload any modules which aren't going to be re-linked this
496 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
498 -- We could at this point detect cycles which aren't broken by
499 -- a source-import, and complain immediately, but it seems better
500 -- to let upsweep_mods do this, so at least some useful work gets
501 -- done before the upsweep is abandoned.
503 = filter (\scc -> any (`notElem` stable_mods)
504 (map name_of_summary (flattenSCC scc)))
507 --hPutStrLn stderr "after tsort:\n"
508 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
510 -- Because we don't take into account source imports when doing
511 -- the topological sort, there shouldn't be any cycles in mg2.
512 -- If there is, we complain and give up -- the user needs to
513 -- break the cycle using a boot file.
515 -- Now do the upsweep, calling compile for each module in
516 -- turn. Final result is version 3 of everything.
518 let threaded2 = CmThreaded pcs1 hst1 hit1
520 -- clean up between compilations
521 let cleanup = cleanTempFilesExcept verb
522 (ppFilesFromSummaries (flattenSCCs upsweep_these))
524 (upsweep_complete_success, threaded3, modsUpswept, newLis)
525 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
526 threaded2 cleanup upsweep_these
528 let ui3 = add_to_ui valid_linkables newLis
529 let (CmThreaded pcs3 hst3 hit3) = threaded3
531 -- At this point, modsUpswept and newLis should have the same
532 -- length, so there is one new (or old) linkable for each
533 -- mod which was processed (passed to compile).
535 -- Make modsDone be the summaries for each home module now
536 -- available; this should equal the domains of hst3 and hit3.
537 -- (NOT STRICTLY TRUE if an interactive session was started
538 -- with some object on disk ???)
539 -- Get in in a roughly top .. bottom order (hence reverse).
541 let modsDone = reverse modsUpswept ++ stable_summaries
543 -- Try and do linking in some form, depending on whether the
544 -- upsweep was completely or only partially successful.
546 if upsweep_complete_success
549 -- Easy; just relink it all.
550 do when (verb >= 2) $
551 hPutStrLn stderr "Upsweep completely successful."
553 -- clean up after ourselves
554 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
556 -- issue a warning for the confusing case where the user said '-o foo'
557 -- but we're not going to do any linking.
558 ofile <- readIORef v_Output_file
559 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
561 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
563 -- link everything together
564 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
566 cmLoadFinish True linkresult
567 hst3 hit3 ui3 modsDone ghci_mode pcs3
570 -- Tricky. We need to back out the effects of compiling any
571 -- half-done cycles, both so as to clean up the top level envs
572 -- and to avoid telling the interactive linker to link them.
573 do when (verb >= 2) $
574 hPutStrLn stderr "Upsweep partially successful."
577 = map name_of_summary modsDone
578 let mods_to_zap_names
579 = findPartiallyCompletedCycles modsDone_names
582 = filter ((`notElem` mods_to_zap_names).name_of_summary)
585 let (hst4, hit4, ui4)
586 = retainInTopLevelEnvs (map name_of_summary mods_to_keep)
589 -- clean up after ourselves
590 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
592 -- link everything together
593 linkresult <- link ghci_mode dflags False ui4 pls2
595 cmLoadFinish False linkresult
596 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
599 -- Finish up after a cmLoad.
601 -- If the link failed, unload everything and return.
602 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
603 dflags <- getDynFlags
604 new_pls <- CmLink.unload ghci_mode dflags [] pls
605 new_state <- cmInit ghci_mode
606 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
608 -- Empty the interactive context and set the module context to the topmost
609 -- newly loaded module, or the Prelude if none were loaded.
610 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
611 = do def_mod <- readIORef defaultCurrentModule
612 let current_mod = case mods of
616 new_ic = emptyInteractiveContext current_mod
618 new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
619 gmode=ghci_mode, pcs=pcs, pls=pls,
621 mods_loaded = map (moduleNameUserString.name_of_summary) mods
623 return (new_cmstate, ok, mods_loaded)
625 -- used to fish out the preprocess output files for the purposes
627 ppFilesFromSummaries summaries
628 = [ fn | Just fn <- map toPpFile summaries ]
631 | hspp /= ml_hs_file loc = hspp
632 | otherwise = Nothing
634 loc = ms_location sum
635 hspp = ml_hspp_file loc
638 -----------------------------------------------------------------------------
641 -- For each module (or SCC of modules), we take:
643 -- - an on-disk linkable, if this is the first time around and one
646 -- - the old linkable, otherwise (and if one is available).
648 -- and we throw away the linkable if it is older than the source
649 -- file. We ignore the on-disk linkables unless all of the dependents
650 -- of this SCC also have on-disk linkables.
652 -- If a module has a valid linkable, then it may be STABLE (see below),
653 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
656 -- ToDo: this pass could be merged with the preUpsweep.
659 :: [Linkable] -- old linkables
660 -> [ModuleName] -- all home modules
661 -> [SCC ModSummary] -- all modules in the program, dependency order
662 -> IO [Linkable] -- still-valid linkables
664 getValidLinkables old_linkables all_home_mods module_graph
665 = foldM (getValidLinkablesSCC old_linkables all_home_mods) [] module_graph
667 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
669 scc = flattenSCC scc0
670 scc_names = map name_of_summary scc
671 home_module m = m `elem` all_home_mods && m `notElem` scc_names
672 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
673 -- NOTE: ms_imps, not ms_allimps above. We don't want to
674 -- force a module's SOURCE imports to be already compiled for
675 -- its object linkable to be valid.
677 has_object m = case findModuleLinkable_maybe new_linkables m of
679 Just l -> isObjectLinkable l
681 objects_allowed = all has_object scc_allhomeimps
685 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
687 -- since an scc can contain only all objects or no objects at all,
688 -- we have to check whether we got all objects or not, and re-do
689 -- the linkable check if not.
691 <- if objects_allowed && not (all isObjectLinkable these_linkables)
692 then foldM (getValidLinkable old_linkables False) [] scc
693 else return these_linkables
695 return (adjusted_linkables ++ new_linkables)
698 getValidLinkable :: [Linkable] -> Bool -> [Linkable] -> ModSummary
700 getValidLinkable old_linkables objects_allowed new_linkables summary
701 = do let mod_name = name_of_summary summary
704 <- if (not objects_allowed)
706 else case ml_obj_file (ms_location summary) of
707 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
708 Nothing -> return Nothing
710 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
713 Just l | not (isObjectLinkable l) || stillThere l
715 -- ToDo: emit a warning if not (stillThere l)
718 -- make sure that if we had an old disk linkable around, that it's
719 -- still there on the disk (in case we need to re-link it).
721 case maybe_disk_linkable of
723 Just l_disk -> linkableTime l == linkableTime l_disk
725 -- we only look for objects on disk the first time around;
726 -- if the user compiles a module on the side during a GHCi session,
727 -- it won't be picked up until the next ":load". This is what the
728 -- "null old_linkables" test below is.
729 linkable | null old_linkables = maybeToList maybe_disk_linkable
730 | otherwise = maybeToList maybe_old_linkable
732 -- only linkables newer than the source code are valid
733 src_date = ms_hs_date summary
736 = filter (\l -> linkableTime l >= src_date) linkable
737 -- why '>=' rather than '>' above? If the filesystem stores
738 -- times to the nearset second, we may occasionally find that
739 -- the object & source have the same modification time,
740 -- especially if the source was automatically generated
741 -- and compiled. Using >= is slightly unsafe, but it matches
744 return (valid_linkable ++ new_linkables)
747 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
748 maybe_getFileLinkable mod_name obj_fn
749 = do obj_exist <- doesFileExist obj_fn
753 do let stub_fn = case splitFilename3 obj_fn of
754 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
755 stub_exist <- doesFileExist stub_fn
756 obj_time <- getModificationTime obj_fn
758 then return (Just (LM obj_time mod_name [DotO obj_fn, DotO stub_fn]))
759 else return (Just (LM obj_time mod_name [DotO obj_fn]))
762 -----------------------------------------------------------------------------
763 -- Do a pre-upsweep without use of "compile", to establish a
764 -- (downward-closed) set of stable modules for which we won't call compile.
767 -- * has a valid linkable (see getValidLinkables above)
768 -- * depends only on stable modules
769 -- * has an interface in the HIT (interactive mode only)
771 preUpsweep :: [Linkable] -- new valid linkables
773 -> [ModuleName] -- names of all mods encountered in downsweep
774 -> [ModuleName] -- accumulating stable modules
775 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
776 -> IO [ModuleName] -- stable modules
778 preUpsweep valid_lis hit all_home_mods stable [] = return stable
779 preUpsweep valid_lis hit all_home_mods stable (scc0:sccs)
780 = do let scc = flattenSCC scc0
781 scc_allhomeimps :: [ModuleName]
783 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
784 all_imports_in_scc_or_stable
785 = all in_stable_or_scc scc_allhomeimps
787 = map name_of_summary scc
789 = m `elem` scc_names || m `elem` stable
791 -- now we check for valid linkables: each module in the SCC must
792 -- have a valid linkable (see getValidLinkables above).
793 has_valid_linkable new_summary
794 = isJust (findModuleLinkable_maybe valid_lis modname)
795 where modname = name_of_summary new_summary
797 has_interface summary = ms_mod summary `elemUFM` hit
799 scc_is_stable = all_imports_in_scc_or_stable
800 && all has_valid_linkable scc
801 && all has_interface scc
804 then preUpsweep valid_lis hit all_home_mods (scc_names++stable) sccs
805 else preUpsweep valid_lis hit all_home_mods stable sccs
808 -- Helper for preUpsweep. Assuming that new_summary's imports are all
809 -- stable (in the sense of preUpsweep), determine if new_summary is itself
810 -- stable, and, if so, in batch mode, return its linkable.
811 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
812 findInSummaries old_summaries mod_name
813 = [s | s <- old_summaries, name_of_summary s == mod_name]
815 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
816 findModInSummaries old_summaries mod
817 = case [s | s <- old_summaries, ms_mod s == mod] of
821 -- Return (names of) all those in modsDone who are part of a cycle
822 -- as defined by theGraph.
823 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
824 findPartiallyCompletedCycles modsDone theGraph
828 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
829 chew ((CyclicSCC vs):rest)
830 = let names_in_this_cycle = nub (map name_of_summary vs)
832 = nub ([done | done <- modsDone,
833 done `elem` names_in_this_cycle])
834 chewed_rest = chew rest
836 if not (null mods_in_this_cycle)
837 && length mods_in_this_cycle < length names_in_this_cycle
838 then mods_in_this_cycle ++ chewed_rest
842 -- Add the given (LM-form) Linkables to the UI, overwriting previous
843 -- versions if they exist.
844 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
846 = filter (not_in lis) ui ++ lis
848 not_in :: [Linkable] -> Linkable -> Bool
850 = all (\l -> linkableModName l /= mod) lis
851 where mod = linkableModName li
854 data CmThreaded -- stuff threaded through individual module compilations
855 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
858 -- Compile multiple modules, stopping as soon as an error appears.
859 -- There better had not be any cyclic groups here -- we check for them.
860 upsweep_mods :: GhciMode
862 -> UnlinkedImage -- valid linkables
863 -> (ModuleName -> [ModuleName]) -- to construct downward closures
864 -> CmThreaded -- PCS & HST & HIT
865 -> IO () -- how to clean up unwanted tmp files
866 -> [SCC ModSummary] -- mods to do (the worklist)
867 -- ...... RETURNING ......
868 -> IO (Bool{-complete success?-},
870 [ModSummary], -- mods which succeeded
871 [Linkable]) -- new linkables
873 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
875 = return (True, threaded, [], [])
877 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
879 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
880 unwords (map (moduleNameUserString.name_of_summary) ms))
881 return (False, threaded, [], [])
883 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
884 ((AcyclicSCC mod):mods)
885 = do --case threaded of
886 -- CmThreaded pcsz hstz hitz
887 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
889 (threaded1, maybe_linkable)
890 <- upsweep_mod ghci_mode dflags oldUI threaded mod
891 (reachable_from (name_of_summary mod))
893 -- remove unwanted tmp files between compilations
896 case maybe_linkable of
898 -> -- No errors; do the rest
899 do (restOK, threaded2, modOKs, linkables)
900 <- upsweep_mods ghci_mode dflags oldUI reachable_from
901 threaded1 cleanup mods
902 return (restOK, threaded2, mod:modOKs, linkable:linkables)
903 Nothing -- we got a compilation error; give up now
904 -> return (False, threaded1, [], [])
907 -- Compile a single module. Always produce a Linkable for it if
908 -- successful. If no compilation happened, return the old Linkable.
909 upsweep_mod :: GhciMode
915 -> IO (CmThreaded, Maybe Linkable)
917 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
919 let mod_name = name_of_summary summary1
921 let (CmThreaded pcs1 hst1 hit1) = threaded1
922 let old_iface = lookupUFM hit1 mod_name
924 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
926 source_unchanged = isJust maybe_old_linkable
928 reachable_only = filter (/= (name_of_summary summary1))
931 -- in interactive mode, all home modules below us *must* have an
932 -- interface in the HIT. We never demand-load home interfaces in
934 (hst1_strictDC, hit1_strictDC, [])
935 = ASSERT(ghci_mode == Batch ||
936 all (`elemUFM` hit1) reachable_only)
937 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
940 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
943 | Just l <- maybe_old_linkable, isObjectLinkable l = True
946 compresult <- compile ghci_mode summary1 source_unchanged
947 have_object old_iface hst1_strictDC hit1_strictDC pcs1
951 -- Compilation "succeeded", and may or may not have returned a new
952 -- linkable (depending on whether compilation was actually performed
954 CompOK pcs2 new_details new_iface maybe_new_linkable
955 -> do let hst2 = addToUFM hst1 mod_name new_details
956 hit2 = addToUFM hit1 mod_name new_iface
957 threaded2 = CmThreaded pcs2 hst2 hit2
959 return (threaded2, if isJust maybe_new_linkable
960 then maybe_new_linkable
961 else Just old_linkable)
963 -- Compilation failed. compile may still have updated
966 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
967 return (threaded2, Nothing)
969 -- Filter modules in the top level envs (HST, HIT, UI).
970 retainInTopLevelEnvs :: [ModuleName]
971 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
972 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
973 retainInTopLevelEnvs keep_these (hst, hit, ui)
974 = (retainInUFM hst keep_these,
975 retainInUFM hit keep_these,
976 filterModuleLinkables (`elem` keep_these) ui
979 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
980 retainInUFM ufm keys_to_keep
981 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
983 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
985 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
986 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
987 downwards_closure_of_module summaries root
988 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
989 toEdge summ = (name_of_summary summ,
990 filter (`elem` all_mods) (ms_allimps summ))
992 all_mods = map name_of_summary summaries
994 res = simple_transitive_closure (map toEdge summaries) [root]
996 -- trace (showSDoc (text "DC of mod" <+> ppr root
997 -- <+> text "=" <+> ppr res)) $
1000 -- Calculate transitive closures from a set of roots given an adjacency list
1001 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1002 simple_transitive_closure graph set
1003 = let set2 = nub (concatMap dsts set ++ set)
1004 dsts node = fromMaybe [] (lookup node graph)
1006 if length set == length set2
1008 else simple_transitive_closure graph set2
1011 -- Calculate SCCs of the module graph, with or without taking into
1012 -- account source imports.
1013 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1014 topological_sort include_source_imports summaries
1016 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1018 = (summ, name_of_summary summ,
1019 (if include_source_imports
1020 then ms_srcimps summ else []) ++ ms_imps summ)
1022 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1023 mash_edge (summ, m, m_imports)
1024 = case lookup m key_map of
1025 Nothing -> panic "reverse_topological_sort"
1026 Just mk -> (summ, mk,
1027 -- ignore imports not from the home package
1028 catMaybes (map (flip lookup key_map) m_imports))
1030 edges = map toEdge summaries
1031 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1032 scc_input = map mash_edge edges
1033 sccs = stronglyConnComp scc_input
1038 -- Chase downwards from the specified root set, returning summaries
1039 -- for all home modules encountered. Only follow source-import
1040 -- links. Also returns a Bool to indicate whether any of the roots
1042 downsweep :: [FilePath] -> [ModSummary] -> IO ([ModSummary], Bool)
1043 downsweep rootNm old_summaries
1044 = do rootSummaries <- mapM getRootSummary rootNm
1046 = any ((=="Main").moduleNameUserString.name_of_summary)
1049 <- loop (concat (map ms_imps rootSummaries))
1050 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1051 let mod = ms_mod s, isHomeModule mod
1053 return (all_summaries, a_root_is_Main)
1055 getRootSummary :: FilePath -> IO ModSummary
1057 | haskellish_src_file file
1058 = do exists <- doesFileExist file
1059 if exists then summariseFile file else do
1060 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1062 = do exists <- doesFileExist hs_file
1063 if exists then summariseFile hs_file else do
1064 exists <- doesFileExist lhs_file
1065 if exists then summariseFile lhs_file else do
1066 let mod_name = mkModuleName file
1067 maybe_summary <- getSummary mod_name
1068 case maybe_summary of
1069 Nothing -> packageModErr mod_name
1072 hs_file = file ++ ".hs"
1073 lhs_file = file ++ ".lhs"
1075 getSummary :: ModuleName -> IO (Maybe ModSummary)
1077 = do found <- findModule nm
1079 Just (mod, location) -> do
1080 let old_summary = findModInSummaries old_summaries mod
1081 summarise mod location old_summary
1083 Nothing -> throwDyn (CmdLineError
1084 ("can't find module `"
1085 ++ showSDoc (ppr nm) ++ "'"))
1087 -- loop invariant: env doesn't contain package modules
1088 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1089 loop [] env = return (moduleEnvElts env)
1091 = do -- imports for modules we don't already have
1092 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1095 needed_summaries <- mapM getSummary needed_imps
1097 -- get just the "home" modules
1098 let new_home_summaries = [ s | Just s <- needed_summaries ]
1100 -- loop, checking the new imports
1101 let new_imps = concat (map ms_imps new_home_summaries)
1102 loop new_imps (extendModuleEnvList env
1103 [ (ms_mod s, s) | s <- new_home_summaries ])
1105 -----------------------------------------------------------------------------
1106 -- Summarising modules
1108 -- We have two types of summarisation:
1110 -- * Summarise a file. This is used for the root module passed to
1111 -- cmLoadModule. The file is read, and used to determine the root
1112 -- module name. The module name may differ from the filename.
1114 -- * Summarise a module. We are given a module name, and must provide
1115 -- a summary. The finder is used to locate the file in which the module
1118 summariseFile :: FilePath -> IO ModSummary
1120 = do hspp_fn <- preprocess file
1121 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1123 let (path, basename, _ext) = splitFilename3 file
1126 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1129 <- case ml_hs_file location of
1130 Nothing -> noHsFileErr mod_name
1131 Just src_fn -> getModificationTime src_fn
1133 return (ModSummary mod
1134 location{ml_hspp_file=Just hspp_fn}
1135 srcimps imps src_timestamp)
1137 -- Summarise a module, and pick up source and timestamp.
1138 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1139 -> IO (Maybe ModSummary)
1140 summarise mod location old_summary
1141 | not (isHomeModule mod) = return Nothing
1143 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1145 case ml_hs_file location of {
1146 Nothing -> noHsFileErr mod;
1149 src_timestamp <- getModificationTime src_fn
1151 -- return the cached summary if the source didn't change
1152 case old_summary of {
1153 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1156 hspp_fn <- preprocess hs_fn
1157 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1159 when (mod_name /= moduleName mod) $
1160 throwDyn (ProgramError
1161 (showSDoc (text hs_fn
1162 <> text ": file name does not match module name"
1163 <+> quotes (ppr (moduleName mod)))))
1165 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1166 srcimps imps src_timestamp))
1172 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1175 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1176 quotes (ppr mod) <+>
1177 text "is a package module")))