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, nameModule )
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 (nameModule 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 findLinkable mod_name (ms_location summary)
806 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
809 case (old_linkable, maybe_disk_linkable) of
810 (Nothing, Nothing) -> []
812 -- new object linkable just appeared
813 (Nothing, Just l) -> up_to_date l True
816 | isObjectLinkable l -> []
817 -- object linkable disappeared! In case we need to
818 -- relink the module, disregard the old linkable and
819 -- just interpret the module from now on.
820 | otherwise -> up_to_date l False
821 -- old byte code linkable
824 | not (isObjectLinkable l) -> up_to_date l False
825 -- if the previous linkable was interpreted, then we
826 -- ignore a newly compiled version, because the version
827 -- numbers in the interface file will be out-of-sync with
828 -- our internal ones.
829 | linkableTime l' > linkableTime l -> up_to_date l' True
830 | linkableTime l' == linkableTime l -> up_to_date l False
832 -- on-disk linkable has been replaced by an older one!
833 -- again, disregard the previous one.
836 | linkableTime l < ms_hs_date summary = []
837 | otherwise = [(l,b)]
838 -- why '<' rather than '<=' above? If the filesystem stores
839 -- times to the nearset second, we may occasionally find that
840 -- the object & source have the same modification time,
841 -- especially if the source was automatically generated
842 -- and compiled. Using >= is slightly unsafe, but it matches
845 return (new_linkables' ++ new_linkables)
848 hptLinkables :: HomePackageTable -> [Linkable]
849 -- Get all the linkables from the home package table, one for each module
850 -- Once the HPT is up to date, these are the ones we should link
851 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
854 -----------------------------------------------------------------------------
855 -- Do a pre-upsweep without use of "compile", to establish a
856 -- (downward-closed) set of stable modules for which we won't call compile.
859 -- * has a valid linkable (see getValidLinkables above)
860 -- * depends only on stable modules
861 -- * has an interface in the HPT (interactive mode only)
863 preUpsweep :: [Linkable] -- new valid linkables
864 -> [ModuleName] -- names of all mods encountered in downsweep
865 -> [ModuleName] -- accumulating stable modules
866 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
867 -> IO [ModuleName] -- stable modules
869 preUpsweep valid_lis all_home_mods stable [] = return stable
870 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
871 = do let scc = flattenSCC scc0
872 scc_allhomeimps :: [ModuleName]
874 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
875 all_imports_in_scc_or_stable
876 = all in_stable_or_scc scc_allhomeimps
878 = map modSummaryName scc
880 = m `elem` scc_names || m `elem` stable
882 -- now we check for valid linkables: each module in the SCC must
883 -- have a valid linkable (see getValidLinkables above).
884 has_valid_linkable new_summary
885 = isJust (findModuleLinkable_maybe valid_lis modname)
886 where modname = modSummaryName new_summary
888 scc_is_stable = all_imports_in_scc_or_stable
889 && all has_valid_linkable scc
892 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
893 else preUpsweep valid_lis all_home_mods stable sccs
896 -- Helper for preUpsweep. Assuming that new_summary's imports are all
897 -- stable (in the sense of preUpsweep), determine if new_summary is itself
898 -- stable, and, if so, in batch mode, return its linkable.
899 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
900 findInSummaries old_summaries mod_name
901 = [s | s <- old_summaries, modSummaryName s == mod_name]
903 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
904 findModInSummaries old_summaries mod
905 = case [s | s <- old_summaries, ms_mod s == mod] of
909 -- Return (names of) all those in modsDone who are part of a cycle
910 -- as defined by theGraph.
911 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
912 findPartiallyCompletedCycles modsDone theGraph
916 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
917 chew ((CyclicSCC vs):rest)
918 = let names_in_this_cycle = nub (map modSummaryName vs)
920 = nub ([done | done <- modsDone,
921 done `elem` names_in_this_cycle])
922 chewed_rest = chew rest
924 if notNull mods_in_this_cycle
925 && length mods_in_this_cycle < length names_in_this_cycle
926 then mods_in_this_cycle ++ chewed_rest
930 data CmThreaded -- stuff threaded through individual module compilations
931 = CmThreaded PersistentCompilerState HomePackageTable
934 -- Compile multiple modules, stopping as soon as an error appears.
935 -- There better had not be any cyclic groups here -- we check for them.
936 upsweep_mods :: GhciMode
938 -> [Linkable] -- Valid linkables
939 -> (ModuleName -> [ModuleName]) -- to construct downward closures
940 -> CmThreaded -- PCS & HPT
941 -> IO () -- how to clean up unwanted tmp files
942 -> [SCC ModSummary] -- mods to do (the worklist)
943 -- ...... RETURNING ......
945 CmThreaded, -- Includes linkables
946 [ModSummary]) -- Mods which succeeded
948 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
950 = return (Succeeded, threaded, [])
952 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
954 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
955 unwords (map (moduleNameUserString.modSummaryName) ms))
956 return (Failed, threaded, [])
958 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
959 ((AcyclicSCC mod):mods)
960 = do --case threaded of
961 -- CmThreaded pcsz hptz
962 -- -> putStrLn ("UPSWEEP_MOD: hpt = " ++
963 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM hptz)))
965 (ok_flag, threaded1) <- upsweep_mod ghci_mode dflags oldUI threaded mod
966 (reachable_from (modSummaryName mod))
968 cleanup -- Remove unwanted tmp files between compilations
970 if failed ok_flag then
971 return (Failed, threaded1, [])
973 (restOK, threaded2, modOKs)
974 <- upsweep_mods ghci_mode dflags oldUI reachable_from
975 threaded1 cleanup mods
976 return (restOK, threaded2, mod:modOKs)
979 -- Compile a single module. Always produce a Linkable for it if
980 -- successful. If no compilation happened, return the old Linkable.
981 upsweep_mod :: GhciMode
987 -> IO (SuccessFlag, CmThreaded)
989 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
991 let this_mod = ms_mod summary1
992 location = ms_location summary1
993 mod_name = moduleName this_mod
995 let (CmThreaded pcs1 hpt1) = threaded1
996 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
997 Just mod_info -> Just (hm_iface mod_info)
1000 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1001 source_unchanged = isJust maybe_old_linkable
1003 reachable_only = filter (/= mod_name) reachable_inc_me
1005 -- In interactive mode, all home modules below us *must* have an
1006 -- interface in the HPT. We never demand-load home interfaces in
1007 -- interactive mode.
1009 = ASSERT(ghci_mode == Batch || all (`elemUFM` hpt1) reachable_only)
1010 retainInTopLevelEnvs reachable_only hpt1
1012 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1015 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1018 compresult <- compile ghci_mode this_mod location source_unchanged
1019 have_object mb_old_iface hpt1_strictDC pcs1
1023 -- Compilation "succeeded", and may or may not have returned a new
1024 -- linkable (depending on whether compilation was actually performed
1026 CompOK pcs2 new_details new_iface maybe_new_linkable
1028 new_linkable = maybe_new_linkable `orElse` old_linkable
1029 new_info = HomeModInfo { hm_iface = new_iface,
1030 hm_details = new_details,
1031 hm_linkable = new_linkable }
1032 hpt2 = extendModuleEnv hpt1 this_mod new_info
1034 return (Succeeded, CmThreaded pcs2 hpt2)
1036 -- Compilation failed. Compile may still have updated the PCS, tho.
1037 CompErrs pcs2 -> return (Failed, CmThreaded pcs2 hpt1)
1039 -- Filter modules in the HPT
1040 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1041 retainInTopLevelEnvs keep_these hpt
1042 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
1044 maybeLookupUFM ufm u = case lookupUFM ufm u of
1046 Just val -> [(u, val)]
1048 -- Needed to clean up HPT so that we don't get duplicates in inst env
1049 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1050 downwards_closure_of_module summaries root
1051 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1052 toEdge summ = (modSummaryName summ,
1053 filter (`elem` all_mods) (ms_allimps summ))
1055 all_mods = map modSummaryName summaries
1057 res = simple_transitive_closure (map toEdge summaries) [root]
1059 -- trace (showSDoc (text "DC of mod" <+> ppr root
1060 -- <+> text "=" <+> ppr res)) $
1063 -- Calculate transitive closures from a set of roots given an adjacency list
1064 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1065 simple_transitive_closure graph set
1066 = let set2 = nub (concatMap dsts set ++ set)
1067 dsts node = fromMaybe [] (lookup node graph)
1069 if length set == length set2
1071 else simple_transitive_closure graph set2
1074 -- Calculate SCCs of the module graph, with or without taking into
1075 -- account source imports.
1076 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1077 topological_sort include_source_imports summaries
1079 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1081 = (summ, modSummaryName summ,
1082 (if include_source_imports
1083 then ms_srcimps summ else []) ++ ms_imps summ)
1085 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1086 mash_edge (summ, m, m_imports)
1087 = case lookup m key_map of
1088 Nothing -> panic "reverse_topological_sort"
1089 Just mk -> (summ, mk,
1090 -- ignore imports not from the home package
1091 catMaybes (map (flip lookup key_map) m_imports))
1093 edges = map toEdge summaries
1094 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1095 scc_input = map mash_edge edges
1096 sccs = stronglyConnComp scc_input
1101 -----------------------------------------------------------------------------
1102 -- Downsweep (dependency analysis)
1104 -- Chase downwards from the specified root set, returning summaries
1105 -- for all home modules encountered. Only follow source-import
1108 -- We pass in the previous collection of summaries, which is used as a
1109 -- cache to avoid recalculating a module summary if the source is
1112 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1113 downsweep roots old_summaries
1114 = do rootSummaries <- mapM getRootSummary roots
1115 checkDuplicates rootSummaries
1117 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1118 (ms_imps m)) rootSummaries))
1119 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1120 let mod = ms_mod s, isHomeModule mod
1122 return all_summaries
1124 getRootSummary :: FilePath -> IO ModSummary
1126 | haskellish_src_file file
1127 = do exists <- doesFileExist file
1128 if exists then summariseFile file else do
1129 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1131 = do exists <- doesFileExist hs_file
1132 if exists then summariseFile hs_file else do
1133 exists <- doesFileExist lhs_file
1134 if exists then summariseFile lhs_file else do
1135 let mod_name = mkModuleName file
1136 maybe_summary <- getSummary (file, mod_name)
1137 case maybe_summary of
1138 Nothing -> packageModErr mod_name
1141 hs_file = file ++ ".hs"
1142 lhs_file = file ++ ".lhs"
1144 -- In a root module, the filename is allowed to diverge from the module
1145 -- name, so we have to check that there aren't multiple root files
1146 -- defining the same module (otherwise the duplicates will be silently
1147 -- ignored, leading to confusing behaviour).
1148 checkDuplicates :: [ModSummary] -> IO ()
1149 checkDuplicates summaries = mapM_ check summaries
1154 many -> multiRootsErr modl many
1155 where modl = ms_mod summ
1157 [ fromJust (ml_hs_file (ms_location summ'))
1158 | summ' <- summaries, ms_mod summ' == modl ]
1160 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1161 getSummary (currentMod,nm)
1162 = do found <- findModule nm
1164 Just (mod, location) -> do
1165 let old_summary = findModInSummaries old_summaries mod
1166 summarise mod location old_summary
1169 throwDyn (CmdLineError
1170 ("can't find module `"
1171 ++ showSDoc (ppr nm) ++ "' (while processing "
1172 ++ show currentMod ++ ")"))
1174 -- loop invariant: env doesn't contain package modules
1175 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1176 loop [] env = return (moduleEnvElts env)
1178 = do -- imports for modules we don't already have
1179 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1182 needed_summaries <- mapM getSummary needed_imps
1184 -- get just the "home" modules
1185 let new_home_summaries = [ s | Just s <- needed_summaries ]
1187 -- loop, checking the new imports
1188 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1189 (ms_imps m)) new_home_summaries)
1190 loop new_imps (extendModuleEnvList env
1191 [ (ms_mod s, s) | s <- new_home_summaries ])
1193 -----------------------------------------------------------------------------
1194 -- Summarising modules
1196 -- We have two types of summarisation:
1198 -- * Summarise a file. This is used for the root module(s) passed to
1199 -- cmLoadModules. The file is read, and used to determine the root
1200 -- module name. The module name may differ from the filename.
1202 -- * Summarise a module. We are given a module name, and must provide
1203 -- a summary. The finder is used to locate the file in which the module
1206 summariseFile :: FilePath -> IO ModSummary
1208 = do hspp_fn <- preprocess file
1209 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1211 let (path, basename, ext) = splitFilename3 file
1212 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1213 the_imps = filter (/= gHC_PRIM_Name) imps
1215 (mod, location) <- mkHomeModLocation mod_name True{-is a root-}
1219 <- case ml_hs_file location of
1220 Nothing -> noHsFileErr mod_name
1221 Just src_fn -> getModificationTime src_fn
1223 return (ModSummary { ms_mod = mod,
1224 ms_location = location{ml_hspp_file=Just hspp_fn},
1225 ms_srcimps = srcimps, ms_imps = the_imps,
1226 ms_hs_date = src_timestamp })
1228 -- Summarise a module, and pick up source and timestamp.
1229 summarise :: Module -> ModLocation -> Maybe ModSummary
1230 -> IO (Maybe ModSummary)
1231 summarise mod location old_summary
1232 | not (isHomeModule mod) = return Nothing
1234 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1236 case ml_hs_file location of {
1237 Nothing -> noHsFileErr mod;
1240 src_timestamp <- getModificationTime src_fn
1242 -- return the cached summary if the source didn't change
1243 case old_summary of {
1244 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1247 hspp_fn <- preprocess hs_fn
1248 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1250 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1251 the_imps = filter (/= gHC_PRIM_Name) imps
1253 when (mod_name /= moduleName mod) $
1254 throwDyn (ProgramError
1255 (showSDoc (text hs_fn
1256 <> text ": file name does not match module name"
1257 <+> quotes (ppr (moduleName mod)))))
1259 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1260 srcimps the_imps src_timestamp))
1266 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1269 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1270 quotes (ppr mod) <+>
1271 text "is a package module")))
1273 multiRootsErr mod files
1274 = throwDyn (ProgramError (showSDoc (
1275 text "module" <+> quotes (ppr mod) <+>
1276 text "is defined in multiple files:" <+>
1277 sep (map text files))))
1281 %************************************************************************
1285 %************************************************************************
1288 -- The ModLocation contains both the original source filename and the
1289 -- filename of the cleaned-up source file after all preprocessing has been
1290 -- done. The point is that the summariser will have to cpp/unlit/whatever
1291 -- all files anyway, and there's no point in doing this twice -- just
1292 -- park the result in a temp file, put the name of it in the location,
1293 -- and let @compile@ read from that file on the way back up.
1296 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1298 emptyMG :: ModuleGraph
1303 ms_mod :: Module, -- name, package
1304 ms_location :: ModLocation, -- location
1305 ms_srcimps :: [ModuleName], -- source imports
1306 ms_imps :: [ModuleName], -- non-source imports
1307 ms_hs_date :: ClockTime -- timestamp of summarised file
1310 instance Outputable ModSummary where
1312 = sep [text "ModSummary {",
1313 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1314 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1315 text "ms_imps =" <+> ppr (ms_imps ms),
1316 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1320 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1322 modSummaryName :: ModSummary -> ModuleName
1323 modSummaryName = moduleName . ms_mod