2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
7 {-# OPTIONS -fvia-C #-}
9 ModuleGraph, ModSummary(..),
11 CmState, emptyCmState, -- abstract
13 cmInit, -- :: GhciMode -> IO CmState
15 cmDepAnal, -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
17 cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
18 -- -> IO (CmState, Bool, [String])
20 cmUnload, -- :: CmState -> DynFlags -> IO CmState
23 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
25 cmSetContext, -- :: CmState -> DynFlags -> [String] -> [String] -> IO CmState
26 cmGetContext, -- :: CmState -> IO ([String],[String])
28 cmInfoThing, -- :: CmState -> DynFlags -> String
29 -- -> IO (CmState, [(TyThing,Fixity)])
31 cmBrowseModule, -- :: CmState -> IO [TyThing]
34 cmRunStmt, -- :: CmState -> DynFlags -> String
35 -- -> IO (CmState, CmRunResult)
37 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
38 -- -> IO (CmState, Maybe String)
40 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
43 cmCompileExpr, -- :: CmState -> DynFlags -> String
44 -- -> IO (CmState, Maybe HValue)
46 cmGetModInfo, -- :: CmState -> (ModuleGraph, HomePackageTable)
47 findModuleLinkable_maybe, -- Exported to InteractiveUI
49 cmGetBindings, -- :: CmState -> [TyThing]
50 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
52 sandboxIO -- Should be somewhere else
57 #include "HsVersions.h"
59 import DriverPipeline ( CompResult(..), preprocess, compile, link )
60 import DriverState ( v_Output_file )
64 import HscMain ( initPersistentCompilerState )
65 import HscTypes hiding ( moduleNameToModule )
67 import PrelNames ( gHC_PRIM_Name )
68 import Module ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
69 ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
70 extendModuleEnvList, extendModuleEnv,
75 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
76 import ErrUtils ( showPass )
77 import SysTools ( cleanTempFilesExcept )
78 import BasicTypes ( SuccessFlag(..), succeeded, failed )
82 import CmdLineOpts ( DynFlags(..), getDynFlags )
83 import Maybes ( expectJust, orElse )
85 import DATA_IOREF ( readIORef )
88 import HscMain ( hscThing, hscStmt, hscTcExpr )
89 import Module ( moduleUserString )
90 import TcRnDriver ( mkGlobalContext, getModuleContents )
91 import Name ( Name, NamedThing(..), isExternalName )
93 import Type ( tidyType )
94 import VarEnv ( emptyTidyEnv )
95 import BasicTypes ( Fixity, FixitySig(..), defaultFixity )
96 import Linker ( HValue, unload, extendLinkEnv )
97 import GHC.Exts ( unsafeCoerce# )
99 import Control.Exception as Exception ( Exception, try )
102 import EXCEPTION ( throwDyn )
105 import Directory ( getModificationTime, doesFileExist )
110 import Time ( ClockTime )
115 -- Persistent state for the entire system
118 gmode :: GhciMode, -- NEVER CHANGES
120 hpt :: HomePackageTable, -- Info about home package module
121 mg :: ModuleGraph, -- the module graph
122 ic :: InteractiveContext, -- command-line binding info
124 pcs :: PersistentCompilerState -- compile's persistent state
127 cmGetModInfo cmstate = (mg cmstate, hpt cmstate)
128 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
129 cmGetPrintUnqual cmstate = icPrintUnqual (ic cmstate)
131 emptyCmState :: GhciMode -> IO CmState
133 = do pcs <- initPersistentCompilerState
134 return (CmState { hpt = emptyHomePackageTable,
137 ic = emptyInteractiveContext,
140 cmInit :: GhciMode -> IO CmState
141 cmInit mode = emptyCmState mode
144 -------------------------------------------------------------------
145 -- The unlinked image
147 -- The compilation manager keeps a list of compiled, but as-yet unlinked
148 -- binaries (byte code or object code). Even when it links bytecode
149 -- it keeps the unlinked version so it can re-link it later without
152 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
153 emptyUI :: UnlinkedImage
156 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
157 findModuleLinkable_maybe lis mod
158 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
161 many -> pprPanic "findModuleLinkable" (ppr mod)
163 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
164 filterModuleLinkables p [] = []
165 filterModuleLinkables p (li:lis)
167 LM _ modnm _ -> if p modnm then retain else dump
169 dump = filterModuleLinkables p lis
172 linkableInSet :: Linkable -> [Linkable] -> Bool
173 linkableInSet l objs_loaded =
174 case findModuleLinkable_maybe objs_loaded (linkableModName l) of
176 Just m -> linkableTime l == linkableTime m
180 %************************************************************************
184 %************************************************************************
188 -----------------------------------------------------------------------------
189 -- Setting the context doesn't throw away any bindings; the bindings
190 -- we've built up in the InteractiveContext simply move to the new
191 -- module. They always shadow anything in scope in the current context.
194 :: CmState -> DynFlags
195 -> [String] -- take the top-level scopes of these modules
196 -> [String] -- and the just the exports from these
198 cmSetContext cmstate dflags toplevs exports = do
199 let CmState{ hpt=hpt, pcs=pcs, ic=old_ic } = cmstate
200 hsc_env = HscEnv { hsc_mode = Interactive, hsc_dflags = dflags,
203 toplev_mods <- mapM (getTopLevModule hpt) (map mkModuleName toplevs)
204 export_mods <- mapM (moduleNameToModule hpt) (map mkModuleName exports)
207 <- mkGlobalContext hsc_env pcs toplev_mods export_mods
210 Nothing -> return cmstate
211 Just env -> return cmstate{ pcs = new_pcs,
212 ic = old_ic{ ic_toplev_scope = toplev_mods,
213 ic_exports = export_mods,
214 ic_rn_gbl_env = env } }
216 getTopLevModule hpt mn =
217 case lookupModuleEnvByName hpt mn of
220 | isJust (mi_globals iface) -> return (mi_module iface)
222 iface = hm_iface mod_info
224 _other -> throwDyn (CmdLineError (
225 "cannot enter the top-level scope of a compiled module (module `" ++
226 moduleNameUserString mn ++ "')"))
228 moduleNameToModule :: HomePackageTable -> ModuleName -> IO Module
229 moduleNameToModule hpt mn = do
230 case lookupModuleEnvByName hpt mn of
231 Just mod_info -> return (mi_module (hm_iface mod_info))
232 _not_a_home_module -> do
233 maybe_stuff <- findModule mn
235 Nothing -> throwDyn (CmdLineError ("can't find module `"
236 ++ moduleNameUserString mn ++ "'"))
237 Just (m,_) -> return m
239 cmGetContext :: CmState -> IO ([String],[String])
240 cmGetContext CmState{ic=ic} =
241 return (map moduleUserString (ic_toplev_scope ic),
242 map moduleUserString (ic_exports ic))
244 cmModuleIsInterpreted :: CmState -> String -> IO Bool
245 cmModuleIsInterpreted cmstate str
246 = case lookupModuleEnvByName (hpt cmstate) (mkModuleName str) of
247 Just details -> return (isJust (mi_globals (hm_iface details)))
248 _not_a_home_module -> return False
250 -----------------------------------------------------------------------------
251 -- cmInfoThing: convert a String to a TyThing
253 -- A string may refer to more than one TyThing (eg. a constructor,
254 -- and type constructor), so we return a list of all the possible TyThings.
256 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
257 cmInfoThing cmstate dflags id
258 = do (new_pcs, things) <- hscThing hsc_env pcs icontext id
259 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
260 return (cmstate{ pcs=new_pcs }, pairs)
262 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
263 hsc_env = HscEnv { hsc_mode = Interactive,
266 pit = eps_PIT (pcs_EPS pcs)
267 getFixity :: PersistentCompilerState -> Name -> Fixity
269 | isExternalName name,
270 Just iface <- lookupIface hpt pit name,
271 Just (FixitySig _ fixity _) <- lookupNameEnv (mi_fixities iface) name
276 -- ---------------------------------------------------------------------------
277 -- cmBrowseModule: get all the TyThings defined in a module
279 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
280 -> IO (CmState, [TyThing])
281 cmBrowseModule cmstate dflags str exports_only = do
282 let mn = mkModuleName str
283 mod <- moduleNameToModule hpt mn
284 (pcs1, maybe_ty_things)
285 <- getModuleContents hsc_env pcs mod exports_only
286 case maybe_ty_things of
287 Nothing -> return (cmstate{pcs=pcs1}, [])
288 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
290 hsc_env = HscEnv { hsc_mode = Interactive, hsc_dflags = dflags,
292 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
294 -----------------------------------------------------------------------------
295 -- cmRunStmt: Run a statement/expr.
298 = CmRunOk [Name] -- names bound by this evaluation
300 | CmRunException Exception -- statement raised an exception
302 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
303 cmRunStmt cmstate@CmState{ hpt=hpt, pcs=pcs, ic=icontext }
306 let hsc_env = HscEnv { hsc_mode = Interactive,
310 (new_pcs, maybe_stuff)
311 <- hscStmt hsc_env pcs icontext expr
314 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
315 Just (new_ic, names, hval) -> do
317 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
318 either_hvals <- sandboxIO thing_to_run
322 -- on error, keep the *old* interactive context,
323 -- so that 'it' is not bound to something
324 -- that doesn't exist.
325 return ( cmstate{ pcs=new_pcs }, CmRunException e )
328 -- Get the newly bound things, and bind them.
329 -- Don't need to delete any shadowed bindings;
330 -- the new ones override the old ones.
331 extendLinkEnv (zip names hvals)
333 return (cmstate{ pcs=new_pcs, ic=new_ic },
337 -- We run the statement in a "sandbox" to protect the rest of the
338 -- system from anything the expression might do. For now, this
339 -- consists of just wrapping it in an exception handler, but see below
340 -- for another version.
342 sandboxIO :: IO a -> IO (Either Exception a)
343 sandboxIO thing = Exception.try thing
346 -- This version of sandboxIO runs the expression in a completely new
347 -- RTS main thread. It is disabled for now because ^C exceptions
348 -- won't be delivered to the new thread, instead they'll be delivered
349 -- to the (blocked) GHCi main thread.
351 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
353 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
355 st_thing <- newStablePtr (Exception.try thing)
356 alloca $ \ p_st_result -> do
357 stat <- rts_evalStableIO st_thing p_st_result
358 freeStablePtr st_thing
360 then do st_result <- peek p_st_result
361 result <- deRefStablePtr st_result
362 freeStablePtr st_result
363 return (Right result)
365 return (Left (fromIntegral stat))
367 foreign import "rts_evalStableIO" {- safe -}
368 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
369 -- more informative than the C type!
372 -----------------------------------------------------------------------------
373 -- cmTypeOfExpr: returns a string representing the type of an expression
375 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
376 cmTypeOfExpr cmstate dflags expr
377 = do (new_pcs, maybe_stuff) <- hscTcExpr hsc_env pcs ic expr
379 let new_cmstate = cmstate{pcs = new_pcs}
382 Nothing -> return (new_cmstate, Nothing)
383 Just ty -> return (new_cmstate, Just str)
385 str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
386 unqual = icPrintUnqual ic
387 tidy_ty = tidyType emptyTidyEnv ty
389 CmState{ hpt=hpt, pcs=pcs, ic=ic } = cmstate
390 hsc_env = HscEnv { hsc_mode = Interactive,
396 -----------------------------------------------------------------------------
397 -- cmTypeOfName: returns a string representing the type of a name.
399 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
400 cmTypeOfName CmState{ pcs=pcs, ic=ic } name
402 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
403 case lookupNameEnv (ic_type_env ic) name of
404 Nothing -> return Nothing
405 Just (AnId id) -> return (Just str)
407 unqual = icPrintUnqual ic
408 ty = tidyType emptyTidyEnv (idType id)
409 str = showSDocForUser unqual (ppr ty)
411 _ -> panic "cmTypeOfName"
413 -----------------------------------------------------------------------------
414 -- cmCompileExpr: compile an expression and deliver an HValue
416 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
417 cmCompileExpr cmstate dflags expr
419 let hsc_env = HscEnv { hsc_mode = Interactive,
423 (new_pcs, maybe_stuff)
424 <- hscStmt hsc_env pcs icontext
425 ("let __cmCompileExpr = "++expr)
428 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
429 Just (new_ic, names, hval) -> do
432 hvals <- (unsafeCoerce# hval) :: IO [HValue]
434 case (names,hvals) of
435 ([n],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
436 _ -> panic "cmCompileExpr"
439 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
444 %************************************************************************
446 Loading and unloading
448 %************************************************************************
451 -----------------------------------------------------------------------------
452 -- Unload the compilation manager's state: everything it knows about the
453 -- current collection of modules in the Home package.
455 cmUnload :: CmState -> DynFlags -> IO CmState
456 cmUnload state@CmState{ gmode=mode, pcs=pcs } dflags
457 = do -- Throw away the old home dir cache
460 -- Unload everything the linker knows about
461 cm_unload mode dflags []
463 -- Start with a fresh CmState, but keep the PersistentCompilerState
464 new_state <- cmInit mode
465 return new_state{ pcs=pcs }
467 cm_unload Batch dflags linkables = return ()
470 cm_unload Interactive dflags linkables = Linker.unload dflags linkables
472 cm_unload Interactive dflags linkables = panic "unload: no interpreter"
476 -----------------------------------------------------------------------------
477 -- Trace dependency graph
479 -- This is a seperate pass so that the caller can back off and keep
480 -- the current state if the downsweep fails. Typically the caller
481 -- might go cmDepAnal
484 -- He wants to do the dependency analysis before the unload, so that
485 -- if the former fails he can use the later
487 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
488 cmDepAnal cmstate dflags rootnames
489 = do showPass dflags "Chasing dependencies"
490 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
491 hPutStrLn stderr (showSDoc (hcat [
492 text progName, text ": chasing modules from: ",
493 hcat (punctuate comma (map text rootnames))]))
494 downsweep rootnames (mg cmstate)
496 -----------------------------------------------------------------------------
497 -- The real business of the compilation manager: given a system state and
498 -- a module name, try and bring the module up to date, probably changing
499 -- the system state at the same time.
501 cmLoadModules :: CmState -- The HPT may not be as up to date
502 -> DynFlags -- as the ModuleGraph
503 -> ModuleGraph -- Bang up to date
504 -> IO (CmState, -- new state
505 SuccessFlag, -- was successful
506 [String]) -- list of modules loaded
508 cmLoadModules cmstate1 dflags mg2unsorted
509 = do -- version 1's are the original, before downsweep
510 let pcs1 = pcs cmstate1
511 let hpt1 = hpt cmstate1
513 let ghci_mode = gmode cmstate1 -- this never changes
515 -- Do the downsweep to reestablish the module graph
516 let verb = verbosity dflags
518 -- Find out if we have a Main module
520 = any ((=="Main").moduleNameUserString.modSummaryName)
523 let mg2unsorted_names = map modSummaryName mg2unsorted
525 -- reachable_from follows source as well as normal imports
526 let reachable_from :: ModuleName -> [ModuleName]
527 reachable_from = downwards_closure_of_module mg2unsorted
529 -- should be cycle free; ignores 'import source's
530 let mg2 = topological_sort False mg2unsorted
531 -- ... whereas this takes them into account. Used for
532 -- backing out partially complete cycles following a failed
533 -- upsweep, and for removing from hpt all the modules
534 -- not in strict downwards closure, during calls to compile.
535 let mg2_with_srcimps = topological_sort True mg2unsorted
537 -- Sort out which linkables we wish to keep in the unlinked image.
538 -- See getValidLinkables below for details.
539 (valid_old_linkables, new_linkables)
540 <- getValidLinkables ghci_mode (hptLinkables hpt1)
541 mg2unsorted_names mg2_with_srcimps
543 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
545 -- Uniq of ModuleName is the same as Module, fortunately...
546 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
548 -- When (verb >= 2) $
549 -- putStrLn (showSDoc (text "Valid linkables:"
550 -- <+> ppr valid_linkables))
552 -- Figure out a stable set of modules which can be retained
553 -- the top level envs, to avoid upsweeping them. Goes to a
554 -- bit of trouble to avoid upsweeping module cycles.
556 -- Construct a set S of stable modules like this:
557 -- Travel upwards, over the sccified graph. For each scc
558 -- of modules ms, add ms to S only if:
559 -- 1. All home imports of ms are either in ms or S
560 -- 2. A valid old linkable exists for each module in ms
562 stable_mods <- preUpsweep valid_old_linkables
563 mg2unsorted_names [] mg2_with_srcimps
566 = concatMap (findInSummaries mg2unsorted) stable_mods
569 = filter (\m -> linkableModName m `elem` stable_mods)
573 putStrLn (showSDoc (text "Stable modules:"
574 <+> sep (map (text.moduleNameUserString) stable_mods)))
576 -- Unload any modules which are going to be re-linked this
578 cm_unload ghci_mode dflags stable_linkables
580 -- we can now glom together our linkable sets
581 let valid_linkables = valid_old_linkables ++ new_linkables
583 -- We could at this point detect cycles which aren't broken by
584 -- a source-import, and complain immediately, but it seems better
585 -- to let upsweep_mods do this, so at least some useful work gets
586 -- done before the upsweep is abandoned.
588 = filter (\scc -> any (`notElem` stable_mods)
589 (map modSummaryName (flattenSCC scc)))
592 --hPutStrLn stderr "after tsort:\n"
593 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
595 -- Because we don't take into account source imports when doing
596 -- the topological sort, there shouldn't be any cycles in mg2.
597 -- If there is, we complain and give up -- the user needs to
598 -- break the cycle using a boot file.
600 -- Now do the upsweep, calling compile for each module in
601 -- turn. Final result is version 3 of everything.
603 let threaded2 = CmThreaded pcs1 hpt2
605 -- clean up between compilations
606 let cleanup = cleanTempFilesExcept verb
607 (ppFilesFromSummaries (flattenSCCs mg2))
609 (upsweep_ok, threaded3, modsUpswept)
610 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
611 threaded2 cleanup upsweep_these
613 let (CmThreaded pcs3 hpt3) = threaded3
615 -- At this point, modsUpswept and newLis should have the same
616 -- length, so there is one new (or old) linkable for each
617 -- mod which was processed (passed to compile).
619 -- Make modsDone be the summaries for each home module now
620 -- available; this should equal the domain of hpt3.
621 -- (NOT STRICTLY TRUE if an interactive session was started
622 -- with some object on disk ???)
623 -- Get in in a roughly top .. bottom order (hence reverse).
625 let modsDone = reverse modsUpswept ++ stable_summaries
627 -- Try and do linking in some form, depending on whether the
628 -- upsweep was completely or only partially successful.
630 if succeeded upsweep_ok
633 -- Easy; just relink it all.
634 do when (verb >= 2) $
635 hPutStrLn stderr "Upsweep completely successful."
637 -- clean up after ourselves
638 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
640 -- issue a warning for the confusing case where the user said '-o foo'
641 -- but we're not going to do any linking.
642 ofile <- readIORef v_Output_file
643 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
645 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
647 -- link everything together
648 linkresult <- link ghci_mode dflags a_root_is_Main (hptLinkables hpt3)
650 cmLoadFinish Succeeded linkresult
651 hpt3 modsDone ghci_mode pcs3
654 -- Tricky. We need to back out the effects of compiling any
655 -- half-done cycles, both so as to clean up the top level envs
656 -- and to avoid telling the interactive linker to link them.
657 do when (verb >= 2) $
658 hPutStrLn stderr "Upsweep partially successful."
661 = map modSummaryName modsDone
662 let mods_to_zap_names
663 = findPartiallyCompletedCycles modsDone_names
666 = filter ((`notElem` mods_to_zap_names).modSummaryName)
669 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep) hpt3
671 -- Clean up after ourselves
672 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
674 -- Link everything together
675 linkresult <- link ghci_mode dflags False (hptLinkables hpt4)
677 cmLoadFinish Failed linkresult
678 hpt4 mods_to_keep ghci_mode pcs3
681 -- Finish up after a cmLoad.
683 -- If the link failed, unload everything and return.
684 cmLoadFinish ok Failed hpt mods ghci_mode pcs = do
685 dflags <- getDynFlags
686 cm_unload ghci_mode dflags []
687 new_state <- cmInit ghci_mode
688 return (new_state{ pcs=pcs }, Failed, [])
690 -- Empty the interactive context and set the module context to the topmost
691 -- newly loaded module, or the Prelude if none were loaded.
692 cmLoadFinish ok Succeeded hpt mods ghci_mode pcs
693 = do let new_cmstate = CmState{ hpt=hpt, mg=mods,
694 gmode=ghci_mode, pcs=pcs,
695 ic = emptyInteractiveContext }
696 mods_loaded = map (moduleNameUserString.modSummaryName) mods
698 return (new_cmstate, ok, mods_loaded)
700 -- used to fish out the preprocess output files for the purposes
702 ppFilesFromSummaries summaries
703 = [ fn | Just fn <- map toPpFile summaries ]
706 | hspp /= ml_hs_file loc = hspp
707 | otherwise = Nothing
709 loc = ms_location sum
710 hspp = ml_hspp_file loc
713 -----------------------------------------------------------------------------
716 -- For each module (or SCC of modules), we take:
718 -- - an on-disk linkable, if this is the first time around and one
721 -- - the old linkable, otherwise (and if one is available).
723 -- and we throw away the linkable if it is older than the source file.
724 -- In interactive mode, we also ignore the on-disk linkables unless
725 -- all of the dependents of this SCC also have on-disk linkables (we
726 -- can't have dynamically loaded objects that depend on interpreted
729 -- If a module has a valid linkable, then it may be STABLE (see below),
730 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
733 -- ToDo: this pass could be merged with the preUpsweep.
737 -> [Linkable] -- old linkables
738 -> [ModuleName] -- all home modules
739 -> [SCC ModSummary] -- all modules in the program, dependency order
740 -> IO ( [Linkable], -- still-valid linkables
741 [Linkable] -- new linkables we just found
744 getValidLinkables mode old_linkables all_home_mods module_graph = do
745 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
747 return (partition_it ls [] [])
749 partition_it [] valid new = (valid,new)
750 partition_it ((l,b):ls) valid new
751 | b = partition_it ls valid (l:new)
752 | otherwise = partition_it ls (l:valid) new
755 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
757 scc = flattenSCC scc0
758 scc_names = map modSummaryName scc
759 home_module m = m `elem` all_home_mods && m `notElem` scc_names
760 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
761 -- NB. ms_imps, not ms_allimps above. We don't want to
762 -- force a module's SOURCE imports to be already compiled for
763 -- its object linkable to be valid.
766 case findModuleLinkable_maybe (map fst new_linkables) m of
768 Just l -> isObjectLinkable l
770 objects_allowed = mode == Batch || all has_object scc_allhomeimps
774 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
776 -- since an scc can contain only all objects or no objects at all,
777 -- we have to check whether we got all objects or not, and re-do
778 -- the linkable check if not.
781 && not (all isObjectLinkable (map fst new_linkables'))
782 then foldM (getValidLinkable old_linkables False) [] scc
783 else return new_linkables'
785 return (new_linkables ++ new_linkables')
788 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
789 -> IO [(Linkable,Bool)]
790 -- True <=> linkable is new; i.e. freshly discovered on the disk
791 -- presumably generated 'on the side'
792 -- by a separate GHC run
793 getValidLinkable old_linkables objects_allowed new_linkables summary
794 -- 'objects_allowed' says whether we permit this module to
795 -- have a .o-file linkable. We only permit it if all the
796 -- modules it depends on also have .o files; a .o file can't
797 -- link to a bytecode module
798 = do let mod_name = modSummaryName summary
801 <- if (not objects_allowed)
804 else case ml_obj_file (ms_location summary) of
805 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
806 Nothing -> return Nothing
808 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
811 case (old_linkable, maybe_disk_linkable) of
812 (Nothing, Nothing) -> []
814 -- new object linkable just appeared
815 (Nothing, Just l) -> up_to_date l True
818 | isObjectLinkable l -> []
819 -- object linkable disappeared! In case we need to
820 -- relink the module, disregard the old linkable and
821 -- just interpret the module from now on.
822 | otherwise -> up_to_date l False
823 -- old byte code linkable
826 | not (isObjectLinkable l) -> up_to_date l False
827 -- if the previous linkable was interpreted, then we
828 -- ignore a newly compiled version, because the version
829 -- numbers in the interface file will be out-of-sync with
830 -- our internal ones.
831 | linkableTime l' > linkableTime l -> up_to_date l' True
832 | linkableTime l' == linkableTime l -> up_to_date l False
834 -- on-disk linkable has been replaced by an older one!
835 -- again, disregard the previous one.
838 | linkableTime l < ms_hs_date summary = []
839 | otherwise = [(l,b)]
840 -- why '<' rather than '<=' above? If the filesystem stores
841 -- times to the nearset second, we may occasionally find that
842 -- the object & source have the same modification time,
843 -- especially if the source was automatically generated
844 -- and compiled. Using >= is slightly unsafe, but it matches
847 return (new_linkables' ++ new_linkables)
850 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
851 maybe_getFileLinkable mod obj_fn
852 = do obj_exist <- doesFileExist obj_fn
856 do let stub_fn = case splitFilename3 obj_fn of
857 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
858 stub_exist <- doesFileExist stub_fn
859 obj_time <- getModificationTime obj_fn
861 then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
862 else return (Just (LM obj_time mod [DotO obj_fn]))
864 hptLinkables :: HomePackageTable -> [Linkable]
865 -- Get all the linkables from the home package table, one for each module
866 -- Once the HPT is up to date, these are the ones we should link
867 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
870 -----------------------------------------------------------------------------
871 -- Do a pre-upsweep without use of "compile", to establish a
872 -- (downward-closed) set of stable modules for which we won't call compile.
875 -- * has a valid linkable (see getValidLinkables above)
876 -- * depends only on stable modules
877 -- * has an interface in the HPT (interactive mode only)
879 preUpsweep :: [Linkable] -- new valid linkables
880 -> [ModuleName] -- names of all mods encountered in downsweep
881 -> [ModuleName] -- accumulating stable modules
882 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
883 -> IO [ModuleName] -- stable modules
885 preUpsweep valid_lis all_home_mods stable [] = return stable
886 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
887 = do let scc = flattenSCC scc0
888 scc_allhomeimps :: [ModuleName]
890 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
891 all_imports_in_scc_or_stable
892 = all in_stable_or_scc scc_allhomeimps
894 = map modSummaryName scc
896 = m `elem` scc_names || m `elem` stable
898 -- now we check for valid linkables: each module in the SCC must
899 -- have a valid linkable (see getValidLinkables above).
900 has_valid_linkable new_summary
901 = isJust (findModuleLinkable_maybe valid_lis modname)
902 where modname = modSummaryName new_summary
904 scc_is_stable = all_imports_in_scc_or_stable
905 && all has_valid_linkable scc
908 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
909 else preUpsweep valid_lis all_home_mods stable sccs
912 -- Helper for preUpsweep. Assuming that new_summary's imports are all
913 -- stable (in the sense of preUpsweep), determine if new_summary is itself
914 -- stable, and, if so, in batch mode, return its linkable.
915 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
916 findInSummaries old_summaries mod_name
917 = [s | s <- old_summaries, modSummaryName s == mod_name]
919 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
920 findModInSummaries old_summaries mod
921 = case [s | s <- old_summaries, ms_mod s == mod] of
925 -- Return (names of) all those in modsDone who are part of a cycle
926 -- as defined by theGraph.
927 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
928 findPartiallyCompletedCycles modsDone theGraph
932 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
933 chew ((CyclicSCC vs):rest)
934 = let names_in_this_cycle = nub (map modSummaryName vs)
936 = nub ([done | done <- modsDone,
937 done `elem` names_in_this_cycle])
938 chewed_rest = chew rest
940 if notNull mods_in_this_cycle
941 && length mods_in_this_cycle < length names_in_this_cycle
942 then mods_in_this_cycle ++ chewed_rest
946 data CmThreaded -- stuff threaded through individual module compilations
947 = CmThreaded PersistentCompilerState HomePackageTable
950 -- Compile multiple modules, stopping as soon as an error appears.
951 -- There better had not be any cyclic groups here -- we check for them.
952 upsweep_mods :: GhciMode
954 -> [Linkable] -- Valid linkables
955 -> (ModuleName -> [ModuleName]) -- to construct downward closures
956 -> CmThreaded -- PCS & HPT
957 -> IO () -- how to clean up unwanted tmp files
958 -> [SCC ModSummary] -- mods to do (the worklist)
959 -- ...... RETURNING ......
961 CmThreaded, -- Includes linkables
962 [ModSummary]) -- Mods which succeeded
964 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
966 = return (Succeeded, threaded, [])
968 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
970 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
971 unwords (map (moduleNameUserString.modSummaryName) ms))
972 return (Failed, threaded, [])
974 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
975 ((AcyclicSCC mod):mods)
976 = do --case threaded of
977 -- CmThreaded pcsz hptz
978 -- -> putStrLn ("UPSWEEP_MOD: hpt = " ++
979 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM hptz)))
981 (ok_flag, threaded1) <- upsweep_mod ghci_mode dflags oldUI threaded mod
982 (reachable_from (modSummaryName mod))
984 cleanup -- Remove unwanted tmp files between compilations
986 if failed ok_flag then
987 return (Failed, threaded1, [])
989 (restOK, threaded2, modOKs)
990 <- upsweep_mods ghci_mode dflags oldUI reachable_from
991 threaded1 cleanup mods
992 return (restOK, threaded2, mod:modOKs)
995 -- Compile a single module. Always produce a Linkable for it if
996 -- successful. If no compilation happened, return the old Linkable.
997 upsweep_mod :: GhciMode
1003 -> IO (SuccessFlag, CmThreaded)
1005 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1007 let this_mod = ms_mod summary1
1008 location = ms_location summary1
1009 mod_name = moduleName this_mod
1011 let (CmThreaded pcs1 hpt1) = threaded1
1012 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
1013 Just mod_info -> Just (hm_iface mod_info)
1016 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1017 source_unchanged = isJust maybe_old_linkable
1019 reachable_only = filter (/= mod_name) reachable_inc_me
1021 -- In interactive mode, all home modules below us *must* have an
1022 -- interface in the HPT. We never demand-load home interfaces in
1023 -- interactive mode.
1025 = ASSERT(ghci_mode == Batch || all (`elemUFM` hpt1) reachable_only)
1026 retainInTopLevelEnvs reachable_only hpt1
1028 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1031 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1034 compresult <- compile ghci_mode this_mod location source_unchanged
1035 have_object mb_old_iface hpt1_strictDC pcs1
1039 -- Compilation "succeeded", and may or may not have returned a new
1040 -- linkable (depending on whether compilation was actually performed
1042 CompOK pcs2 new_details new_iface maybe_new_linkable
1044 new_linkable = maybe_new_linkable `orElse` old_linkable
1045 new_info = HomeModInfo { hm_iface = new_iface,
1046 hm_details = new_details,
1047 hm_linkable = new_linkable }
1048 hpt2 = extendModuleEnv hpt1 this_mod new_info
1050 return (Succeeded, CmThreaded pcs2 hpt2)
1052 -- Compilation failed. Compile may still have updated the PCS, tho.
1053 CompErrs pcs2 -> return (Failed, CmThreaded pcs2 hpt1)
1055 -- Filter modules in the HPT
1056 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1057 retainInTopLevelEnvs keep_these hpt
1058 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
1060 maybeLookupUFM ufm u = case lookupUFM ufm u of
1062 Just val -> [(u, val)]
1064 -- Needed to clean up HPT so that we don't get duplicates in inst env
1065 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1066 downwards_closure_of_module summaries root
1067 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1068 toEdge summ = (modSummaryName summ,
1069 filter (`elem` all_mods) (ms_allimps summ))
1071 all_mods = map modSummaryName summaries
1073 res = simple_transitive_closure (map toEdge summaries) [root]
1075 -- trace (showSDoc (text "DC of mod" <+> ppr root
1076 -- <+> text "=" <+> ppr res)) $
1079 -- Calculate transitive closures from a set of roots given an adjacency list
1080 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1081 simple_transitive_closure graph set
1082 = let set2 = nub (concatMap dsts set ++ set)
1083 dsts node = fromMaybe [] (lookup node graph)
1085 if length set == length set2
1087 else simple_transitive_closure graph set2
1090 -- Calculate SCCs of the module graph, with or without taking into
1091 -- account source imports.
1092 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1093 topological_sort include_source_imports summaries
1095 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1097 = (summ, modSummaryName summ,
1098 (if include_source_imports
1099 then ms_srcimps summ else []) ++ ms_imps summ)
1101 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1102 mash_edge (summ, m, m_imports)
1103 = case lookup m key_map of
1104 Nothing -> panic "reverse_topological_sort"
1105 Just mk -> (summ, mk,
1106 -- ignore imports not from the home package
1107 catMaybes (map (flip lookup key_map) m_imports))
1109 edges = map toEdge summaries
1110 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1111 scc_input = map mash_edge edges
1112 sccs = stronglyConnComp scc_input
1117 -----------------------------------------------------------------------------
1118 -- Downsweep (dependency analysis)
1120 -- Chase downwards from the specified root set, returning summaries
1121 -- for all home modules encountered. Only follow source-import
1124 -- We pass in the previous collection of summaries, which is used as a
1125 -- cache to avoid recalculating a module summary if the source is
1128 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1129 downsweep roots old_summaries
1130 = do rootSummaries <- mapM getRootSummary roots
1131 checkDuplicates rootSummaries
1133 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1134 (ms_imps m)) rootSummaries))
1135 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1136 let mod = ms_mod s, isHomeModule mod
1138 return all_summaries
1140 getRootSummary :: FilePath -> IO ModSummary
1142 | haskellish_src_file file
1143 = do exists <- doesFileExist file
1144 if exists then summariseFile file else do
1145 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1147 = do exists <- doesFileExist hs_file
1148 if exists then summariseFile hs_file else do
1149 exists <- doesFileExist lhs_file
1150 if exists then summariseFile lhs_file else do
1151 let mod_name = mkModuleName file
1152 maybe_summary <- getSummary (file, mod_name)
1153 case maybe_summary of
1154 Nothing -> packageModErr mod_name
1157 hs_file = file ++ ".hs"
1158 lhs_file = file ++ ".lhs"
1160 -- In a root module, the filename is allowed to diverge from the module
1161 -- name, so we have to check that there aren't multiple root files
1162 -- defining the same module (otherwise the duplicates will be silently
1163 -- ignored, leading to confusing behaviour).
1164 checkDuplicates :: [ModSummary] -> IO ()
1165 checkDuplicates summaries = mapM_ check summaries
1170 many -> multiRootsErr modl many
1171 where modl = ms_mod summ
1173 [ fromJust (ml_hs_file (ms_location summ'))
1174 | summ' <- summaries, ms_mod summ' == modl ]
1176 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1177 getSummary (currentMod,nm)
1178 = do found <- findModule nm
1180 Just (mod, location) -> do
1181 let old_summary = findModInSummaries old_summaries mod
1182 summarise mod location old_summary
1185 throwDyn (CmdLineError
1186 ("can't find module `"
1187 ++ showSDoc (ppr nm) ++ "' (while processing "
1188 ++ show currentMod ++ ")"))
1190 -- loop invariant: env doesn't contain package modules
1191 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1192 loop [] env = return (moduleEnvElts env)
1194 = do -- imports for modules we don't already have
1195 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1198 needed_summaries <- mapM getSummary needed_imps
1200 -- get just the "home" modules
1201 let new_home_summaries = [ s | Just s <- needed_summaries ]
1203 -- loop, checking the new imports
1204 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1205 (ms_imps m)) new_home_summaries)
1206 loop new_imps (extendModuleEnvList env
1207 [ (ms_mod s, s) | s <- new_home_summaries ])
1209 -----------------------------------------------------------------------------
1210 -- Summarising modules
1212 -- We have two types of summarisation:
1214 -- * Summarise a file. This is used for the root module(s) passed to
1215 -- cmLoadModules. The file is read, and used to determine the root
1216 -- module name. The module name may differ from the filename.
1218 -- * Summarise a module. We are given a module name, and must provide
1219 -- a summary. The finder is used to locate the file in which the module
1222 summariseFile :: FilePath -> IO ModSummary
1224 = do hspp_fn <- preprocess file
1225 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1227 let (path, basename, _ext) = splitFilename3 file
1228 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1229 the_imps = filter (/= gHC_PRIM_Name) imps
1232 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1235 <- case ml_hs_file location of
1236 Nothing -> noHsFileErr mod_name
1237 Just src_fn -> getModificationTime src_fn
1239 return (ModSummary { ms_mod = mod,
1240 ms_location = location{ml_hspp_file=Just hspp_fn},
1241 ms_srcimps = srcimps, ms_imps = the_imps,
1242 ms_hs_date = src_timestamp })
1244 -- Summarise a module, and pick up source and timestamp.
1245 summarise :: Module -> ModLocation -> Maybe ModSummary
1246 -> IO (Maybe ModSummary)
1247 summarise mod location old_summary
1248 | not (isHomeModule mod) = return Nothing
1250 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1252 case ml_hs_file location of {
1253 Nothing -> noHsFileErr mod;
1256 src_timestamp <- getModificationTime src_fn
1258 -- return the cached summary if the source didn't change
1259 case old_summary of {
1260 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1263 hspp_fn <- preprocess hs_fn
1264 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1266 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1267 the_imps = filter (/= gHC_PRIM_Name) imps
1269 when (mod_name /= moduleName mod) $
1270 throwDyn (ProgramError
1271 (showSDoc (text hs_fn
1272 <> text ": file name does not match module name"
1273 <+> quotes (ppr (moduleName mod)))))
1275 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1276 srcimps the_imps src_timestamp))
1282 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1285 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1286 quotes (ppr mod) <+>
1287 text "is a package module")))
1289 multiRootsErr mod files
1290 = throwDyn (ProgramError (showSDoc (
1291 text "module" <+> quotes (ppr mod) <+>
1292 text "is defined in multiple files:" <+>
1293 sep (map text files))))
1297 %************************************************************************
1301 %************************************************************************
1304 -- The ModLocation contains both the original source filename and the
1305 -- filename of the cleaned-up source file after all preprocessing has been
1306 -- done. The point is that the summariser will have to cpp/unlit/whatever
1307 -- all files anyway, and there's no point in doing this twice -- just
1308 -- park the result in a temp file, put the name of it in the location,
1309 -- and let @compile@ read from that file on the way back up.
1312 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1314 emptyMG :: ModuleGraph
1319 ms_mod :: Module, -- name, package
1320 ms_location :: ModLocation, -- location
1321 ms_srcimps :: [ModuleName], -- source imports
1322 ms_imps :: [ModuleName], -- non-source imports
1323 ms_hs_date :: ClockTime -- timestamp of summarised file
1326 instance Outputable ModSummary where
1328 = sep [text "ModSummary {",
1329 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1330 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1331 text "ms_imps =" <+> ppr (ms_imps ms),
1332 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1336 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1338 modSummaryName :: ModSummary -> ModuleName
1339 modSummaryName = moduleName . ms_mod