2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
8 ModuleGraph, ModSummary(..),
12 cmInit, -- :: GhciMode -> DynFlags -> IO CmState
14 cmDepAnal, -- :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
16 cmLoadModules, -- :: CmState -> DynFlags -> ModuleGraph
17 -- -> IO (CmState, Bool, [String])
19 cmUnload, -- :: CmState -> DynFlags -> IO CmState
22 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
24 cmSetContext, -- :: CmState -> DynFlags -> [String] -> [String] -> IO CmState
25 cmGetContext, -- :: CmState -> IO ([String],[String])
27 cmInfoThing, -- :: CmState -> String -> IO (CmState, [(TyThing,Fixity)])
28 cmBrowseModule, -- :: CmState -> IO [TyThing]
31 cmRunStmt, -- :: CmState -> DynFlags -> String
32 -- -> IO (CmState, CmRunResult)
34 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
35 -- -> IO (CmState, Maybe String)
37 cmKindOfType, -- :: 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)
49 cmGetBindings, -- :: CmState -> [TyThing]
50 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
55 #include "HsVersions.h"
57 import DriverPipeline ( CompResult(..), preprocess, compile, link )
58 import HscMain ( newHscEnv )
59 import DriverState ( v_Output_file, v_NoHsMain, v_MainModIs )
63 import PrelNames ( gHC_PRIM_Name )
64 import Module ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
65 ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
66 extendModuleEnvList, extendModuleEnv,
71 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
72 import ErrUtils ( showPass )
73 import SysTools ( cleanTempFilesExcept )
74 import BasicTypes ( SuccessFlag(..), succeeded, failed )
78 import CmdLineOpts ( DynFlags(..), getDynFlags )
79 import Maybes ( expectJust, orElse, mapCatMaybes )
81 import DATA_IOREF ( readIORef )
84 import HscMain ( hscThing, hscStmt, hscTcExpr, hscKcType )
85 import TcRnDriver ( mkExportEnv, getModuleContents )
86 import IfaceSyn ( IfaceDecl )
87 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
91 import Type ( tidyType )
92 import VarEnv ( emptyTidyEnv )
93 import BasicTypes ( Fixity )
94 import Linker ( HValue, unload, extendLinkEnv )
95 import GHC.Exts ( unsafeCoerce# )
97 import SrcLoc ( SrcLoc )
98 import Control.Exception as Exception ( Exception, try )
101 import EXCEPTION ( throwDyn )
104 import Directory ( getModificationTime, doesFileExist )
109 import Time ( ClockTime )
114 -- Persistent state for the entire system
117 cm_hsc :: HscEnv, -- Includes the home-package table
118 cm_mg :: ModuleGraph, -- The module graph
119 cm_ic :: InteractiveContext -- Command-line binding info
123 cmGetModInfo cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
124 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
125 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
126 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
129 cmInit :: GhciMode -> DynFlags -> IO CmState
130 cmInit ghci_mode dflags
131 = do { hsc_env <- newHscEnv ghci_mode dflags
132 ; return (CmState { cm_hsc = hsc_env,
134 cm_ic = emptyInteractiveContext })}
136 discardCMInfo :: CmState -> CmState
137 -- Forget the compilation manager's state, including the home package table
138 -- but retain the persistent info in HscEnv
139 discardCMInfo cm_state
140 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
141 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
143 -------------------------------------------------------------------
144 -- The unlinked image
146 -- The compilation manager keeps a list of compiled, but as-yet unlinked
147 -- binaries (byte code or object code). Even when it links bytecode
148 -- it keeps the unlinked version so it can re-link it later without
151 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
153 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
154 findModuleLinkable_maybe lis mod
155 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
158 many -> pprPanic "findModuleLinkable" (ppr mod)
162 %************************************************************************
166 %************************************************************************
170 -----------------------------------------------------------------------------
171 -- Setting the context doesn't throw away any bindings; the bindings
172 -- we've built up in the InteractiveContext simply move to the new
173 -- module. They always shadow anything in scope in the current context.
177 -> [String] -- take the top-level scopes of these modules
178 -> [String] -- and the just the exports from these
180 cmSetContext cmstate toplevs exports = do
181 let old_ic = cm_ic cmstate
182 hsc_env = cm_hsc cmstate
183 hpt = hsc_HPT hsc_env
185 export_env <- mkExportEnv hsc_env (map mkModuleName exports)
186 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
188 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
189 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
190 ic_exports = exports,
191 ic_rn_gbl_env = all_env } }
193 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
195 = case lookupModuleEnvByName hpt (mkModuleName mod) of
196 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
197 Just details -> case hm_globals details of
198 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
199 Just env -> return env
201 cmGetContext :: CmState -> IO ([String],[String])
202 cmGetContext CmState{cm_ic=ic} =
203 return (ic_toplev_scope ic, ic_exports ic)
205 cmModuleIsInterpreted :: CmState -> String -> IO Bool
206 cmModuleIsInterpreted cmstate str
207 = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
208 Just details -> return (isJust (hm_globals details))
209 _not_a_home_module -> return False
211 -----------------------------------------------------------------------------
212 cmSetDFlags :: CmState -> DynFlags -> CmState
213 cmSetDFlags cm_state dflags
214 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
216 -----------------------------------------------------------------------------
217 -- cmInfoThing: convert a String to a TyThing
219 -- A string may refer to more than one TyThing (eg. a constructor,
220 -- and type constructor), so we return a list of all the possible TyThings.
222 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity,SrcLoc)]
223 cmInfoThing cmstate id
224 = hscThing (cm_hsc cmstate) (cm_ic cmstate) id
226 -- ---------------------------------------------------------------------------
227 -- cmBrowseModule: get all the TyThings defined in a module
229 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
230 cmBrowseModule cmstate str exports_only
231 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
232 (mkModuleName str) exports_only
234 Nothing -> return [] -- An error of some kind
239 -----------------------------------------------------------------------------
240 -- cmRunStmt: Run a statement/expr.
243 = CmRunOk [Name] -- names bound by this evaluation
245 | CmRunException Exception -- statement raised an exception
247 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
248 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
250 maybe_stuff <- hscStmt hsc_env icontext expr
253 Nothing -> return (cmstate, CmRunFailed)
254 Just (new_ic, names, hval) -> do
256 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
257 either_hvals <- sandboxIO thing_to_run
261 -- on error, keep the *old* interactive context,
262 -- so that 'it' is not bound to something
263 -- that doesn't exist.
264 return ( cmstate, CmRunException e )
267 -- Get the newly bound things, and bind them.
268 -- Don't need to delete any shadowed bindings;
269 -- the new ones override the old ones.
270 extendLinkEnv (zip names hvals)
272 return (cmstate{ cm_ic=new_ic },
276 -- We run the statement in a "sandbox" to protect the rest of the
277 -- system from anything the expression might do. For now, this
278 -- consists of just wrapping it in an exception handler, but see below
279 -- for another version.
281 sandboxIO :: IO a -> IO (Either Exception a)
282 sandboxIO thing = Exception.try thing
285 -- This version of sandboxIO runs the expression in a completely new
286 -- RTS main thread. It is disabled for now because ^C exceptions
287 -- won't be delivered to the new thread, instead they'll be delivered
288 -- to the (blocked) GHCi main thread.
290 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
292 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
294 st_thing <- newStablePtr (Exception.try thing)
295 alloca $ \ p_st_result -> do
296 stat <- rts_evalStableIO st_thing p_st_result
297 freeStablePtr st_thing
299 then do st_result <- peek p_st_result
300 result <- deRefStablePtr st_result
301 freeStablePtr st_result
302 return (Right result)
304 return (Left (fromIntegral stat))
306 foreign import "rts_evalStableIO" {- safe -}
307 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
308 -- more informative than the C type!
311 -----------------------------------------------------------------------------
312 -- cmTypeOfExpr: returns a string representing the type of an expression
314 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
315 cmTypeOfExpr cmstate expr
316 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
319 Nothing -> return Nothing
320 Just ty -> return (Just res_str)
322 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
323 unqual = icPrintUnqual (cm_ic cmstate)
324 tidy_ty = tidyType emptyTidyEnv ty
327 -----------------------------------------------------------------------------
328 -- cmKindOfType: returns a string representing the kind of a type
330 cmKindOfType :: CmState -> String -> IO (Maybe String)
331 cmKindOfType cmstate str
332 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
334 Nothing -> return Nothing
335 Just kind -> return (Just res_str)
337 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
338 unqual = icPrintUnqual (cm_ic cmstate)
340 -----------------------------------------------------------------------------
341 -- cmTypeOfName: returns a string representing the type of a name.
343 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
344 cmTypeOfName CmState{ cm_ic=ic } name
346 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
347 case lookupNameEnv (ic_type_env ic) name of
348 Nothing -> return Nothing
349 Just (AnId id) -> return (Just str)
351 unqual = icPrintUnqual ic
352 ty = tidyType emptyTidyEnv (idType id)
353 str = showSDocForUser unqual (ppr ty)
355 _ -> panic "cmTypeOfName"
357 -----------------------------------------------------------------------------
358 -- cmCompileExpr: compile an expression and deliver an HValue
360 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
361 cmCompileExpr cmstate expr
364 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
365 ("let __cmCompileExpr = "++expr)
368 Nothing -> return Nothing
369 Just (new_ic, names, hval) -> do
372 hvals <- (unsafeCoerce# hval) :: IO [HValue]
374 case (names,hvals) of
375 ([n],[hv]) -> return (Just hv)
376 _ -> panic "cmCompileExpr"
382 %************************************************************************
384 Loading and unloading
386 %************************************************************************
389 -----------------------------------------------------------------------------
390 -- Unload the compilation manager's state: everything it knows about the
391 -- current collection of modules in the Home package.
393 cmUnload :: CmState -> IO CmState
394 cmUnload state@CmState{ cm_hsc = hsc_env }
395 = do -- Throw away the old home dir cache
398 -- Unload everything the linker knows about
401 -- Start with a fresh CmState, but keep the PersistentCompilerState
402 return (discardCMInfo state)
404 cm_unload hsc_env linkables
405 = case hsc_mode hsc_env of
408 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
410 Interactive -> panic "unload: no interpreter"
414 -----------------------------------------------------------------------------
415 -- Trace dependency graph
417 -- This is a seperate pass so that the caller can back off and keep
418 -- the current state if the downsweep fails. Typically the caller
419 -- might go cmDepAnal
422 -- He wants to do the dependency analysis before the unload, so that
423 -- if the former fails he can use the later
425 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
426 cmDepAnal cmstate rootnames
427 = do showPass dflags "Chasing dependencies"
428 when (verbosity dflags >= 1 && gmode == Batch) $
429 hPutStrLn stderr (showSDoc (hcat [
430 text "Chasing modules from: ",
431 hcat (punctuate comma (map text rootnames))]))
432 downsweep rootnames (cm_mg cmstate)
434 hsc_env = cm_hsc cmstate
435 dflags = hsc_dflags hsc_env
436 gmode = hsc_mode hsc_env
438 -----------------------------------------------------------------------------
439 -- The real business of the compilation manager: given a system state and
440 -- a module name, try and bring the module up to date, probably changing
441 -- the system state at the same time.
443 cmLoadModules :: CmState -- The HPT may not be as up to date
444 -> ModuleGraph -- Bang up to date
445 -> IO (CmState, -- new state
446 SuccessFlag, -- was successful
447 [String]) -- list of modules loaded
449 cmLoadModules cmstate1 mg2unsorted
450 = do -- version 1's are the original, before downsweep
451 let hsc_env = cm_hsc cmstate1
452 let hpt1 = hsc_HPT hsc_env
453 let ghci_mode = hsc_mode hsc_env -- this never changes
454 let dflags = hsc_dflags hsc_env -- this never changes
456 -- Do the downsweep to reestablish the module graph
457 let verb = verbosity dflags
459 -- Find out if we have a Main module
460 mb_main_mod <- readIORef v_MainModIs
462 main_mod = mb_main_mod `orElse` "Main"
464 = any ((==main_mod).moduleNameUserString.modSummaryName)
467 let mg2unsorted_names = map modSummaryName mg2unsorted
469 -- reachable_from follows source as well as normal imports
470 let reachable_from :: ModuleName -> [ModuleName]
471 reachable_from = downwards_closure_of_module mg2unsorted
473 -- should be cycle free; ignores 'import source's
474 let mg2 = topological_sort False mg2unsorted
475 -- ... whereas this takes them into account. Used for
476 -- backing out partially complete cycles following a failed
477 -- upsweep, and for removing from hpt all the modules
478 -- not in strict downwards closure, during calls to compile.
479 let mg2_with_srcimps = topological_sort True mg2unsorted
481 -- Sort out which linkables we wish to keep in the unlinked image.
482 -- See getValidLinkables below for details.
483 (valid_old_linkables, new_linkables)
484 <- getValidLinkables ghci_mode (hptLinkables hpt1)
485 mg2unsorted_names mg2_with_srcimps
487 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
489 -- Uniq of ModuleName is the same as Module, fortunately...
490 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
491 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
493 -- When (verb >= 2) $
494 -- putStrLn (showSDoc (text "Valid linkables:"
495 -- <+> ppr valid_linkables))
497 -- Figure out a stable set of modules which can be retained
498 -- the top level envs, to avoid upsweeping them. Goes to a
499 -- bit of trouble to avoid upsweeping module cycles.
501 -- Construct a set S of stable modules like this:
502 -- Travel upwards, over the sccified graph. For each scc
503 -- of modules ms, add ms to S only if:
504 -- 1. All home imports of ms are either in ms or S
505 -- 2. A valid old linkable exists for each module in ms
507 stable_mods <- preUpsweep valid_old_linkables
508 mg2unsorted_names [] mg2_with_srcimps
511 = concatMap (findInSummaries mg2unsorted) stable_mods
514 = filter (\m -> linkableModName m `elem` stable_mods)
518 hPutStrLn stderr (showSDoc (text "Stable modules:"
519 <+> sep (map (text.moduleNameUserString) stable_mods)))
521 -- Unload any modules which are going to be re-linked this
523 cm_unload hsc_env2 stable_linkables
525 -- we can now glom together our linkable sets
526 let valid_linkables = valid_old_linkables ++ new_linkables
528 -- We could at this point detect cycles which aren't broken by
529 -- a source-import, and complain immediately, but it seems better
530 -- to let upsweep_mods do this, so at least some useful work gets
531 -- done before the upsweep is abandoned.
533 = filter (\scc -> any (`notElem` stable_mods)
534 (map modSummaryName (flattenSCC scc)))
537 --hPutStrLn stderr "after tsort:\n"
538 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
540 -- Because we don't take into account source imports when doing
541 -- the topological sort, there shouldn't be any cycles in mg2.
542 -- If there is, we complain and give up -- the user needs to
543 -- break the cycle using a boot file.
545 -- Now do the upsweep, calling compile for each module in
546 -- turn. Final result is version 3 of everything.
548 -- clean up between compilations
549 let cleanup = cleanTempFilesExcept verb
550 (ppFilesFromSummaries (flattenSCCs mg2))
552 (upsweep_ok, hsc_env3, modsUpswept)
553 <- upsweep_mods hsc_env2 valid_linkables reachable_from
554 cleanup upsweep_these
556 -- At this point, modsUpswept and newLis should have the same
557 -- length, so there is one new (or old) linkable for each
558 -- mod which was processed (passed to compile).
560 -- Make modsDone be the summaries for each home module now
561 -- available; this should equal the domain of hpt3.
562 -- (NOT STRICTLY TRUE if an interactive session was started
563 -- with some object on disk ???)
564 -- Get in in a roughly top .. bottom order (hence reverse).
566 let modsDone = reverse modsUpswept ++ stable_summaries
568 -- Try and do linking in some form, depending on whether the
569 -- upsweep was completely or only partially successful.
571 if succeeded upsweep_ok
574 -- Easy; just relink it all.
575 do when (verb >= 2) $
576 hPutStrLn stderr "Upsweep completely successful."
578 -- clean up after ourselves
579 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
581 ofile <- readIORef v_Output_file
582 no_hs_main <- readIORef v_NoHsMain
584 -- Issue a warning for the confusing case where the user
585 -- said '-o foo' but we're not going to do any linking.
586 -- We attempt linking if either (a) one of the modules is
587 -- called Main, or (b) the user said -no-hs-main, indicating
588 -- that main() is going to come from somewhere else.
590 let do_linking = a_root_is_Main || no_hs_main
591 when (ghci_mode == Batch && isJust ofile && not do_linking
593 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
595 -- link everything together
596 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
598 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
599 cmLoadFinish Succeeded linkresult cmstate3
602 -- Tricky. We need to back out the effects of compiling any
603 -- half-done cycles, both so as to clean up the top level envs
604 -- and to avoid telling the interactive linker to link them.
605 do when (verb >= 2) $
606 hPutStrLn stderr "Upsweep partially successful."
609 = map modSummaryName modsDone
610 let mods_to_zap_names
611 = findPartiallyCompletedCycles modsDone_names
614 = filter ((`notElem` mods_to_zap_names).modSummaryName)
617 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
620 -- Clean up after ourselves
621 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
623 -- Link everything together
624 linkresult <- link ghci_mode dflags False hpt4
626 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
627 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
628 cmLoadFinish Failed linkresult cmstate3
631 -- Finish up after a cmLoad.
633 -- If the link failed, unload everything and return.
634 cmLoadFinish ok Failed cmstate
635 = do cm_unload (cm_hsc cmstate) []
636 return (discardCMInfo cmstate, Failed, [])
638 -- Empty the interactive context and set the module context to the topmost
639 -- newly loaded module, or the Prelude if none were loaded.
640 cmLoadFinish ok Succeeded cmstate
641 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
642 mods_loaded = map (moduleNameUserString.modSummaryName)
645 return (new_cmstate, ok, mods_loaded)
647 -- used to fish out the preprocess output files for the purposes of
648 -- cleaning up. The preprocessed file *might* be the same as the
649 -- source file, but that doesn't do any harm.
650 ppFilesFromSummaries summaries
651 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
653 -----------------------------------------------------------------------------
656 -- For each module (or SCC of modules), we take:
658 -- - an on-disk linkable, if this is the first time around and one
661 -- - the old linkable, otherwise (and if one is available).
663 -- and we throw away the linkable if it is older than the source file.
664 -- In interactive mode, we also ignore the on-disk linkables unless
665 -- all of the dependents of this SCC also have on-disk linkables (we
666 -- can't have dynamically loaded objects that depend on interpreted
669 -- If a module has a valid linkable, then it may be STABLE (see below),
670 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
673 -- ToDo: this pass could be merged with the preUpsweep.
677 -> [Linkable] -- old linkables
678 -> [ModuleName] -- all home modules
679 -> [SCC ModSummary] -- all modules in the program, dependency order
680 -> IO ( [Linkable], -- still-valid linkables
681 [Linkable] -- new linkables we just found
684 getValidLinkables mode old_linkables all_home_mods module_graph = do
685 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
687 return (partition_it ls [] [])
689 partition_it [] valid new = (valid,new)
690 partition_it ((l,b):ls) valid new
691 | b = partition_it ls valid (l:new)
692 | otherwise = partition_it ls (l:valid) new
695 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
697 scc = flattenSCC scc0
698 scc_names = map modSummaryName scc
699 home_module m = m `elem` all_home_mods && m `notElem` scc_names
700 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
701 -- NB. ms_imps, not ms_allimps above. We don't want to
702 -- force a module's SOURCE imports to be already compiled for
703 -- its object linkable to be valid.
706 case findModuleLinkable_maybe (map fst new_linkables) m of
708 Just l -> isObjectLinkable l
710 objects_allowed = mode == Batch || all has_object scc_allhomeimps
714 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
716 -- since an scc can contain only all objects or no objects at all,
717 -- we have to check whether we got all objects or not, and re-do
718 -- the linkable check if not.
721 && not (all isObjectLinkable (map fst new_linkables'))
722 then foldM (getValidLinkable old_linkables False) [] scc
723 else return new_linkables'
725 return (new_linkables ++ new_linkables')
728 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
729 -> IO [(Linkable,Bool)]
730 -- True <=> linkable is new; i.e. freshly discovered on the disk
731 -- presumably generated 'on the side'
732 -- by a separate GHC run
733 getValidLinkable old_linkables objects_allowed new_linkables summary
734 -- 'objects_allowed' says whether we permit this module to
735 -- have a .o-file linkable. We only permit it if all the
736 -- modules it depends on also have .o files; a .o file can't
737 -- link to a bytecode module
738 = do let mod_name = modSummaryName summary
741 <- if (not objects_allowed)
744 else findLinkable mod_name (ms_location summary)
746 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
749 case (old_linkable, maybe_disk_linkable) of
750 (Nothing, Nothing) -> []
752 -- new object linkable just appeared
753 (Nothing, Just l) -> up_to_date l True
756 | isObjectLinkable l -> []
757 -- object linkable disappeared! In case we need to
758 -- relink the module, disregard the old linkable and
759 -- just interpret the module from now on.
760 | otherwise -> up_to_date l False
761 -- old byte code linkable
764 | not (isObjectLinkable l) -> up_to_date l False
765 -- if the previous linkable was interpreted, then we
766 -- ignore a newly compiled version, because the version
767 -- numbers in the interface file will be out-of-sync with
768 -- our internal ones.
769 | linkableTime l' > linkableTime l -> up_to_date l' True
770 | linkableTime l' == linkableTime l -> up_to_date l False
772 -- on-disk linkable has been replaced by an older one!
773 -- again, disregard the previous one.
776 | linkableTime l < ms_hs_date summary = []
777 | otherwise = [(l,b)]
778 -- why '<' rather than '<=' above? If the filesystem stores
779 -- times to the nearset second, we may occasionally find that
780 -- the object & source have the same modification time,
781 -- especially if the source was automatically generated
782 -- and compiled. Using >= is slightly unsafe, but it matches
785 return (new_linkables' ++ new_linkables)
788 hptLinkables :: HomePackageTable -> [Linkable]
789 -- Get all the linkables from the home package table, one for each module
790 -- Once the HPT is up to date, these are the ones we should link
791 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
794 -----------------------------------------------------------------------------
795 -- Do a pre-upsweep without use of "compile", to establish a
796 -- (downward-closed) set of stable modules for which we won't call compile.
799 -- * has a valid linkable (see getValidLinkables above)
800 -- * depends only on stable modules
801 -- * has an interface in the HPT (interactive mode only)
803 preUpsweep :: [Linkable] -- new valid linkables
804 -> [ModuleName] -- names of all mods encountered in downsweep
805 -> [ModuleName] -- accumulating stable modules
806 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
807 -> IO [ModuleName] -- stable modules
809 preUpsweep valid_lis all_home_mods stable [] = return stable
810 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
811 = do let scc = flattenSCC scc0
812 scc_allhomeimps :: [ModuleName]
814 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
815 all_imports_in_scc_or_stable
816 = all in_stable_or_scc scc_allhomeimps
818 = map modSummaryName scc
820 = m `elem` scc_names || m `elem` stable
822 -- now we check for valid linkables: each module in the SCC must
823 -- have a valid linkable (see getValidLinkables above).
824 has_valid_linkable new_summary
825 = isJust (findModuleLinkable_maybe valid_lis modname)
826 where modname = modSummaryName new_summary
828 scc_is_stable = all_imports_in_scc_or_stable
829 && all has_valid_linkable scc
832 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
833 else preUpsweep valid_lis all_home_mods stable sccs
836 -- Helper for preUpsweep. Assuming that new_summary's imports are all
837 -- stable (in the sense of preUpsweep), determine if new_summary is itself
838 -- stable, and, if so, in batch mode, return its linkable.
839 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
840 findInSummaries old_summaries mod_name
841 = [s | s <- old_summaries, modSummaryName s == mod_name]
843 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
844 findModInSummaries old_summaries mod
845 = case [s | s <- old_summaries, ms_mod s == mod] of
849 -- Return (names of) all those in modsDone who are part of a cycle
850 -- as defined by theGraph.
851 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
852 findPartiallyCompletedCycles modsDone theGraph
856 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
857 chew ((CyclicSCC vs):rest)
858 = let names_in_this_cycle = nub (map modSummaryName vs)
860 = nub ([done | done <- modsDone,
861 done `elem` names_in_this_cycle])
862 chewed_rest = chew rest
864 if notNull mods_in_this_cycle
865 && length mods_in_this_cycle < length names_in_this_cycle
866 then mods_in_this_cycle ++ chewed_rest
870 -- Compile multiple modules, stopping as soon as an error appears.
871 -- There better had not be any cyclic groups here -- we check for them.
872 upsweep_mods :: HscEnv -- Includes up-to-date HPT
873 -> [Linkable] -- Valid linkables
874 -> (ModuleName -> [ModuleName]) -- to construct downward closures
875 -> IO () -- how to clean up unwanted tmp files
876 -> [SCC ModSummary] -- mods to do (the worklist)
877 -- ...... RETURNING ......
879 HscEnv, -- With an updated HPT
880 [ModSummary]) -- Mods which succeeded
882 upsweep_mods hsc_env oldUI reachable_from cleanup
884 = return (Succeeded, hsc_env, [])
886 upsweep_mods hsc_env oldUI reachable_from cleanup
888 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
889 unwords (map (moduleNameUserString.modSummaryName) ms))
890 return (Failed, hsc_env, [])
892 upsweep_mods hsc_env oldUI reachable_from cleanup
893 ((AcyclicSCC mod):mods)
894 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
895 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
897 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
898 (reachable_from (modSummaryName mod))
900 cleanup -- Remove unwanted tmp files between compilations
902 if failed ok_flag then
903 return (Failed, hsc_env1, [])
905 (restOK, hsc_env2, modOKs)
906 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
907 return (restOK, hsc_env2, mod:modOKs)
910 -- Compile a single module. Always produce a Linkable for it if
911 -- successful. If no compilation happened, return the old Linkable.
912 upsweep_mod :: HscEnv
917 HscEnv) -- With updated HPT
919 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
921 let this_mod = ms_mod summary1
922 location = ms_location summary1
923 mod_name = moduleName this_mod
924 hpt1 = hsc_HPT hsc_env
926 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
927 Just mod_info -> Just (hm_iface mod_info)
930 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
931 source_unchanged = isJust maybe_old_linkable
933 reachable_only = filter (/= mod_name) reachable_inc_me
935 -- In interactive mode, all home modules below us *must* have an
936 -- interface in the HPT. We never demand-load home interfaces in
939 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
940 retainInTopLevelEnvs reachable_only hpt1
941 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
943 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
946 | Just l <- maybe_old_linkable, isObjectLinkable l = True
949 compresult <- compile hsc_env_strictDC this_mod location
950 (ms_hs_date summary1)
951 source_unchanged have_object mb_old_iface
955 -- Compilation "succeeded", and may or may not have returned a new
956 -- linkable (depending on whether compilation was actually performed
958 CompOK new_details new_globals new_iface maybe_new_linkable
960 new_linkable = maybe_new_linkable `orElse` old_linkable
961 new_info = HomeModInfo { hm_iface = new_iface,
962 hm_globals = new_globals,
963 hm_details = new_details,
964 hm_linkable = new_linkable }
965 hpt2 = extendModuleEnv hpt1 this_mod new_info
967 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
969 -- Compilation failed. Compile may still have updated the PCS, tho.
970 CompErrs -> return (Failed, hsc_env)
972 -- Filter modules in the HPT
973 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
974 retainInTopLevelEnvs keep_these hpt
975 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
977 maybeLookupUFM ufm u = case lookupUFM ufm u of
979 Just val -> [(u, val)]
981 -- Needed to clean up HPT so that we don't get duplicates in inst env
982 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
983 downwards_closure_of_module summaries root
984 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
985 toEdge summ = (modSummaryName summ,
986 filter (`elem` all_mods) (ms_allimps summ))
988 all_mods = map modSummaryName summaries
990 res = simple_transitive_closure (map toEdge summaries) [root]
992 -- trace (showSDoc (text "DC of mod" <+> ppr root
993 -- <+> text "=" <+> ppr res)) $
996 -- Calculate transitive closures from a set of roots given an adjacency list
997 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
998 simple_transitive_closure graph set
999 = let set2 = nub (concatMap dsts set ++ set)
1000 dsts node = fromMaybe [] (lookup node graph)
1002 if length set == length set2
1004 else simple_transitive_closure graph set2
1007 -- Calculate SCCs of the module graph, with or without taking into
1008 -- account source imports.
1009 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1010 topological_sort include_source_imports summaries
1012 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1014 = (summ, modSummaryName summ,
1015 (if include_source_imports
1016 then ms_srcimps summ else []) ++ ms_imps summ)
1018 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1019 mash_edge (summ, m, m_imports)
1020 = case lookup m key_map of
1021 Nothing -> panic "reverse_topological_sort"
1022 Just mk -> (summ, mk,
1023 -- ignore imports not from the home package
1024 mapCatMaybes (flip lookup key_map) m_imports)
1026 edges = map toEdge summaries
1027 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1028 scc_input = map mash_edge edges
1029 sccs = stronglyConnComp scc_input
1034 -----------------------------------------------------------------------------
1035 -- Downsweep (dependency analysis)
1037 -- Chase downwards from the specified root set, returning summaries
1038 -- for all home modules encountered. Only follow source-import
1041 -- We pass in the previous collection of summaries, which is used as a
1042 -- cache to avoid recalculating a module summary if the source is
1045 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1046 downsweep roots old_summaries
1047 = do rootSummaries <- mapM getRootSummary roots
1048 checkDuplicates rootSummaries
1050 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1051 (ms_imps m)) rootSummaries))
1052 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1053 let mod = ms_mod s, isHomeModule mod
1055 return all_summaries
1057 getRootSummary :: FilePath -> IO ModSummary
1059 | isHaskellSrcFilename file
1060 = do exists <- doesFileExist file
1061 if exists then summariseFile file else do
1062 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1064 = do exists <- doesFileExist hs_file
1065 if exists then summariseFile hs_file else do
1066 exists <- doesFileExist lhs_file
1067 if exists then summariseFile lhs_file else do
1068 let mod_name = mkModuleName file
1069 maybe_summary <- getSummary (file, mod_name)
1070 case maybe_summary of
1071 Nothing -> packageModErr mod_name
1074 hs_file = file ++ ".hs"
1075 lhs_file = file ++ ".lhs"
1077 -- In a root module, the filename is allowed to diverge from the module
1078 -- name, so we have to check that there aren't multiple root files
1079 -- defining the same module (otherwise the duplicates will be silently
1080 -- ignored, leading to confusing behaviour).
1081 checkDuplicates :: [ModSummary] -> IO ()
1082 checkDuplicates summaries = mapM_ check summaries
1087 many -> multiRootsErr modl many
1088 where modl = ms_mod summ
1090 [ fromJust (ml_hs_file (ms_location summ'))
1091 | summ' <- summaries, ms_mod summ' == modl ]
1093 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1094 getSummary (currentMod,nm)
1095 = do found <- findModule nm
1097 Right (mod, location) -> do
1098 let old_summary = findModInSummaries old_summaries mod
1099 summarise mod location old_summary
1102 dflags <- getDynFlags
1103 throwDyn (noModError dflags currentMod nm files)
1105 -- loop invariant: env doesn't contain package modules
1106 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1107 loop [] env = return (moduleEnvElts env)
1109 = do -- imports for modules we don't already have
1110 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1113 needed_summaries <- mapM getSummary needed_imps
1115 -- get just the "home" modules
1116 let new_home_summaries = [ s | Just s <- needed_summaries ]
1118 -- loop, checking the new imports
1119 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1120 (ms_imps m)) new_home_summaries)
1121 loop new_imps (extendModuleEnvList env
1122 [ (ms_mod s, s) | s <- new_home_summaries ])
1124 -- ToDo: we don't have a proper line number for this error
1125 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1126 hang (text loc <> colon) 4 $
1127 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1131 | verbosity dflags < 3 =
1132 text "(use -v to see a list of the files searched for)"
1134 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1136 -----------------------------------------------------------------------------
1137 -- Summarising modules
1139 -- We have two types of summarisation:
1141 -- * Summarise a file. This is used for the root module(s) passed to
1142 -- cmLoadModules. The file is read, and used to determine the root
1143 -- module name. The module name may differ from the filename.
1145 -- * Summarise a module. We are given a module name, and must provide
1146 -- a summary. The finder is used to locate the file in which the module
1149 summariseFile :: FilePath -> IO ModSummary
1151 = do hspp_fn <- preprocess file
1152 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1154 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1155 the_imps = filter (/= gHC_PRIM_Name) imps
1157 (mod, location) <- mkHomeModLocation mod_name file
1160 <- case ml_hs_file location of
1161 Nothing -> noHsFileErr mod_name
1162 Just src_fn -> getModificationTime src_fn
1164 return (ModSummary { ms_mod = mod,
1165 ms_location = location{ml_hspp_file=Just hspp_fn},
1166 ms_srcimps = srcimps, ms_imps = the_imps,
1167 ms_hs_date = src_timestamp })
1169 -- Summarise a module, and pick up source and timestamp.
1170 summarise :: Module -> ModLocation -> Maybe ModSummary
1171 -> IO (Maybe ModSummary)
1172 summarise mod location old_summary
1173 | not (isHomeModule mod) = return Nothing
1175 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1177 case ml_hs_file location of {
1178 Nothing -> noHsFileErr mod;
1181 src_timestamp <- getModificationTime src_fn
1183 -- return the cached summary if the source didn't change
1184 case old_summary of {
1185 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1188 hspp_fn <- preprocess hs_fn
1189 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1191 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1192 the_imps = filter (/= gHC_PRIM_Name) imps
1194 when (mod_name /= moduleName mod) $
1195 throwDyn (ProgramError
1196 (showSDoc (text hs_fn
1197 <> text ": file name does not match module name"
1198 <+> quotes (ppr (moduleName mod)))))
1200 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1201 srcimps the_imps src_timestamp))
1207 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1210 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1211 quotes (ppr mod) <+>
1212 text "is a package module")))
1214 multiRootsErr mod files
1215 = throwDyn (ProgramError (showSDoc (
1216 text "module" <+> quotes (ppr mod) <+>
1217 text "is defined in multiple files:" <+>
1218 sep (map text files))))
1222 %************************************************************************
1226 %************************************************************************
1229 -- The ModLocation contains both the original source filename and the
1230 -- filename of the cleaned-up source file after all preprocessing has been
1231 -- done. The point is that the summariser will have to cpp/unlit/whatever
1232 -- all files anyway, and there's no point in doing this twice -- just
1233 -- park the result in a temp file, put the name of it in the location,
1234 -- and let @compile@ read from that file on the way back up.
1237 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1239 emptyMG :: ModuleGraph
1244 ms_mod :: Module, -- name, package
1245 ms_location :: ModLocation, -- location
1246 ms_srcimps :: [ModuleName], -- source imports
1247 ms_imps :: [ModuleName], -- non-source imports
1248 ms_hs_date :: ClockTime -- timestamp of summarised file
1251 instance Outputable ModSummary where
1253 = sep [text "ModSummary {",
1254 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1255 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1256 text "ms_imps =" <+> ppr (ms_imps ms),
1257 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1261 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1263 modSummaryName :: ModSummary -> ModuleName
1264 modSummaryName = moduleName . ms_mod