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, v_NoHsMain )
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 Left _ -> throwDyn (CmdLineError ("can't find module `"
236 ++ moduleNameUserString mn ++ "'"))
237 Right (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 new_pit = eps_PIT (pcs_EPS new_pcs)
260 pairs = map (\x -> (x, getFixity new_pit (getName x))) things
261 return (cmstate{ pcs=new_pcs }, pairs)
263 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
264 hsc_env = HscEnv { hsc_mode = Interactive,
268 getFixity :: PackageIfaceTable -> Name -> Fixity
270 | isExternalName name,
271 Just iface <- lookupIface hpt pit (nameModule name),
272 Just (FixitySig _ fixity _) <- lookupNameEnv (mi_fixities iface) name
277 -- ---------------------------------------------------------------------------
278 -- cmBrowseModule: get all the TyThings defined in a module
280 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
281 -> IO (CmState, [TyThing])
282 cmBrowseModule cmstate dflags str exports_only = do
283 let mn = mkModuleName str
284 mod <- moduleNameToModule hpt mn
285 (pcs1, maybe_ty_things)
286 <- getModuleContents hsc_env pcs mod exports_only
287 case maybe_ty_things of
288 Nothing -> return (cmstate{pcs=pcs1}, [])
289 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
291 hsc_env = HscEnv { hsc_mode = Interactive, hsc_dflags = dflags,
293 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
295 -----------------------------------------------------------------------------
296 -- cmRunStmt: Run a statement/expr.
299 = CmRunOk [Name] -- names bound by this evaluation
301 | CmRunException Exception -- statement raised an exception
303 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
304 cmRunStmt cmstate@CmState{ hpt=hpt, pcs=pcs, ic=icontext }
307 let hsc_env = HscEnv { hsc_mode = Interactive,
311 (new_pcs, maybe_stuff)
312 <- hscStmt hsc_env pcs icontext expr
315 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
316 Just (new_ic, names, hval) -> do
318 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
319 either_hvals <- sandboxIO thing_to_run
323 -- on error, keep the *old* interactive context,
324 -- so that 'it' is not bound to something
325 -- that doesn't exist.
326 return ( cmstate{ pcs=new_pcs }, CmRunException e )
329 -- Get the newly bound things, and bind them.
330 -- Don't need to delete any shadowed bindings;
331 -- the new ones override the old ones.
332 extendLinkEnv (zip names hvals)
334 return (cmstate{ pcs=new_pcs, ic=new_ic },
338 -- We run the statement in a "sandbox" to protect the rest of the
339 -- system from anything the expression might do. For now, this
340 -- consists of just wrapping it in an exception handler, but see below
341 -- for another version.
343 sandboxIO :: IO a -> IO (Either Exception a)
344 sandboxIO thing = Exception.try thing
347 -- This version of sandboxIO runs the expression in a completely new
348 -- RTS main thread. It is disabled for now because ^C exceptions
349 -- won't be delivered to the new thread, instead they'll be delivered
350 -- to the (blocked) GHCi main thread.
352 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
354 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
356 st_thing <- newStablePtr (Exception.try thing)
357 alloca $ \ p_st_result -> do
358 stat <- rts_evalStableIO st_thing p_st_result
359 freeStablePtr st_thing
361 then do st_result <- peek p_st_result
362 result <- deRefStablePtr st_result
363 freeStablePtr st_result
364 return (Right result)
366 return (Left (fromIntegral stat))
368 foreign import "rts_evalStableIO" {- safe -}
369 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
370 -- more informative than the C type!
373 -----------------------------------------------------------------------------
374 -- cmTypeOfExpr: returns a string representing the type of an expression
376 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
377 cmTypeOfExpr cmstate dflags expr
378 = do (new_pcs, maybe_stuff) <- hscTcExpr hsc_env pcs ic expr
380 let new_cmstate = cmstate{pcs = new_pcs}
383 Nothing -> return (new_cmstate, Nothing)
384 Just ty -> return (new_cmstate, Just str)
386 str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
387 unqual = icPrintUnqual ic
388 tidy_ty = tidyType emptyTidyEnv ty
390 CmState{ hpt=hpt, pcs=pcs, ic=ic } = cmstate
391 hsc_env = HscEnv { hsc_mode = Interactive,
397 -----------------------------------------------------------------------------
398 -- cmTypeOfName: returns a string representing the type of a name.
400 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
401 cmTypeOfName CmState{ pcs=pcs, ic=ic } name
403 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
404 case lookupNameEnv (ic_type_env ic) name of
405 Nothing -> return Nothing
406 Just (AnId id) -> return (Just str)
408 unqual = icPrintUnqual ic
409 ty = tidyType emptyTidyEnv (idType id)
410 str = showSDocForUser unqual (ppr ty)
412 _ -> panic "cmTypeOfName"
414 -----------------------------------------------------------------------------
415 -- cmCompileExpr: compile an expression and deliver an HValue
417 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
418 cmCompileExpr cmstate dflags expr
420 let hsc_env = HscEnv { hsc_mode = Interactive,
424 (new_pcs, maybe_stuff)
425 <- hscStmt hsc_env pcs icontext
426 ("let __cmCompileExpr = "++expr)
429 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
430 Just (new_ic, names, hval) -> do
433 hvals <- (unsafeCoerce# hval) :: IO [HValue]
435 case (names,hvals) of
436 ([n],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
437 _ -> panic "cmCompileExpr"
440 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
445 %************************************************************************
447 Loading and unloading
449 %************************************************************************
452 -----------------------------------------------------------------------------
453 -- Unload the compilation manager's state: everything it knows about the
454 -- current collection of modules in the Home package.
456 cmUnload :: CmState -> DynFlags -> IO CmState
457 cmUnload state@CmState{ gmode=mode, pcs=pcs } dflags
458 = do -- Throw away the old home dir cache
461 -- Unload everything the linker knows about
462 cm_unload mode dflags []
464 -- Start with a fresh CmState, but keep the PersistentCompilerState
465 new_state <- cmInit mode
466 return new_state{ pcs=pcs }
468 cm_unload Batch dflags linkables = return ()
471 cm_unload Interactive dflags linkables = Linker.unload dflags linkables
473 cm_unload Interactive dflags linkables = panic "unload: no interpreter"
477 -----------------------------------------------------------------------------
478 -- Trace dependency graph
480 -- This is a seperate pass so that the caller can back off and keep
481 -- the current state if the downsweep fails. Typically the caller
482 -- might go cmDepAnal
485 -- He wants to do the dependency analysis before the unload, so that
486 -- if the former fails he can use the later
488 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
489 cmDepAnal cmstate dflags rootnames
490 = do showPass dflags "Chasing dependencies"
491 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
492 hPutStrLn stderr (showSDoc (hcat [
493 text "Chasing modules from: ",
494 hcat (punctuate comma (map text rootnames))]))
495 downsweep rootnames (mg cmstate)
497 -----------------------------------------------------------------------------
498 -- The real business of the compilation manager: given a system state and
499 -- a module name, try and bring the module up to date, probably changing
500 -- the system state at the same time.
502 cmLoadModules :: CmState -- The HPT may not be as up to date
503 -> DynFlags -- as the ModuleGraph
504 -> ModuleGraph -- Bang up to date
505 -> IO (CmState, -- new state
506 SuccessFlag, -- was successful
507 [String]) -- list of modules loaded
509 cmLoadModules cmstate1 dflags mg2unsorted
510 = do -- version 1's are the original, before downsweep
511 let pcs1 = pcs cmstate1
512 let hpt1 = hpt cmstate1
514 let ghci_mode = gmode cmstate1 -- this never changes
516 -- Do the downsweep to reestablish the module graph
517 let verb = verbosity dflags
519 -- Find out if we have a Main module
521 = any ((=="Main").moduleNameUserString.modSummaryName)
524 let mg2unsorted_names = map modSummaryName mg2unsorted
526 -- reachable_from follows source as well as normal imports
527 let reachable_from :: ModuleName -> [ModuleName]
528 reachable_from = downwards_closure_of_module mg2unsorted
530 -- should be cycle free; ignores 'import source's
531 let mg2 = topological_sort False mg2unsorted
532 -- ... whereas this takes them into account. Used for
533 -- backing out partially complete cycles following a failed
534 -- upsweep, and for removing from hpt all the modules
535 -- not in strict downwards closure, during calls to compile.
536 let mg2_with_srcimps = topological_sort True mg2unsorted
538 -- Sort out which linkables we wish to keep in the unlinked image.
539 -- See getValidLinkables below for details.
540 (valid_old_linkables, new_linkables)
541 <- getValidLinkables ghci_mode (hptLinkables hpt1)
542 mg2unsorted_names mg2_with_srcimps
544 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
546 -- Uniq of ModuleName is the same as Module, fortunately...
547 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
549 -- When (verb >= 2) $
550 -- putStrLn (showSDoc (text "Valid linkables:"
551 -- <+> ppr valid_linkables))
553 -- Figure out a stable set of modules which can be retained
554 -- the top level envs, to avoid upsweeping them. Goes to a
555 -- bit of trouble to avoid upsweeping module cycles.
557 -- Construct a set S of stable modules like this:
558 -- Travel upwards, over the sccified graph. For each scc
559 -- of modules ms, add ms to S only if:
560 -- 1. All home imports of ms are either in ms or S
561 -- 2. A valid old linkable exists for each module in ms
563 stable_mods <- preUpsweep valid_old_linkables
564 mg2unsorted_names [] mg2_with_srcimps
567 = concatMap (findInSummaries mg2unsorted) stable_mods
570 = filter (\m -> linkableModName m `elem` stable_mods)
574 hPutStrLn stderr (showSDoc (text "Stable modules:"
575 <+> sep (map (text.moduleNameUserString) stable_mods)))
577 -- Unload any modules which are going to be re-linked this
579 cm_unload ghci_mode dflags stable_linkables
581 -- we can now glom together our linkable sets
582 let valid_linkables = valid_old_linkables ++ new_linkables
584 -- We could at this point detect cycles which aren't broken by
585 -- a source-import, and complain immediately, but it seems better
586 -- to let upsweep_mods do this, so at least some useful work gets
587 -- done before the upsweep is abandoned.
589 = filter (\scc -> any (`notElem` stable_mods)
590 (map modSummaryName (flattenSCC scc)))
593 --hPutStrLn stderr "after tsort:\n"
594 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
596 -- Because we don't take into account source imports when doing
597 -- the topological sort, there shouldn't be any cycles in mg2.
598 -- If there is, we complain and give up -- the user needs to
599 -- break the cycle using a boot file.
601 -- Now do the upsweep, calling compile for each module in
602 -- turn. Final result is version 3 of everything.
604 let threaded2 = CmThreaded pcs1 hpt2
606 -- clean up between compilations
607 let cleanup = cleanTempFilesExcept verb
608 (ppFilesFromSummaries (flattenSCCs mg2))
610 (upsweep_ok, threaded3, modsUpswept)
611 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
612 threaded2 cleanup upsweep_these
614 let (CmThreaded pcs3 hpt3) = threaded3
616 -- At this point, modsUpswept and newLis should have the same
617 -- length, so there is one new (or old) linkable for each
618 -- mod which was processed (passed to compile).
620 -- Make modsDone be the summaries for each home module now
621 -- available; this should equal the domain of hpt3.
622 -- (NOT STRICTLY TRUE if an interactive session was started
623 -- with some object on disk ???)
624 -- Get in in a roughly top .. bottom order (hence reverse).
626 let modsDone = reverse modsUpswept ++ stable_summaries
628 -- Try and do linking in some form, depending on whether the
629 -- upsweep was completely or only partially successful.
631 if succeeded upsweep_ok
634 -- Easy; just relink it all.
635 do when (verb >= 2) $
636 hPutStrLn stderr "Upsweep completely successful."
638 -- clean up after ourselves
639 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
641 ofile <- readIORef v_Output_file
642 no_hs_main <- readIORef v_NoHsMain
644 -- Issue a warning for the confusing case where the user
645 -- said '-o foo' but we're not going to do any linking.
646 -- We attempt linking if either (a) one of the modules is
647 -- called Main, or (b) the user said -no-hs-main, indicating
648 -- that main() is going to come from somewhere else.
650 let do_linking = a_root_is_Main || no_hs_main
651 when (ghci_mode == Batch && isJust ofile && not do_linking
653 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
655 -- link everything together
656 linkresult <- link ghci_mode dflags do_linking hpt3
658 cmLoadFinish Succeeded linkresult
659 hpt3 modsDone ghci_mode pcs3
662 -- Tricky. We need to back out the effects of compiling any
663 -- half-done cycles, both so as to clean up the top level envs
664 -- and to avoid telling the interactive linker to link them.
665 do when (verb >= 2) $
666 hPutStrLn stderr "Upsweep partially successful."
669 = map modSummaryName modsDone
670 let mods_to_zap_names
671 = findPartiallyCompletedCycles modsDone_names
674 = filter ((`notElem` mods_to_zap_names).modSummaryName)
677 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep) hpt3
679 -- Clean up after ourselves
680 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
682 -- Link everything together
683 linkresult <- link ghci_mode dflags False hpt4
685 cmLoadFinish Failed linkresult
686 hpt4 mods_to_keep ghci_mode pcs3
689 -- Finish up after a cmLoad.
691 -- If the link failed, unload everything and return.
692 cmLoadFinish ok Failed hpt mods ghci_mode pcs = do
693 dflags <- getDynFlags
694 cm_unload ghci_mode dflags []
695 new_state <- cmInit ghci_mode
696 return (new_state{ pcs=pcs }, Failed, [])
698 -- Empty the interactive context and set the module context to the topmost
699 -- newly loaded module, or the Prelude if none were loaded.
700 cmLoadFinish ok Succeeded hpt mods ghci_mode pcs
701 = do let new_cmstate = CmState{ hpt=hpt, mg=mods,
702 gmode=ghci_mode, pcs=pcs,
703 ic = emptyInteractiveContext }
704 mods_loaded = map (moduleNameUserString.modSummaryName) mods
706 return (new_cmstate, ok, mods_loaded)
708 -- used to fish out the preprocess output files for the purposes
710 ppFilesFromSummaries summaries
711 = [ fn | Just fn <- map toPpFile summaries ]
714 | hspp /= ml_hs_file loc = hspp
715 | otherwise = Nothing
717 loc = ms_location sum
718 hspp = ml_hspp_file loc
721 -----------------------------------------------------------------------------
724 -- For each module (or SCC of modules), we take:
726 -- - an on-disk linkable, if this is the first time around and one
729 -- - the old linkable, otherwise (and if one is available).
731 -- and we throw away the linkable if it is older than the source file.
732 -- In interactive mode, we also ignore the on-disk linkables unless
733 -- all of the dependents of this SCC also have on-disk linkables (we
734 -- can't have dynamically loaded objects that depend on interpreted
737 -- If a module has a valid linkable, then it may be STABLE (see below),
738 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
741 -- ToDo: this pass could be merged with the preUpsweep.
745 -> [Linkable] -- old linkables
746 -> [ModuleName] -- all home modules
747 -> [SCC ModSummary] -- all modules in the program, dependency order
748 -> IO ( [Linkable], -- still-valid linkables
749 [Linkable] -- new linkables we just found
752 getValidLinkables mode old_linkables all_home_mods module_graph = do
753 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
755 return (partition_it ls [] [])
757 partition_it [] valid new = (valid,new)
758 partition_it ((l,b):ls) valid new
759 | b = partition_it ls valid (l:new)
760 | otherwise = partition_it ls (l:valid) new
763 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
765 scc = flattenSCC scc0
766 scc_names = map modSummaryName scc
767 home_module m = m `elem` all_home_mods && m `notElem` scc_names
768 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
769 -- NB. ms_imps, not ms_allimps above. We don't want to
770 -- force a module's SOURCE imports to be already compiled for
771 -- its object linkable to be valid.
774 case findModuleLinkable_maybe (map fst new_linkables) m of
776 Just l -> isObjectLinkable l
778 objects_allowed = mode == Batch || all has_object scc_allhomeimps
782 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
784 -- since an scc can contain only all objects or no objects at all,
785 -- we have to check whether we got all objects or not, and re-do
786 -- the linkable check if not.
789 && not (all isObjectLinkable (map fst new_linkables'))
790 then foldM (getValidLinkable old_linkables False) [] scc
791 else return new_linkables'
793 return (new_linkables ++ new_linkables')
796 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
797 -> IO [(Linkable,Bool)]
798 -- True <=> linkable is new; i.e. freshly discovered on the disk
799 -- presumably generated 'on the side'
800 -- by a separate GHC run
801 getValidLinkable old_linkables objects_allowed new_linkables summary
802 -- 'objects_allowed' says whether we permit this module to
803 -- have a .o-file linkable. We only permit it if all the
804 -- modules it depends on also have .o files; a .o file can't
805 -- link to a bytecode module
806 = do let mod_name = modSummaryName summary
809 <- if (not objects_allowed)
812 else findLinkable mod_name (ms_location summary)
814 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
817 case (old_linkable, maybe_disk_linkable) of
818 (Nothing, Nothing) -> []
820 -- new object linkable just appeared
821 (Nothing, Just l) -> up_to_date l True
824 | isObjectLinkable l -> []
825 -- object linkable disappeared! In case we need to
826 -- relink the module, disregard the old linkable and
827 -- just interpret the module from now on.
828 | otherwise -> up_to_date l False
829 -- old byte code linkable
832 | not (isObjectLinkable l) -> up_to_date l False
833 -- if the previous linkable was interpreted, then we
834 -- ignore a newly compiled version, because the version
835 -- numbers in the interface file will be out-of-sync with
836 -- our internal ones.
837 | linkableTime l' > linkableTime l -> up_to_date l' True
838 | linkableTime l' == linkableTime l -> up_to_date l False
840 -- on-disk linkable has been replaced by an older one!
841 -- again, disregard the previous one.
844 | linkableTime l < ms_hs_date summary = []
845 | otherwise = [(l,b)]
846 -- why '<' rather than '<=' above? If the filesystem stores
847 -- times to the nearset second, we may occasionally find that
848 -- the object & source have the same modification time,
849 -- especially if the source was automatically generated
850 -- and compiled. Using >= is slightly unsafe, but it matches
853 return (new_linkables' ++ new_linkables)
856 hptLinkables :: HomePackageTable -> [Linkable]
857 -- Get all the linkables from the home package table, one for each module
858 -- Once the HPT is up to date, these are the ones we should link
859 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
862 -----------------------------------------------------------------------------
863 -- Do a pre-upsweep without use of "compile", to establish a
864 -- (downward-closed) set of stable modules for which we won't call compile.
867 -- * has a valid linkable (see getValidLinkables above)
868 -- * depends only on stable modules
869 -- * has an interface in the HPT (interactive mode only)
871 preUpsweep :: [Linkable] -- new valid linkables
872 -> [ModuleName] -- names of all mods encountered in downsweep
873 -> [ModuleName] -- accumulating stable modules
874 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
875 -> IO [ModuleName] -- stable modules
877 preUpsweep valid_lis all_home_mods stable [] = return stable
878 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
879 = do let scc = flattenSCC scc0
880 scc_allhomeimps :: [ModuleName]
882 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
883 all_imports_in_scc_or_stable
884 = all in_stable_or_scc scc_allhomeimps
886 = map modSummaryName scc
888 = m `elem` scc_names || m `elem` stable
890 -- now we check for valid linkables: each module in the SCC must
891 -- have a valid linkable (see getValidLinkables above).
892 has_valid_linkable new_summary
893 = isJust (findModuleLinkable_maybe valid_lis modname)
894 where modname = modSummaryName new_summary
896 scc_is_stable = all_imports_in_scc_or_stable
897 && all has_valid_linkable scc
900 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
901 else preUpsweep valid_lis all_home_mods stable sccs
904 -- Helper for preUpsweep. Assuming that new_summary's imports are all
905 -- stable (in the sense of preUpsweep), determine if new_summary is itself
906 -- stable, and, if so, in batch mode, return its linkable.
907 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
908 findInSummaries old_summaries mod_name
909 = [s | s <- old_summaries, modSummaryName s == mod_name]
911 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
912 findModInSummaries old_summaries mod
913 = case [s | s <- old_summaries, ms_mod s == mod] of
917 -- Return (names of) all those in modsDone who are part of a cycle
918 -- as defined by theGraph.
919 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
920 findPartiallyCompletedCycles modsDone theGraph
924 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
925 chew ((CyclicSCC vs):rest)
926 = let names_in_this_cycle = nub (map modSummaryName vs)
928 = nub ([done | done <- modsDone,
929 done `elem` names_in_this_cycle])
930 chewed_rest = chew rest
932 if notNull mods_in_this_cycle
933 && length mods_in_this_cycle < length names_in_this_cycle
934 then mods_in_this_cycle ++ chewed_rest
938 data CmThreaded -- stuff threaded through individual module compilations
939 = CmThreaded PersistentCompilerState HomePackageTable
942 -- Compile multiple modules, stopping as soon as an error appears.
943 -- There better had not be any cyclic groups here -- we check for them.
944 upsweep_mods :: GhciMode
946 -> [Linkable] -- Valid linkables
947 -> (ModuleName -> [ModuleName]) -- to construct downward closures
948 -> CmThreaded -- PCS & HPT
949 -> IO () -- how to clean up unwanted tmp files
950 -> [SCC ModSummary] -- mods to do (the worklist)
951 -- ...... RETURNING ......
953 CmThreaded, -- Includes linkables
954 [ModSummary]) -- Mods which succeeded
956 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
958 = return (Succeeded, threaded, [])
960 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
962 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
963 unwords (map (moduleNameUserString.modSummaryName) ms))
964 return (Failed, threaded, [])
966 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
967 ((AcyclicSCC mod):mods)
968 = do --case threaded of
969 -- CmThreaded pcsz hptz
970 -- -> putStrLn ("UPSWEEP_MOD: hpt = " ++
971 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM hptz)))
973 (ok_flag, threaded1) <- upsweep_mod ghci_mode dflags oldUI threaded mod
974 (reachable_from (modSummaryName mod))
976 cleanup -- Remove unwanted tmp files between compilations
978 if failed ok_flag then
979 return (Failed, threaded1, [])
981 (restOK, threaded2, modOKs)
982 <- upsweep_mods ghci_mode dflags oldUI reachable_from
983 threaded1 cleanup mods
984 return (restOK, threaded2, mod:modOKs)
987 -- Compile a single module. Always produce a Linkable for it if
988 -- successful. If no compilation happened, return the old Linkable.
989 upsweep_mod :: GhciMode
995 -> IO (SuccessFlag, CmThreaded)
997 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
999 let this_mod = ms_mod summary1
1000 location = ms_location summary1
1001 mod_name = moduleName this_mod
1003 let (CmThreaded pcs1 hpt1) = threaded1
1004 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
1005 Just mod_info -> Just (hm_iface mod_info)
1008 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1009 source_unchanged = isJust maybe_old_linkable
1011 reachable_only = filter (/= mod_name) reachable_inc_me
1013 -- In interactive mode, all home modules below us *must* have an
1014 -- interface in the HPT. We never demand-load home interfaces in
1015 -- interactive mode.
1017 = ASSERT(ghci_mode == Batch || all (`elemUFM` hpt1) reachable_only)
1018 retainInTopLevelEnvs reachable_only hpt1
1020 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1023 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1026 compresult <- compile ghci_mode this_mod location source_unchanged
1027 have_object mb_old_iface hpt1_strictDC pcs1
1031 -- Compilation "succeeded", and may or may not have returned a new
1032 -- linkable (depending on whether compilation was actually performed
1034 CompOK pcs2 new_details new_iface maybe_new_linkable
1036 new_linkable = maybe_new_linkable `orElse` old_linkable
1037 new_info = HomeModInfo { hm_iface = new_iface,
1038 hm_details = new_details,
1039 hm_linkable = new_linkable }
1040 hpt2 = extendModuleEnv hpt1 this_mod new_info
1042 return (Succeeded, CmThreaded pcs2 hpt2)
1044 -- Compilation failed. Compile may still have updated the PCS, tho.
1045 CompErrs pcs2 -> return (Failed, CmThreaded pcs2 hpt1)
1047 -- Filter modules in the HPT
1048 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1049 retainInTopLevelEnvs keep_these hpt
1050 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
1052 maybeLookupUFM ufm u = case lookupUFM ufm u of
1054 Just val -> [(u, val)]
1056 -- Needed to clean up HPT so that we don't get duplicates in inst env
1057 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1058 downwards_closure_of_module summaries root
1059 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1060 toEdge summ = (modSummaryName summ,
1061 filter (`elem` all_mods) (ms_allimps summ))
1063 all_mods = map modSummaryName summaries
1065 res = simple_transitive_closure (map toEdge summaries) [root]
1067 -- trace (showSDoc (text "DC of mod" <+> ppr root
1068 -- <+> text "=" <+> ppr res)) $
1071 -- Calculate transitive closures from a set of roots given an adjacency list
1072 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1073 simple_transitive_closure graph set
1074 = let set2 = nub (concatMap dsts set ++ set)
1075 dsts node = fromMaybe [] (lookup node graph)
1077 if length set == length set2
1079 else simple_transitive_closure graph set2
1082 -- Calculate SCCs of the module graph, with or without taking into
1083 -- account source imports.
1084 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1085 topological_sort include_source_imports summaries
1087 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1089 = (summ, modSummaryName summ,
1090 (if include_source_imports
1091 then ms_srcimps summ else []) ++ ms_imps summ)
1093 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1094 mash_edge (summ, m, m_imports)
1095 = case lookup m key_map of
1096 Nothing -> panic "reverse_topological_sort"
1097 Just mk -> (summ, mk,
1098 -- ignore imports not from the home package
1099 catMaybes (map (flip lookup key_map) m_imports))
1101 edges = map toEdge summaries
1102 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1103 scc_input = map mash_edge edges
1104 sccs = stronglyConnComp scc_input
1109 -----------------------------------------------------------------------------
1110 -- Downsweep (dependency analysis)
1112 -- Chase downwards from the specified root set, returning summaries
1113 -- for all home modules encountered. Only follow source-import
1116 -- We pass in the previous collection of summaries, which is used as a
1117 -- cache to avoid recalculating a module summary if the source is
1120 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1121 downsweep roots old_summaries
1122 = do rootSummaries <- mapM getRootSummary roots
1123 checkDuplicates rootSummaries
1125 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1126 (ms_imps m)) rootSummaries))
1127 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1128 let mod = ms_mod s, isHomeModule mod
1130 return all_summaries
1132 getRootSummary :: FilePath -> IO ModSummary
1134 | haskellish_src_file file
1135 = do exists <- doesFileExist file
1136 if exists then summariseFile file else do
1137 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1139 = do exists <- doesFileExist hs_file
1140 if exists then summariseFile hs_file else do
1141 exists <- doesFileExist lhs_file
1142 if exists then summariseFile lhs_file else do
1143 let mod_name = mkModuleName file
1144 maybe_summary <- getSummary (file, mod_name)
1145 case maybe_summary of
1146 Nothing -> packageModErr mod_name
1149 hs_file = file ++ ".hs"
1150 lhs_file = file ++ ".lhs"
1152 -- In a root module, the filename is allowed to diverge from the module
1153 -- name, so we have to check that there aren't multiple root files
1154 -- defining the same module (otherwise the duplicates will be silently
1155 -- ignored, leading to confusing behaviour).
1156 checkDuplicates :: [ModSummary] -> IO ()
1157 checkDuplicates summaries = mapM_ check summaries
1162 many -> multiRootsErr modl many
1163 where modl = ms_mod summ
1165 [ fromJust (ml_hs_file (ms_location summ'))
1166 | summ' <- summaries, ms_mod summ' == modl ]
1168 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1169 getSummary (currentMod,nm)
1170 = do found <- findModule nm
1172 Right (mod, location) -> do
1173 let old_summary = findModInSummaries old_summaries mod
1174 summarise mod location old_summary
1177 dflags <- getDynFlags
1178 throwDyn (noModError dflags currentMod nm files)
1180 -- loop invariant: env doesn't contain package modules
1181 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1182 loop [] env = return (moduleEnvElts env)
1184 = do -- imports for modules we don't already have
1185 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1188 needed_summaries <- mapM getSummary needed_imps
1190 -- get just the "home" modules
1191 let new_home_summaries = [ s | Just s <- needed_summaries ]
1193 -- loop, checking the new imports
1194 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1195 (ms_imps m)) new_home_summaries)
1196 loop new_imps (extendModuleEnvList env
1197 [ (ms_mod s, s) | s <- new_home_summaries ])
1199 -- ToDo: we don't have a proper line number for this error
1200 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1201 hang (text loc <> colon) 4 $
1202 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1206 | verbosity dflags < 3 =
1207 text "(use -v to see a list of the files searched for)"
1209 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1211 -----------------------------------------------------------------------------
1212 -- Summarising modules
1214 -- We have two types of summarisation:
1216 -- * Summarise a file. This is used for the root module(s) passed to
1217 -- cmLoadModules. The file is read, and used to determine the root
1218 -- module name. The module name may differ from the filename.
1220 -- * Summarise a module. We are given a module name, and must provide
1221 -- a summary. The finder is used to locate the file in which the module
1224 summariseFile :: FilePath -> IO ModSummary
1226 = do hspp_fn <- preprocess file
1227 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1229 let (path, basename, ext) = splitFilename3 file
1230 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1231 the_imps = filter (/= gHC_PRIM_Name) imps
1233 (mod, location) <- mkHomeModLocation mod_name True{-is a root-}
1237 <- case ml_hs_file location of
1238 Nothing -> noHsFileErr mod_name
1239 Just src_fn -> getModificationTime src_fn
1241 return (ModSummary { ms_mod = mod,
1242 ms_location = location{ml_hspp_file=Just hspp_fn},
1243 ms_srcimps = srcimps, ms_imps = the_imps,
1244 ms_hs_date = src_timestamp })
1246 -- Summarise a module, and pick up source and timestamp.
1247 summarise :: Module -> ModLocation -> Maybe ModSummary
1248 -> IO (Maybe ModSummary)
1249 summarise mod location old_summary
1250 | not (isHomeModule mod) = return Nothing
1252 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1254 case ml_hs_file location of {
1255 Nothing -> noHsFileErr mod;
1258 src_timestamp <- getModificationTime src_fn
1260 -- return the cached summary if the source didn't change
1261 case old_summary of {
1262 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1265 hspp_fn <- preprocess hs_fn
1266 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1268 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1269 the_imps = filter (/= gHC_PRIM_Name) imps
1271 when (mod_name /= moduleName mod) $
1272 throwDyn (ProgramError
1273 (showSDoc (text hs_fn
1274 <> text ": file name does not match module name"
1275 <+> quotes (ppr (moduleName mod)))))
1277 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1278 srcimps the_imps src_timestamp))
1284 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1287 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1288 quotes (ppr mod) <+>
1289 text "is a package module")))
1291 multiRootsErr mod files
1292 = throwDyn (ProgramError (showSDoc (
1293 text "module" <+> quotes (ppr mod) <+>
1294 text "is defined in multiple files:" <+>
1295 sep (map text files))))
1299 %************************************************************************
1303 %************************************************************************
1306 -- The ModLocation contains both the original source filename and the
1307 -- filename of the cleaned-up source file after all preprocessing has been
1308 -- done. The point is that the summariser will have to cpp/unlit/whatever
1309 -- all files anyway, and there's no point in doing this twice -- just
1310 -- park the result in a temp file, put the name of it in the location,
1311 -- and let @compile@ read from that file on the way back up.
1314 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1316 emptyMG :: ModuleGraph
1321 ms_mod :: Module, -- name, package
1322 ms_location :: ModLocation, -- location
1323 ms_srcimps :: [ModuleName], -- source imports
1324 ms_imps :: [ModuleName], -- non-source imports
1325 ms_hs_date :: ClockTime -- timestamp of summarised file
1328 instance Outputable ModSummary where
1330 = sep [text "ModSummary {",
1331 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1332 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1333 text "ms_imps =" <+> ppr (ms_imps ms),
1334 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1338 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1340 modSummaryName :: ModSummary -> ModuleName
1341 modSummaryName = moduleName . ms_mod