2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
8 ModuleGraph, ModSummary(..),
12 cmInit, -- :: GhciMode -> IO CmState
14 cmDepAnal, -- :: CmState -> [FilePath] -> IO ModuleGraph
16 cmLoadModules, -- :: CmState -> ModuleGraph
17 -- -> IO (CmState, Bool, [String])
19 cmUnload, -- :: CmState -> IO CmState
22 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
24 cmSetContext, -- :: CmState -> [String] -> [String] -> IO CmState
25 cmGetContext, -- :: CmState -> IO ([String],[String])
27 cmGetInfo, -- :: CmState -> String -> IO (CmState, [(TyThing,Fixity)])
29 cmBrowseModule, -- :: CmState -> IO [TyThing]
32 cmRunStmt, -- :: CmState -> String -> IO (CmState, CmRunResult)
34 cmTypeOfExpr, -- :: CmState -> String -> IO (CmState, Maybe String)
35 cmKindOfType, -- :: CmState -> String -> IO (CmState, Maybe String)
36 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
39 cmCompileExpr, -- :: CmState -> String -> IO (CmState, Maybe HValue)
41 cmGetModInfo, -- :: CmState -> (ModuleGraph, HomePackageTable)
44 cmGetBindings, -- :: CmState -> [TyThing]
45 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
50 #include "HsVersions.h"
52 import DriverPipeline ( CompResult(..), preprocess, compile, link )
53 import HscMain ( newHscEnv )
54 import DriverState ( v_Output_file, v_NoHsMain, v_MainModIs )
58 import PrelNames ( gHC_PRIM_Name )
59 import Module ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
60 ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
61 extendModuleEnvList, extendModuleEnv,
66 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
67 import ErrUtils ( showPass )
68 import SysTools ( cleanTempFilesExcept )
69 import BasicTypes ( SuccessFlag(..), succeeded, failed )
73 import CmdLineOpts ( DynFlags(..), getDynFlags )
74 import Maybes ( expectJust, orElse, mapCatMaybes )
76 import DATA_IOREF ( readIORef )
79 import HscMain ( hscGetInfo, GetInfoResult, hscStmt, hscTcExpr, hscKcType )
80 import TcRnDriver ( mkExportEnv, getModuleContents )
81 import IfaceSyn ( IfaceDecl, IfaceInst )
82 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
86 import Type ( tidyType )
87 import VarEnv ( emptyTidyEnv )
88 import BasicTypes ( Fixity )
89 import Linker ( HValue, unload, extendLinkEnv )
90 import GHC.Exts ( unsafeCoerce# )
92 import SrcLoc ( SrcLoc )
93 import Control.Exception as Exception ( Exception, try )
96 import EXCEPTION ( throwDyn )
99 import Directory ( getModificationTime, doesFileExist )
104 import Time ( ClockTime )
109 -- Persistent state for the entire system
112 cm_hsc :: HscEnv, -- Includes the home-package table
113 cm_mg :: ModuleGraph, -- The module graph
114 cm_ic :: InteractiveContext -- Command-line binding info
118 cmGetModInfo cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
119 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
120 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
121 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
124 cmInit :: GhciMode -> DynFlags -> IO CmState
125 cmInit ghci_mode dflags
126 = do { hsc_env <- newHscEnv ghci_mode dflags
127 ; return (CmState { cm_hsc = hsc_env,
129 cm_ic = emptyInteractiveContext })}
131 discardCMInfo :: CmState -> CmState
132 -- Forget the compilation manager's state, including the home package table
133 -- but retain the persistent info in HscEnv
134 discardCMInfo cm_state
135 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
136 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
138 -------------------------------------------------------------------
139 -- The unlinked image
141 -- The compilation manager keeps a list of compiled, but as-yet unlinked
142 -- binaries (byte code or object code). Even when it links bytecode
143 -- it keeps the unlinked version so it can re-link it later without
146 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
148 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
149 findModuleLinkable_maybe lis mod
150 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
153 many -> pprPanic "findModuleLinkable" (ppr mod)
157 %************************************************************************
161 %************************************************************************
165 -----------------------------------------------------------------------------
166 -- Setting the context doesn't throw away any bindings; the bindings
167 -- we've built up in the InteractiveContext simply move to the new
168 -- module. They always shadow anything in scope in the current context.
172 -> [String] -- take the top-level scopes of these modules
173 -> [String] -- and the just the exports from these
175 cmSetContext cmstate toplevs exports = do
176 let old_ic = cm_ic cmstate
177 hsc_env = cm_hsc cmstate
178 hpt = hsc_HPT hsc_env
180 export_env <- mkExportEnv hsc_env (map mkModuleName exports)
181 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
183 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
184 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
185 ic_exports = exports,
186 ic_rn_gbl_env = all_env } }
188 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
190 = case lookupModuleEnvByName hpt (mkModuleName mod) of
191 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
192 Just details -> case hm_globals details of
193 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
194 Just env -> return env
196 cmGetContext :: CmState -> IO ([String],[String])
197 cmGetContext CmState{cm_ic=ic} =
198 return (ic_toplev_scope ic, ic_exports ic)
200 cmModuleIsInterpreted :: CmState -> String -> IO Bool
201 cmModuleIsInterpreted cmstate str
202 = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
203 Just details -> return (isJust (hm_globals details))
204 _not_a_home_module -> return False
206 -----------------------------------------------------------------------------
207 cmSetDFlags :: CmState -> DynFlags -> CmState
208 cmSetDFlags cm_state dflags
209 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
211 -----------------------------------------------------------------------------
212 -- cmInfoThing: convert a String to a TyThing
214 -- A string may refer to more than one TyThing (eg. a constructor,
215 -- and type constructor), so we return a list of all the possible TyThings.
217 cmGetInfo :: CmState -> String -> IO [GetInfoResult]
218 cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
220 -- ---------------------------------------------------------------------------
221 -- cmBrowseModule: get all the TyThings defined in a module
223 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
224 cmBrowseModule cmstate str exports_only
225 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
226 (mkModuleName str) exports_only
228 Nothing -> return [] -- An error of some kind
233 -----------------------------------------------------------------------------
234 -- cmRunStmt: Run a statement/expr.
237 = CmRunOk [Name] -- names bound by this evaluation
239 | CmRunException Exception -- statement raised an exception
241 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
242 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
244 maybe_stuff <- hscStmt hsc_env icontext expr
247 Nothing -> return (cmstate, CmRunFailed)
248 Just (new_ic, names, hval) -> do
250 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
251 either_hvals <- sandboxIO thing_to_run
255 -- on error, keep the *old* interactive context,
256 -- so that 'it' is not bound to something
257 -- that doesn't exist.
258 return ( cmstate, CmRunException e )
261 -- Get the newly bound things, and bind them.
262 -- Don't need to delete any shadowed bindings;
263 -- the new ones override the old ones.
264 extendLinkEnv (zip names hvals)
266 return (cmstate{ cm_ic=new_ic },
270 -- We run the statement in a "sandbox" to protect the rest of the
271 -- system from anything the expression might do. For now, this
272 -- consists of just wrapping it in an exception handler, but see below
273 -- for another version.
275 sandboxIO :: IO a -> IO (Either Exception a)
276 sandboxIO thing = Exception.try thing
279 -- This version of sandboxIO runs the expression in a completely new
280 -- RTS main thread. It is disabled for now because ^C exceptions
281 -- won't be delivered to the new thread, instead they'll be delivered
282 -- to the (blocked) GHCi main thread.
284 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
286 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
288 st_thing <- newStablePtr (Exception.try thing)
289 alloca $ \ p_st_result -> do
290 stat <- rts_evalStableIO st_thing p_st_result
291 freeStablePtr st_thing
293 then do st_result <- peek p_st_result
294 result <- deRefStablePtr st_result
295 freeStablePtr st_result
296 return (Right result)
298 return (Left (fromIntegral stat))
300 foreign import "rts_evalStableIO" {- safe -}
301 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
302 -- more informative than the C type!
305 -----------------------------------------------------------------------------
306 -- cmTypeOfExpr: returns a string representing the type of an expression
308 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
309 cmTypeOfExpr cmstate expr
310 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
313 Nothing -> return Nothing
314 Just ty -> return (Just res_str)
316 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
317 unqual = icPrintUnqual (cm_ic cmstate)
318 tidy_ty = tidyType emptyTidyEnv ty
321 -----------------------------------------------------------------------------
322 -- cmKindOfType: returns a string representing the kind of a type
324 cmKindOfType :: CmState -> String -> IO (Maybe String)
325 cmKindOfType cmstate str
326 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
328 Nothing -> return Nothing
329 Just kind -> return (Just res_str)
331 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
332 unqual = icPrintUnqual (cm_ic cmstate)
334 -----------------------------------------------------------------------------
335 -- cmTypeOfName: returns a string representing the type of a name.
337 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
338 cmTypeOfName CmState{ cm_ic=ic } name
340 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
341 case lookupNameEnv (ic_type_env ic) name of
342 Nothing -> return Nothing
343 Just (AnId id) -> return (Just str)
345 unqual = icPrintUnqual ic
346 ty = tidyType emptyTidyEnv (idType id)
347 str = showSDocForUser unqual (ppr ty)
349 _ -> panic "cmTypeOfName"
351 -----------------------------------------------------------------------------
352 -- cmCompileExpr: compile an expression and deliver an HValue
354 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
355 cmCompileExpr cmstate expr
358 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
359 ("let __cmCompileExpr = "++expr)
362 Nothing -> return Nothing
363 Just (new_ic, names, hval) -> do
366 hvals <- (unsafeCoerce# hval) :: IO [HValue]
368 case (names,hvals) of
369 ([n],[hv]) -> return (Just hv)
370 _ -> panic "cmCompileExpr"
376 %************************************************************************
378 Loading and unloading
380 %************************************************************************
383 -----------------------------------------------------------------------------
384 -- Unload the compilation manager's state: everything it knows about the
385 -- current collection of modules in the Home package.
387 cmUnload :: CmState -> IO CmState
388 cmUnload state@CmState{ cm_hsc = hsc_env }
389 = do -- Throw away the old home dir cache
392 -- Unload everything the linker knows about
395 -- Start with a fresh CmState, but keep the PersistentCompilerState
396 return (discardCMInfo state)
398 cm_unload hsc_env linkables
399 = case hsc_mode hsc_env of
402 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
404 Interactive -> panic "unload: no interpreter"
408 -----------------------------------------------------------------------------
409 -- Trace dependency graph
411 -- This is a seperate pass so that the caller can back off and keep
412 -- the current state if the downsweep fails. Typically the caller
413 -- might go cmDepAnal
416 -- He wants to do the dependency analysis before the unload, so that
417 -- if the former fails he can use the later
419 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
420 cmDepAnal cmstate rootnames
421 = do showPass dflags "Chasing dependencies"
422 when (verbosity dflags >= 1 && gmode == Batch) $
423 hPutStrLn stderr (showSDoc (hcat [
424 text "Chasing modules from: ",
425 hcat (punctuate comma (map text rootnames))]))
426 downsweep rootnames (cm_mg cmstate)
428 hsc_env = cm_hsc cmstate
429 dflags = hsc_dflags hsc_env
430 gmode = hsc_mode hsc_env
432 -----------------------------------------------------------------------------
433 -- The real business of the compilation manager: given a system state and
434 -- a module name, try and bring the module up to date, probably changing
435 -- the system state at the same time.
437 cmLoadModules :: CmState -- The HPT may not be as up to date
438 -> ModuleGraph -- Bang up to date
439 -> IO (CmState, -- new state
440 SuccessFlag, -- was successful
441 [String]) -- list of modules loaded
443 cmLoadModules cmstate1 mg2unsorted
444 = do -- version 1's are the original, before downsweep
445 let hsc_env = cm_hsc cmstate1
446 let hpt1 = hsc_HPT hsc_env
447 let ghci_mode = hsc_mode hsc_env -- this never changes
448 let dflags = hsc_dflags hsc_env -- this never changes
450 -- Do the downsweep to reestablish the module graph
451 let verb = verbosity dflags
453 -- Find out if we have a Main module
454 mb_main_mod <- readIORef v_MainModIs
456 main_mod = mb_main_mod `orElse` "Main"
458 = any ((==main_mod).moduleNameUserString.modSummaryName)
461 let mg2unsorted_names = map modSummaryName mg2unsorted
463 -- reachable_from follows source as well as normal imports
464 let reachable_from :: ModuleName -> [ModuleName]
465 reachable_from = downwards_closure_of_module mg2unsorted
467 -- should be cycle free; ignores 'import source's
468 let mg2 = topological_sort False mg2unsorted
469 -- ... whereas this takes them into account. Used for
470 -- backing out partially complete cycles following a failed
471 -- upsweep, and for removing from hpt all the modules
472 -- not in strict downwards closure, during calls to compile.
473 let mg2_with_srcimps = topological_sort True mg2unsorted
475 -- Sort out which linkables we wish to keep in the unlinked image.
476 -- See getValidLinkables below for details.
477 (valid_old_linkables, new_linkables)
478 <- getValidLinkables ghci_mode (hptLinkables hpt1)
479 mg2unsorted_names mg2_with_srcimps
481 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
483 -- Uniq of ModuleName is the same as Module, fortunately...
484 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
485 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
487 -- When (verb >= 2) $
488 -- putStrLn (showSDoc (text "Valid linkables:"
489 -- <+> ppr valid_linkables))
491 -- Figure out a stable set of modules which can be retained
492 -- the top level envs, to avoid upsweeping them. Goes to a
493 -- bit of trouble to avoid upsweeping module cycles.
495 -- Construct a set S of stable modules like this:
496 -- Travel upwards, over the sccified graph. For each scc
497 -- of modules ms, add ms to S only if:
498 -- 1. All home imports of ms are either in ms or S
499 -- 2. A valid old linkable exists for each module in ms
501 stable_mods <- preUpsweep valid_old_linkables
502 mg2unsorted_names [] mg2_with_srcimps
505 = concatMap (findInSummaries mg2unsorted) stable_mods
508 = filter (\m -> linkableModName m `elem` stable_mods)
512 hPutStrLn stderr (showSDoc (text "Stable modules:"
513 <+> sep (map (text.moduleNameUserString) stable_mods)))
515 -- Unload any modules which are going to be re-linked this
517 cm_unload hsc_env2 stable_linkables
519 -- we can now glom together our linkable sets
520 let valid_linkables = valid_old_linkables ++ new_linkables
522 -- We could at this point detect cycles which aren't broken by
523 -- a source-import, and complain immediately, but it seems better
524 -- to let upsweep_mods do this, so at least some useful work gets
525 -- done before the upsweep is abandoned.
527 = filter (\scc -> any (`notElem` stable_mods)
528 (map modSummaryName (flattenSCC scc)))
531 --hPutStrLn stderr "after tsort:\n"
532 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
534 -- Because we don't take into account source imports when doing
535 -- the topological sort, there shouldn't be any cycles in mg2.
536 -- If there is, we complain and give up -- the user needs to
537 -- break the cycle using a boot file.
539 -- Now do the upsweep, calling compile for each module in
540 -- turn. Final result is version 3 of everything.
542 -- clean up between compilations
543 let cleanup = cleanTempFilesExcept verb
544 (ppFilesFromSummaries (flattenSCCs mg2))
546 (upsweep_ok, hsc_env3, modsUpswept)
547 <- upsweep_mods hsc_env2 valid_linkables reachable_from
548 cleanup upsweep_these
550 -- At this point, modsUpswept and newLis should have the same
551 -- length, so there is one new (or old) linkable for each
552 -- mod which was processed (passed to compile).
554 -- Make modsDone be the summaries for each home module now
555 -- available; this should equal the domain of hpt3.
556 -- (NOT STRICTLY TRUE if an interactive session was started
557 -- with some object on disk ???)
558 -- Get in in a roughly top .. bottom order (hence reverse).
560 let modsDone = reverse modsUpswept ++ stable_summaries
562 -- Try and do linking in some form, depending on whether the
563 -- upsweep was completely or only partially successful.
565 if succeeded upsweep_ok
568 -- Easy; just relink it all.
569 do when (verb >= 2) $
570 hPutStrLn stderr "Upsweep completely successful."
572 -- clean up after ourselves
573 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
575 ofile <- readIORef v_Output_file
576 no_hs_main <- readIORef v_NoHsMain
578 -- Issue a warning for the confusing case where the user
579 -- said '-o foo' but we're not going to do any linking.
580 -- We attempt linking if either (a) one of the modules is
581 -- called Main, or (b) the user said -no-hs-main, indicating
582 -- that main() is going to come from somewhere else.
584 let do_linking = a_root_is_Main || no_hs_main
585 when (ghci_mode == Batch && isJust ofile && not do_linking
587 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
589 -- link everything together
590 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
592 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
593 cmLoadFinish Succeeded linkresult cmstate3
596 -- Tricky. We need to back out the effects of compiling any
597 -- half-done cycles, both so as to clean up the top level envs
598 -- and to avoid telling the interactive linker to link them.
599 do when (verb >= 2) $
600 hPutStrLn stderr "Upsweep partially successful."
603 = map modSummaryName modsDone
604 let mods_to_zap_names
605 = findPartiallyCompletedCycles modsDone_names
608 = filter ((`notElem` mods_to_zap_names).modSummaryName)
611 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
614 -- Clean up after ourselves
615 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
617 -- Link everything together
618 linkresult <- link ghci_mode dflags False hpt4
620 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
621 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
622 cmLoadFinish Failed linkresult cmstate3
625 -- Finish up after a cmLoad.
627 -- If the link failed, unload everything and return.
628 cmLoadFinish ok Failed cmstate
629 = do cm_unload (cm_hsc cmstate) []
630 return (discardCMInfo cmstate, Failed, [])
632 -- Empty the interactive context and set the module context to the topmost
633 -- newly loaded module, or the Prelude if none were loaded.
634 cmLoadFinish ok Succeeded cmstate
635 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
636 mods_loaded = map (moduleNameUserString.modSummaryName)
639 return (new_cmstate, ok, mods_loaded)
641 -- used to fish out the preprocess output files for the purposes of
642 -- cleaning up. The preprocessed file *might* be the same as the
643 -- source file, but that doesn't do any harm.
644 ppFilesFromSummaries summaries
645 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
647 -----------------------------------------------------------------------------
650 -- For each module (or SCC of modules), we take:
652 -- - an on-disk linkable, if this is the first time around and one
655 -- - the old linkable, otherwise (and if one is available).
657 -- and we throw away the linkable if it is older than the source file.
658 -- In interactive mode, we also ignore the on-disk linkables unless
659 -- all of the dependents of this SCC also have on-disk linkables (we
660 -- can't have dynamically loaded objects that depend on interpreted
663 -- If a module has a valid linkable, then it may be STABLE (see below),
664 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
667 -- ToDo: this pass could be merged with the preUpsweep.
671 -> [Linkable] -- old linkables
672 -> [ModuleName] -- all home modules
673 -> [SCC ModSummary] -- all modules in the program, dependency order
674 -> IO ( [Linkable], -- still-valid linkables
675 [Linkable] -- new linkables we just found
678 getValidLinkables mode old_linkables all_home_mods module_graph = do
679 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
681 return (partition_it ls [] [])
683 partition_it [] valid new = (valid,new)
684 partition_it ((l,b):ls) valid new
685 | b = partition_it ls valid (l:new)
686 | otherwise = partition_it ls (l:valid) new
689 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
691 scc = flattenSCC scc0
692 scc_names = map modSummaryName scc
693 home_module m = m `elem` all_home_mods && m `notElem` scc_names
694 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
695 -- NB. ms_imps, not ms_allimps above. We don't want to
696 -- force a module's SOURCE imports to be already compiled for
697 -- its object linkable to be valid.
700 case findModuleLinkable_maybe (map fst new_linkables) m of
702 Just l -> isObjectLinkable l
704 objects_allowed = mode == Batch || all has_object scc_allhomeimps
708 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
710 -- since an scc can contain only all objects or no objects at all,
711 -- we have to check whether we got all objects or not, and re-do
712 -- the linkable check if not.
715 && not (all isObjectLinkable (map fst new_linkables'))
716 then foldM (getValidLinkable old_linkables False) [] scc
717 else return new_linkables'
719 return (new_linkables ++ new_linkables')
722 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
723 -> IO [(Linkable,Bool)]
724 -- True <=> linkable is new; i.e. freshly discovered on the disk
725 -- presumably generated 'on the side'
726 -- by a separate GHC run
727 getValidLinkable old_linkables objects_allowed new_linkables summary
728 -- 'objects_allowed' says whether we permit this module to
729 -- have a .o-file linkable. We only permit it if all the
730 -- modules it depends on also have .o files; a .o file can't
731 -- link to a bytecode module
732 = do let mod_name = modSummaryName summary
735 <- if (not objects_allowed)
738 else findLinkable mod_name (ms_location summary)
740 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
743 case (old_linkable, maybe_disk_linkable) of
744 (Nothing, Nothing) -> []
746 -- new object linkable just appeared
747 (Nothing, Just l) -> up_to_date l True
750 | isObjectLinkable l -> []
751 -- object linkable disappeared! In case we need to
752 -- relink the module, disregard the old linkable and
753 -- just interpret the module from now on.
754 | otherwise -> up_to_date l False
755 -- old byte code linkable
758 | not (isObjectLinkable l) -> up_to_date l False
759 -- if the previous linkable was interpreted, then we
760 -- ignore a newly compiled version, because the version
761 -- numbers in the interface file will be out-of-sync with
762 -- our internal ones.
763 | linkableTime l' > linkableTime l -> up_to_date l' True
764 | linkableTime l' == linkableTime l -> up_to_date l False
766 -- on-disk linkable has been replaced by an older one!
767 -- again, disregard the previous one.
770 | linkableTime l < ms_hs_date summary = []
771 | otherwise = [(l,b)]
772 -- why '<' rather than '<=' above? If the filesystem stores
773 -- times to the nearset second, we may occasionally find that
774 -- the object & source have the same modification time,
775 -- especially if the source was automatically generated
776 -- and compiled. Using >= is slightly unsafe, but it matches
779 return (new_linkables' ++ new_linkables)
782 hptLinkables :: HomePackageTable -> [Linkable]
783 -- Get all the linkables from the home package table, one for each module
784 -- Once the HPT is up to date, these are the ones we should link
785 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
788 -----------------------------------------------------------------------------
789 -- Do a pre-upsweep without use of "compile", to establish a
790 -- (downward-closed) set of stable modules for which we won't call compile.
793 -- * has a valid linkable (see getValidLinkables above)
794 -- * depends only on stable modules
795 -- * has an interface in the HPT (interactive mode only)
797 preUpsweep :: [Linkable] -- new valid linkables
798 -> [ModuleName] -- names of all mods encountered in downsweep
799 -> [ModuleName] -- accumulating stable modules
800 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
801 -> IO [ModuleName] -- stable modules
803 preUpsweep valid_lis all_home_mods stable [] = return stable
804 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
805 = do let scc = flattenSCC scc0
806 scc_allhomeimps :: [ModuleName]
808 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
809 all_imports_in_scc_or_stable
810 = all in_stable_or_scc scc_allhomeimps
812 = map modSummaryName scc
814 = m `elem` scc_names || m `elem` stable
816 -- now we check for valid linkables: each module in the SCC must
817 -- have a valid linkable (see getValidLinkables above).
818 has_valid_linkable new_summary
819 = isJust (findModuleLinkable_maybe valid_lis modname)
820 where modname = modSummaryName new_summary
822 scc_is_stable = all_imports_in_scc_or_stable
823 && all has_valid_linkable scc
826 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
827 else preUpsweep valid_lis all_home_mods stable sccs
830 -- Helper for preUpsweep. Assuming that new_summary's imports are all
831 -- stable (in the sense of preUpsweep), determine if new_summary is itself
832 -- stable, and, if so, in batch mode, return its linkable.
833 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
834 findInSummaries old_summaries mod_name
835 = [s | s <- old_summaries, modSummaryName s == mod_name]
837 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
838 findModInSummaries old_summaries mod
839 = case [s | s <- old_summaries, ms_mod s == mod] of
843 -- Return (names of) all those in modsDone who are part of a cycle
844 -- as defined by theGraph.
845 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
846 findPartiallyCompletedCycles modsDone theGraph
850 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
851 chew ((CyclicSCC vs):rest)
852 = let names_in_this_cycle = nub (map modSummaryName vs)
854 = nub ([done | done <- modsDone,
855 done `elem` names_in_this_cycle])
856 chewed_rest = chew rest
858 if notNull mods_in_this_cycle
859 && length mods_in_this_cycle < length names_in_this_cycle
860 then mods_in_this_cycle ++ chewed_rest
864 -- Compile multiple modules, stopping as soon as an error appears.
865 -- There better had not be any cyclic groups here -- we check for them.
866 upsweep_mods :: HscEnv -- Includes up-to-date HPT
867 -> [Linkable] -- Valid linkables
868 -> (ModuleName -> [ModuleName]) -- to construct downward closures
869 -> IO () -- how to clean up unwanted tmp files
870 -> [SCC ModSummary] -- mods to do (the worklist)
871 -- ...... RETURNING ......
873 HscEnv, -- With an updated HPT
874 [ModSummary]) -- Mods which succeeded
876 upsweep_mods hsc_env oldUI reachable_from cleanup
878 = return (Succeeded, hsc_env, [])
880 upsweep_mods hsc_env oldUI reachable_from cleanup
882 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
883 unwords (map (moduleNameUserString.modSummaryName) ms))
884 return (Failed, hsc_env, [])
886 upsweep_mods hsc_env oldUI reachable_from cleanup
887 ((AcyclicSCC mod):mods)
888 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
889 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
891 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
892 (reachable_from (modSummaryName mod))
894 cleanup -- Remove unwanted tmp files between compilations
896 if failed ok_flag then
897 return (Failed, hsc_env1, [])
899 (restOK, hsc_env2, modOKs)
900 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
901 return (restOK, hsc_env2, mod:modOKs)
904 -- Compile a single module. Always produce a Linkable for it if
905 -- successful. If no compilation happened, return the old Linkable.
906 upsweep_mod :: HscEnv
911 HscEnv) -- With updated HPT
913 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
915 let this_mod = ms_mod summary1
916 location = ms_location summary1
917 mod_name = moduleName this_mod
918 hpt1 = hsc_HPT hsc_env
920 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
921 Just mod_info -> Just (hm_iface mod_info)
924 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
925 source_unchanged = isJust maybe_old_linkable
927 reachable_only = filter (/= mod_name) reachable_inc_me
929 -- In interactive mode, all home modules below us *must* have an
930 -- interface in the HPT. We never demand-load home interfaces in
933 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
934 retainInTopLevelEnvs reachable_only hpt1
935 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
937 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
940 | Just l <- maybe_old_linkable, isObjectLinkable l = True
943 compresult <- compile hsc_env_strictDC this_mod location
944 (ms_hs_date summary1)
945 source_unchanged have_object mb_old_iface
949 -- Compilation "succeeded", and may or may not have returned a new
950 -- linkable (depending on whether compilation was actually performed
952 CompOK new_details new_globals new_iface maybe_new_linkable
954 new_linkable = maybe_new_linkable `orElse` old_linkable
955 new_info = HomeModInfo { hm_iface = new_iface,
956 hm_globals = new_globals,
957 hm_details = new_details,
958 hm_linkable = new_linkable }
959 hpt2 = extendModuleEnv hpt1 this_mod new_info
961 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
963 -- Compilation failed. Compile may still have updated the PCS, tho.
964 CompErrs -> return (Failed, hsc_env)
966 -- Filter modules in the HPT
967 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
968 retainInTopLevelEnvs keep_these hpt
969 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
971 maybeLookupUFM ufm u = case lookupUFM ufm u of
973 Just val -> [(u, val)]
975 -- Needed to clean up HPT so that we don't get duplicates in inst env
976 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
977 downwards_closure_of_module summaries root
978 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
979 toEdge summ = (modSummaryName summ,
980 filter (`elem` all_mods) (ms_allimps summ))
982 all_mods = map modSummaryName summaries
984 res = simple_transitive_closure (map toEdge summaries) [root]
986 -- trace (showSDoc (text "DC of mod" <+> ppr root
987 -- <+> text "=" <+> ppr res)) $
990 -- Calculate transitive closures from a set of roots given an adjacency list
991 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
992 simple_transitive_closure graph set
993 = let set2 = nub (concatMap dsts set ++ set)
994 dsts node = fromMaybe [] (lookup node graph)
996 if length set == length set2
998 else simple_transitive_closure graph set2
1001 -- Calculate SCCs of the module graph, with or without taking into
1002 -- account source imports.
1003 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1004 topological_sort include_source_imports summaries
1006 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1008 = (summ, modSummaryName summ,
1009 (if include_source_imports
1010 then ms_srcimps summ else []) ++ ms_imps summ)
1012 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1013 mash_edge (summ, m, m_imports)
1014 = case lookup m key_map of
1015 Nothing -> panic "reverse_topological_sort"
1016 Just mk -> (summ, mk,
1017 -- ignore imports not from the home package
1018 mapCatMaybes (flip lookup key_map) m_imports)
1020 edges = map toEdge summaries
1021 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1022 scc_input = map mash_edge edges
1023 sccs = stronglyConnComp scc_input
1028 -----------------------------------------------------------------------------
1029 -- Downsweep (dependency analysis)
1031 -- Chase downwards from the specified root set, returning summaries
1032 -- for all home modules encountered. Only follow source-import
1035 -- We pass in the previous collection of summaries, which is used as a
1036 -- cache to avoid recalculating a module summary if the source is
1039 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1040 downsweep roots old_summaries
1041 = do rootSummaries <- mapM getRootSummary roots
1042 checkDuplicates rootSummaries
1044 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1045 (ms_imps m)) rootSummaries))
1046 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1047 let mod = ms_mod s, isHomeModule mod
1049 return all_summaries
1051 getRootSummary :: FilePath -> IO ModSummary
1053 | isHaskellSrcFilename file
1054 = do exists <- doesFileExist file
1055 if exists then summariseFile file else do
1056 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1058 = do exists <- doesFileExist hs_file
1059 if exists then summariseFile hs_file else do
1060 exists <- doesFileExist lhs_file
1061 if exists then summariseFile lhs_file else do
1062 let mod_name = mkModuleName file
1063 maybe_summary <- getSummary (file, mod_name)
1064 case maybe_summary of
1065 Nothing -> packageModErr mod_name
1068 hs_file = file ++ ".hs"
1069 lhs_file = file ++ ".lhs"
1071 -- In a root module, the filename is allowed to diverge from the module
1072 -- name, so we have to check that there aren't multiple root files
1073 -- defining the same module (otherwise the duplicates will be silently
1074 -- ignored, leading to confusing behaviour).
1075 checkDuplicates :: [ModSummary] -> IO ()
1076 checkDuplicates summaries = mapM_ check summaries
1081 many -> multiRootsErr modl many
1082 where modl = ms_mod summ
1084 [ fromJust (ml_hs_file (ms_location summ'))
1085 | summ' <- summaries, ms_mod summ' == modl ]
1087 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1088 getSummary (currentMod,nm)
1089 = do found <- findModule nm
1091 Right (mod, location) -> do
1092 let old_summary = findModInSummaries old_summaries mod
1093 summarise mod location old_summary
1096 dflags <- getDynFlags
1097 throwDyn (noModError dflags currentMod nm files)
1099 -- loop invariant: env doesn't contain package modules
1100 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1101 loop [] env = return (moduleEnvElts env)
1103 = do -- imports for modules we don't already have
1104 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1107 needed_summaries <- mapM getSummary needed_imps
1109 -- get just the "home" modules
1110 let new_home_summaries = [ s | Just s <- needed_summaries ]
1112 -- loop, checking the new imports
1113 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1114 (ms_imps m)) new_home_summaries)
1115 loop new_imps (extendModuleEnvList env
1116 [ (ms_mod s, s) | s <- new_home_summaries ])
1118 -- ToDo: we don't have a proper line number for this error
1119 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1120 hang (text loc <> colon) 4 $
1121 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1125 | verbosity dflags < 3 =
1126 text "(use -v to see a list of the files searched for)"
1128 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1130 -----------------------------------------------------------------------------
1131 -- Summarising modules
1133 -- We have two types of summarisation:
1135 -- * Summarise a file. This is used for the root module(s) passed to
1136 -- cmLoadModules. The file is read, and used to determine the root
1137 -- module name. The module name may differ from the filename.
1139 -- * Summarise a module. We are given a module name, and must provide
1140 -- a summary. The finder is used to locate the file in which the module
1143 summariseFile :: FilePath -> IO ModSummary
1145 = do hspp_fn <- preprocess file
1146 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1148 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1149 the_imps = filter (/= gHC_PRIM_Name) imps
1151 (mod, location) <- mkHomeModLocation mod_name file
1154 <- case ml_hs_file location of
1155 Nothing -> noHsFileErr mod_name
1156 Just src_fn -> getModificationTime src_fn
1158 return (ModSummary { ms_mod = mod,
1159 ms_location = location{ml_hspp_file=Just hspp_fn},
1160 ms_srcimps = srcimps, ms_imps = the_imps,
1161 ms_hs_date = src_timestamp })
1163 -- Summarise a module, and pick up source and timestamp.
1164 summarise :: Module -> ModLocation -> Maybe ModSummary
1165 -> IO (Maybe ModSummary)
1166 summarise mod location old_summary
1167 | not (isHomeModule mod) = return Nothing
1169 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1171 case ml_hs_file location of {
1172 Nothing -> noHsFileErr mod;
1175 src_timestamp <- getModificationTime src_fn
1177 -- return the cached summary if the source didn't change
1178 case old_summary of {
1179 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1182 hspp_fn <- preprocess hs_fn
1183 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1185 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1186 the_imps = filter (/= gHC_PRIM_Name) imps
1188 when (mod_name /= moduleName mod) $
1189 throwDyn (ProgramError
1190 (showSDoc (text hs_fn
1191 <> text ": file name does not match module name"
1192 <+> quotes (ppr (moduleName mod)))))
1194 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1195 srcimps the_imps src_timestamp))
1201 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1204 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1205 quotes (ppr mod) <+>
1206 text "is a package module")))
1208 multiRootsErr mod files
1209 = throwDyn (ProgramError (showSDoc (
1210 text "module" <+> quotes (ppr mod) <+>
1211 text "is defined in multiple files:" <+>
1212 sep (map text files))))
1216 %************************************************************************
1220 %************************************************************************
1223 -- The ModLocation contains both the original source filename and the
1224 -- filename of the cleaned-up source file after all preprocessing has been
1225 -- done. The point is that the summariser will have to cpp/unlit/whatever
1226 -- all files anyway, and there's no point in doing this twice -- just
1227 -- park the result in a temp file, put the name of it in the location,
1228 -- and let @compile@ read from that file on the way back up.
1231 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1233 emptyMG :: ModuleGraph
1238 ms_mod :: Module, -- name, package
1239 ms_location :: ModLocation, -- location
1240 ms_srcimps :: [ModuleName], -- source imports
1241 ms_imps :: [ModuleName], -- non-source imports
1242 ms_hs_date :: ClockTime -- timestamp of summarised file
1245 instance Outputable ModSummary where
1247 = sep [text "ModSummary {",
1248 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1249 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1250 text "ms_imps =" <+> ppr (ms_imps ms),
1251 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1255 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1257 modSummaryName :: ModSummary -> ModuleName
1258 modSummaryName = moduleName . ms_mod