2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
7 {-# OPTIONS -fvia-C #-}
9 ModuleGraph, ModSummary(..),
13 cmInit, -- :: GhciMode -> DynFlags -> 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)
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 )
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 Control.Exception as Exception ( Exception, try )
100 import EXCEPTION ( throwDyn )
103 import Directory ( getModificationTime, doesFileExist )
108 import Time ( ClockTime )
113 -- Persistent state for the entire system
116 cm_hsc :: HscEnv, -- Includes the home-package table
117 cm_mg :: ModuleGraph, -- The module graph
118 cm_ic :: InteractiveContext -- Command-line binding info
122 cmGetModInfo cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
123 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
124 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
125 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
128 cmInit :: GhciMode -> DynFlags -> IO CmState
129 cmInit ghci_mode dflags
130 = do { hsc_env <- newHscEnv ghci_mode dflags
131 ; return (CmState { cm_hsc = hsc_env,
133 cm_ic = emptyInteractiveContext })}
135 discardCMInfo :: CmState -> CmState
136 -- Forget the compilation manager's state, including the home package table
137 -- but retain the persistent info in HscEnv
138 discardCMInfo cm_state
139 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
140 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
142 -------------------------------------------------------------------
143 -- The unlinked image
145 -- The compilation manager keeps a list of compiled, but as-yet unlinked
146 -- binaries (byte code or object code). Even when it links bytecode
147 -- it keeps the unlinked version so it can re-link it later without
150 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
152 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
153 findModuleLinkable_maybe lis mod
154 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
157 many -> pprPanic "findModuleLinkable" (ppr mod)
161 %************************************************************************
165 %************************************************************************
169 -----------------------------------------------------------------------------
170 -- Setting the context doesn't throw away any bindings; the bindings
171 -- we've built up in the InteractiveContext simply move to the new
172 -- module. They always shadow anything in scope in the current context.
176 -> [String] -- take the top-level scopes of these modules
177 -> [String] -- and the just the exports from these
179 cmSetContext cmstate toplevs exports = do
180 let old_ic = cm_ic cmstate
181 hsc_env = cm_hsc cmstate
182 hpt = hsc_HPT hsc_env
184 export_env <- mkExportEnv hsc_env (map mkModuleName exports)
185 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
187 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
188 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
189 ic_exports = exports,
190 ic_rn_gbl_env = all_env } }
192 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
194 = case lookupModuleEnvByName hpt (mkModuleName mod) of
195 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
196 Just details -> case hm_globals details of
197 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
198 Just env -> return env
200 cmGetContext :: CmState -> IO ([String],[String])
201 cmGetContext CmState{cm_ic=ic} =
202 return (ic_toplev_scope ic, ic_exports ic)
204 cmModuleIsInterpreted :: CmState -> String -> IO Bool
205 cmModuleIsInterpreted cmstate str
206 = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
207 Just details -> return (isJust (hm_globals details))
208 _not_a_home_module -> return False
210 -----------------------------------------------------------------------------
211 cmSetDFlags :: CmState -> DynFlags -> CmState
212 cmSetDFlags cm_state dflags
213 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
215 -----------------------------------------------------------------------------
216 -- cmInfoThing: convert a String to a TyThing
218 -- A string may refer to more than one TyThing (eg. a constructor,
219 -- and type constructor), so we return a list of all the possible TyThings.
221 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity)]
222 cmInfoThing cmstate id
223 = hscThing (cm_hsc cmstate) (cm_ic cmstate) id
225 -- ---------------------------------------------------------------------------
226 -- cmBrowseModule: get all the TyThings defined in a module
228 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
229 cmBrowseModule cmstate str exports_only
230 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
231 (mkModuleName str) exports_only
233 Nothing -> return [] -- An error of some kind
238 -----------------------------------------------------------------------------
239 -- cmRunStmt: Run a statement/expr.
242 = CmRunOk [Name] -- names bound by this evaluation
244 | CmRunException Exception -- statement raised an exception
246 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
247 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
249 maybe_stuff <- hscStmt hsc_env icontext expr
252 Nothing -> return (cmstate, CmRunFailed)
253 Just (new_ic, names, hval) -> do
255 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
256 either_hvals <- sandboxIO thing_to_run
260 -- on error, keep the *old* interactive context,
261 -- so that 'it' is not bound to something
262 -- that doesn't exist.
263 return ( cmstate, CmRunException e )
266 -- Get the newly bound things, and bind them.
267 -- Don't need to delete any shadowed bindings;
268 -- the new ones override the old ones.
269 extendLinkEnv (zip names hvals)
271 return (cmstate{ cm_ic=new_ic },
275 -- We run the statement in a "sandbox" to protect the rest of the
276 -- system from anything the expression might do. For now, this
277 -- consists of just wrapping it in an exception handler, but see below
278 -- for another version.
280 sandboxIO :: IO a -> IO (Either Exception a)
281 sandboxIO thing = Exception.try thing
284 -- This version of sandboxIO runs the expression in a completely new
285 -- RTS main thread. It is disabled for now because ^C exceptions
286 -- won't be delivered to the new thread, instead they'll be delivered
287 -- to the (blocked) GHCi main thread.
289 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
291 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
293 st_thing <- newStablePtr (Exception.try thing)
294 alloca $ \ p_st_result -> do
295 stat <- rts_evalStableIO st_thing p_st_result
296 freeStablePtr st_thing
298 then do st_result <- peek p_st_result
299 result <- deRefStablePtr st_result
300 freeStablePtr st_result
301 return (Right result)
303 return (Left (fromIntegral stat))
305 foreign import "rts_evalStableIO" {- safe -}
306 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
307 -- more informative than the C type!
310 -----------------------------------------------------------------------------
311 -- cmTypeOfExpr: returns a string representing the type of an expression
313 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
314 cmTypeOfExpr cmstate expr
315 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
318 Nothing -> return Nothing
319 Just ty -> return (Just str)
321 str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
322 unqual = icPrintUnqual (cm_ic cmstate)
323 tidy_ty = tidyType emptyTidyEnv ty
326 -----------------------------------------------------------------------------
327 -- cmTypeOfName: returns a string representing the type of a name.
329 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
330 cmTypeOfName CmState{ cm_ic=ic } name
332 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
333 case lookupNameEnv (ic_type_env ic) name of
334 Nothing -> return Nothing
335 Just (AnId id) -> return (Just str)
337 unqual = icPrintUnqual ic
338 ty = tidyType emptyTidyEnv (idType id)
339 str = showSDocForUser unqual (ppr ty)
341 _ -> panic "cmTypeOfName"
343 -----------------------------------------------------------------------------
344 -- cmCompileExpr: compile an expression and deliver an HValue
346 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
347 cmCompileExpr cmstate expr
350 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
351 ("let __cmCompileExpr = "++expr)
354 Nothing -> return Nothing
355 Just (new_ic, names, hval) -> do
358 hvals <- (unsafeCoerce# hval) :: IO [HValue]
360 case (names,hvals) of
361 ([n],[hv]) -> return (Just hv)
362 _ -> panic "cmCompileExpr"
368 %************************************************************************
370 Loading and unloading
372 %************************************************************************
375 -----------------------------------------------------------------------------
376 -- Unload the compilation manager's state: everything it knows about the
377 -- current collection of modules in the Home package.
379 cmUnload :: CmState -> IO CmState
380 cmUnload state@CmState{ cm_hsc = hsc_env }
381 = do -- Throw away the old home dir cache
384 -- Unload everything the linker knows about
387 -- Start with a fresh CmState, but keep the PersistentCompilerState
388 return (discardCMInfo state)
390 cm_unload hsc_env linkables
391 = case hsc_mode hsc_env of
394 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
396 Interactive -> panic "unload: no interpreter"
400 -----------------------------------------------------------------------------
401 -- Trace dependency graph
403 -- This is a seperate pass so that the caller can back off and keep
404 -- the current state if the downsweep fails. Typically the caller
405 -- might go cmDepAnal
408 -- He wants to do the dependency analysis before the unload, so that
409 -- if the former fails he can use the later
411 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
412 cmDepAnal cmstate rootnames
413 = do showPass dflags "Chasing dependencies"
414 when (verbosity dflags >= 1 && gmode == Batch) $
415 hPutStrLn stderr (showSDoc (hcat [
416 text "Chasing modules from: ",
417 hcat (punctuate comma (map text rootnames))]))
418 downsweep rootnames (cm_mg cmstate)
420 hsc_env = cm_hsc cmstate
421 dflags = hsc_dflags hsc_env
422 gmode = hsc_mode hsc_env
424 -----------------------------------------------------------------------------
425 -- The real business of the compilation manager: given a system state and
426 -- a module name, try and bring the module up to date, probably changing
427 -- the system state at the same time.
429 cmLoadModules :: CmState -- The HPT may not be as up to date
430 -> ModuleGraph -- Bang up to date
431 -> IO (CmState, -- new state
432 SuccessFlag, -- was successful
433 [String]) -- list of modules loaded
435 cmLoadModules cmstate1 mg2unsorted
436 = do -- version 1's are the original, before downsweep
437 let hsc_env = cm_hsc cmstate1
438 let hpt1 = hsc_HPT hsc_env
439 let ghci_mode = hsc_mode hsc_env -- this never changes
440 let dflags = hsc_dflags hsc_env -- this never changes
442 -- Do the downsweep to reestablish the module graph
443 let verb = verbosity dflags
445 -- Find out if we have a Main module
446 mb_main_mod <- readIORef v_MainModIs
448 main_mod = mb_main_mod `orElse` "Main"
450 = any ((==main_mod).moduleNameUserString.modSummaryName)
453 let mg2unsorted_names = map modSummaryName mg2unsorted
455 -- reachable_from follows source as well as normal imports
456 let reachable_from :: ModuleName -> [ModuleName]
457 reachable_from = downwards_closure_of_module mg2unsorted
459 -- should be cycle free; ignores 'import source's
460 let mg2 = topological_sort False mg2unsorted
461 -- ... whereas this takes them into account. Used for
462 -- backing out partially complete cycles following a failed
463 -- upsweep, and for removing from hpt all the modules
464 -- not in strict downwards closure, during calls to compile.
465 let mg2_with_srcimps = topological_sort True mg2unsorted
467 -- Sort out which linkables we wish to keep in the unlinked image.
468 -- See getValidLinkables below for details.
469 (valid_old_linkables, new_linkables)
470 <- getValidLinkables ghci_mode (hptLinkables hpt1)
471 mg2unsorted_names mg2_with_srcimps
473 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
475 -- Uniq of ModuleName is the same as Module, fortunately...
476 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
477 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
479 -- When (verb >= 2) $
480 -- putStrLn (showSDoc (text "Valid linkables:"
481 -- <+> ppr valid_linkables))
483 -- Figure out a stable set of modules which can be retained
484 -- the top level envs, to avoid upsweeping them. Goes to a
485 -- bit of trouble to avoid upsweeping module cycles.
487 -- Construct a set S of stable modules like this:
488 -- Travel upwards, over the sccified graph. For each scc
489 -- of modules ms, add ms to S only if:
490 -- 1. All home imports of ms are either in ms or S
491 -- 2. A valid old linkable exists for each module in ms
493 stable_mods <- preUpsweep valid_old_linkables
494 mg2unsorted_names [] mg2_with_srcimps
497 = concatMap (findInSummaries mg2unsorted) stable_mods
500 = filter (\m -> linkableModName m `elem` stable_mods)
504 hPutStrLn stderr (showSDoc (text "Stable modules:"
505 <+> sep (map (text.moduleNameUserString) stable_mods)))
507 -- Unload any modules which are going to be re-linked this
509 cm_unload hsc_env2 stable_linkables
511 -- we can now glom together our linkable sets
512 let valid_linkables = valid_old_linkables ++ new_linkables
514 -- We could at this point detect cycles which aren't broken by
515 -- a source-import, and complain immediately, but it seems better
516 -- to let upsweep_mods do this, so at least some useful work gets
517 -- done before the upsweep is abandoned.
519 = filter (\scc -> any (`notElem` stable_mods)
520 (map modSummaryName (flattenSCC scc)))
523 --hPutStrLn stderr "after tsort:\n"
524 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
526 -- Because we don't take into account source imports when doing
527 -- the topological sort, there shouldn't be any cycles in mg2.
528 -- If there is, we complain and give up -- the user needs to
529 -- break the cycle using a boot file.
531 -- Now do the upsweep, calling compile for each module in
532 -- turn. Final result is version 3 of everything.
534 -- clean up between compilations
535 let cleanup = cleanTempFilesExcept verb
536 (ppFilesFromSummaries (flattenSCCs mg2))
538 (upsweep_ok, hsc_env3, modsUpswept)
539 <- upsweep_mods hsc_env2 valid_linkables reachable_from
540 cleanup upsweep_these
542 -- At this point, modsUpswept and newLis should have the same
543 -- length, so there is one new (or old) linkable for each
544 -- mod which was processed (passed to compile).
546 -- Make modsDone be the summaries for each home module now
547 -- available; this should equal the domain of hpt3.
548 -- (NOT STRICTLY TRUE if an interactive session was started
549 -- with some object on disk ???)
550 -- Get in in a roughly top .. bottom order (hence reverse).
552 let modsDone = reverse modsUpswept ++ stable_summaries
554 -- Try and do linking in some form, depending on whether the
555 -- upsweep was completely or only partially successful.
557 if succeeded upsweep_ok
560 -- Easy; just relink it all.
561 do when (verb >= 2) $
562 hPutStrLn stderr "Upsweep completely successful."
564 -- clean up after ourselves
565 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
567 ofile <- readIORef v_Output_file
568 no_hs_main <- readIORef v_NoHsMain
570 -- Issue a warning for the confusing case where the user
571 -- said '-o foo' but we're not going to do any linking.
572 -- We attempt linking if either (a) one of the modules is
573 -- called Main, or (b) the user said -no-hs-main, indicating
574 -- that main() is going to come from somewhere else.
576 let do_linking = a_root_is_Main || no_hs_main
577 when (ghci_mode == Batch && isJust ofile && not do_linking
579 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
581 -- link everything together
582 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
584 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
585 cmLoadFinish Succeeded linkresult cmstate3
588 -- Tricky. We need to back out the effects of compiling any
589 -- half-done cycles, both so as to clean up the top level envs
590 -- and to avoid telling the interactive linker to link them.
591 do when (verb >= 2) $
592 hPutStrLn stderr "Upsweep partially successful."
595 = map modSummaryName modsDone
596 let mods_to_zap_names
597 = findPartiallyCompletedCycles modsDone_names
600 = filter ((`notElem` mods_to_zap_names).modSummaryName)
603 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
606 -- Clean up after ourselves
607 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
609 -- Link everything together
610 linkresult <- link ghci_mode dflags False hpt4
612 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
613 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
614 cmLoadFinish Failed linkresult cmstate3
617 -- Finish up after a cmLoad.
619 -- If the link failed, unload everything and return.
620 cmLoadFinish ok Failed cmstate
621 = do cm_unload (cm_hsc cmstate) []
622 return (discardCMInfo cmstate, Failed, [])
624 -- Empty the interactive context and set the module context to the topmost
625 -- newly loaded module, or the Prelude if none were loaded.
626 cmLoadFinish ok Succeeded cmstate
627 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
628 mods_loaded = map (moduleNameUserString.modSummaryName)
631 return (new_cmstate, ok, mods_loaded)
633 -- used to fish out the preprocess output files for the purposes of
634 -- cleaning up. The preprocessed file *might* be the same as the
635 -- source file, but that doesn't do any harm.
636 ppFilesFromSummaries summaries
637 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
639 -----------------------------------------------------------------------------
642 -- For each module (or SCC of modules), we take:
644 -- - an on-disk linkable, if this is the first time around and one
647 -- - the old linkable, otherwise (and if one is available).
649 -- and we throw away the linkable if it is older than the source file.
650 -- In interactive mode, we also ignore the on-disk linkables unless
651 -- all of the dependents of this SCC also have on-disk linkables (we
652 -- can't have dynamically loaded objects that depend on interpreted
655 -- If a module has a valid linkable, then it may be STABLE (see below),
656 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
659 -- ToDo: this pass could be merged with the preUpsweep.
663 -> [Linkable] -- old linkables
664 -> [ModuleName] -- all home modules
665 -> [SCC ModSummary] -- all modules in the program, dependency order
666 -> IO ( [Linkable], -- still-valid linkables
667 [Linkable] -- new linkables we just found
670 getValidLinkables mode old_linkables all_home_mods module_graph = do
671 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
673 return (partition_it ls [] [])
675 partition_it [] valid new = (valid,new)
676 partition_it ((l,b):ls) valid new
677 | b = partition_it ls valid (l:new)
678 | otherwise = partition_it ls (l:valid) new
681 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
683 scc = flattenSCC scc0
684 scc_names = map modSummaryName scc
685 home_module m = m `elem` all_home_mods && m `notElem` scc_names
686 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
687 -- NB. ms_imps, not ms_allimps above. We don't want to
688 -- force a module's SOURCE imports to be already compiled for
689 -- its object linkable to be valid.
692 case findModuleLinkable_maybe (map fst new_linkables) m of
694 Just l -> isObjectLinkable l
696 objects_allowed = mode == Batch || all has_object scc_allhomeimps
700 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
702 -- since an scc can contain only all objects or no objects at all,
703 -- we have to check whether we got all objects or not, and re-do
704 -- the linkable check if not.
707 && not (all isObjectLinkable (map fst new_linkables'))
708 then foldM (getValidLinkable old_linkables False) [] scc
709 else return new_linkables'
711 return (new_linkables ++ new_linkables')
714 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
715 -> IO [(Linkable,Bool)]
716 -- True <=> linkable is new; i.e. freshly discovered on the disk
717 -- presumably generated 'on the side'
718 -- by a separate GHC run
719 getValidLinkable old_linkables objects_allowed new_linkables summary
720 -- 'objects_allowed' says whether we permit this module to
721 -- have a .o-file linkable. We only permit it if all the
722 -- modules it depends on also have .o files; a .o file can't
723 -- link to a bytecode module
724 = do let mod_name = modSummaryName summary
727 <- if (not objects_allowed)
730 else findLinkable mod_name (ms_location summary)
732 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
735 case (old_linkable, maybe_disk_linkable) of
736 (Nothing, Nothing) -> []
738 -- new object linkable just appeared
739 (Nothing, Just l) -> up_to_date l True
742 | isObjectLinkable l -> []
743 -- object linkable disappeared! In case we need to
744 -- relink the module, disregard the old linkable and
745 -- just interpret the module from now on.
746 | otherwise -> up_to_date l False
747 -- old byte code linkable
750 | not (isObjectLinkable l) -> up_to_date l False
751 -- if the previous linkable was interpreted, then we
752 -- ignore a newly compiled version, because the version
753 -- numbers in the interface file will be out-of-sync with
754 -- our internal ones.
755 | linkableTime l' > linkableTime l -> up_to_date l' True
756 | linkableTime l' == linkableTime l -> up_to_date l False
758 -- on-disk linkable has been replaced by an older one!
759 -- again, disregard the previous one.
762 | linkableTime l < ms_hs_date summary = []
763 | otherwise = [(l,b)]
764 -- why '<' rather than '<=' above? If the filesystem stores
765 -- times to the nearset second, we may occasionally find that
766 -- the object & source have the same modification time,
767 -- especially if the source was automatically generated
768 -- and compiled. Using >= is slightly unsafe, but it matches
771 return (new_linkables' ++ new_linkables)
774 hptLinkables :: HomePackageTable -> [Linkable]
775 -- Get all the linkables from the home package table, one for each module
776 -- Once the HPT is up to date, these are the ones we should link
777 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
780 -----------------------------------------------------------------------------
781 -- Do a pre-upsweep without use of "compile", to establish a
782 -- (downward-closed) set of stable modules for which we won't call compile.
785 -- * has a valid linkable (see getValidLinkables above)
786 -- * depends only on stable modules
787 -- * has an interface in the HPT (interactive mode only)
789 preUpsweep :: [Linkable] -- new valid linkables
790 -> [ModuleName] -- names of all mods encountered in downsweep
791 -> [ModuleName] -- accumulating stable modules
792 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
793 -> IO [ModuleName] -- stable modules
795 preUpsweep valid_lis all_home_mods stable [] = return stable
796 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
797 = do let scc = flattenSCC scc0
798 scc_allhomeimps :: [ModuleName]
800 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
801 all_imports_in_scc_or_stable
802 = all in_stable_or_scc scc_allhomeimps
804 = map modSummaryName scc
806 = m `elem` scc_names || m `elem` stable
808 -- now we check for valid linkables: each module in the SCC must
809 -- have a valid linkable (see getValidLinkables above).
810 has_valid_linkable new_summary
811 = isJust (findModuleLinkable_maybe valid_lis modname)
812 where modname = modSummaryName new_summary
814 scc_is_stable = all_imports_in_scc_or_stable
815 && all has_valid_linkable scc
818 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
819 else preUpsweep valid_lis all_home_mods stable sccs
822 -- Helper for preUpsweep. Assuming that new_summary's imports are all
823 -- stable (in the sense of preUpsweep), determine if new_summary is itself
824 -- stable, and, if so, in batch mode, return its linkable.
825 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
826 findInSummaries old_summaries mod_name
827 = [s | s <- old_summaries, modSummaryName s == mod_name]
829 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
830 findModInSummaries old_summaries mod
831 = case [s | s <- old_summaries, ms_mod s == mod] of
835 -- Return (names of) all those in modsDone who are part of a cycle
836 -- as defined by theGraph.
837 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
838 findPartiallyCompletedCycles modsDone theGraph
842 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
843 chew ((CyclicSCC vs):rest)
844 = let names_in_this_cycle = nub (map modSummaryName vs)
846 = nub ([done | done <- modsDone,
847 done `elem` names_in_this_cycle])
848 chewed_rest = chew rest
850 if notNull mods_in_this_cycle
851 && length mods_in_this_cycle < length names_in_this_cycle
852 then mods_in_this_cycle ++ chewed_rest
856 -- Compile multiple modules, stopping as soon as an error appears.
857 -- There better had not be any cyclic groups here -- we check for them.
858 upsweep_mods :: HscEnv -- Includes up-to-date HPT
859 -> [Linkable] -- Valid linkables
860 -> (ModuleName -> [ModuleName]) -- to construct downward closures
861 -> IO () -- how to clean up unwanted tmp files
862 -> [SCC ModSummary] -- mods to do (the worklist)
863 -- ...... RETURNING ......
865 HscEnv, -- With an updated HPT
866 [ModSummary]) -- Mods which succeeded
868 upsweep_mods hsc_env oldUI reachable_from cleanup
870 = return (Succeeded, hsc_env, [])
872 upsweep_mods hsc_env oldUI reachable_from cleanup
874 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
875 unwords (map (moduleNameUserString.modSummaryName) ms))
876 return (Failed, hsc_env, [])
878 upsweep_mods hsc_env oldUI reachable_from cleanup
879 ((AcyclicSCC mod):mods)
880 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
881 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
883 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
884 (reachable_from (modSummaryName mod))
886 cleanup -- Remove unwanted tmp files between compilations
888 if failed ok_flag then
889 return (Failed, hsc_env1, [])
891 (restOK, hsc_env2, modOKs)
892 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
893 return (restOK, hsc_env2, mod:modOKs)
896 -- Compile a single module. Always produce a Linkable for it if
897 -- successful. If no compilation happened, return the old Linkable.
898 upsweep_mod :: HscEnv
903 HscEnv) -- With updated HPT
905 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
907 let this_mod = ms_mod summary1
908 location = ms_location summary1
909 mod_name = moduleName this_mod
910 hpt1 = hsc_HPT hsc_env
912 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
913 Just mod_info -> Just (hm_iface mod_info)
916 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
917 source_unchanged = isJust maybe_old_linkable
919 reachable_only = filter (/= mod_name) reachable_inc_me
921 -- In interactive mode, all home modules below us *must* have an
922 -- interface in the HPT. We never demand-load home interfaces in
925 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
926 retainInTopLevelEnvs reachable_only hpt1
927 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
929 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
932 | Just l <- maybe_old_linkable, isObjectLinkable l = True
935 compresult <- compile hsc_env_strictDC this_mod location
936 source_unchanged have_object mb_old_iface
940 -- Compilation "succeeded", and may or may not have returned a new
941 -- linkable (depending on whether compilation was actually performed
943 CompOK new_details new_globals new_iface maybe_new_linkable
945 new_linkable = maybe_new_linkable `orElse` old_linkable
946 new_info = HomeModInfo { hm_iface = new_iface,
947 hm_globals = new_globals,
948 hm_details = new_details,
949 hm_linkable = new_linkable }
950 hpt2 = extendModuleEnv hpt1 this_mod new_info
952 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
954 -- Compilation failed. Compile may still have updated the PCS, tho.
955 CompErrs -> return (Failed, hsc_env)
957 -- Filter modules in the HPT
958 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
959 retainInTopLevelEnvs keep_these hpt
960 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
962 maybeLookupUFM ufm u = case lookupUFM ufm u of
964 Just val -> [(u, val)]
966 -- Needed to clean up HPT so that we don't get duplicates in inst env
967 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
968 downwards_closure_of_module summaries root
969 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
970 toEdge summ = (modSummaryName summ,
971 filter (`elem` all_mods) (ms_allimps summ))
973 all_mods = map modSummaryName summaries
975 res = simple_transitive_closure (map toEdge summaries) [root]
977 -- trace (showSDoc (text "DC of mod" <+> ppr root
978 -- <+> text "=" <+> ppr res)) $
981 -- Calculate transitive closures from a set of roots given an adjacency list
982 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
983 simple_transitive_closure graph set
984 = let set2 = nub (concatMap dsts set ++ set)
985 dsts node = fromMaybe [] (lookup node graph)
987 if length set == length set2
989 else simple_transitive_closure graph set2
992 -- Calculate SCCs of the module graph, with or without taking into
993 -- account source imports.
994 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
995 topological_sort include_source_imports summaries
997 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
999 = (summ, modSummaryName summ,
1000 (if include_source_imports
1001 then ms_srcimps summ else []) ++ ms_imps summ)
1003 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1004 mash_edge (summ, m, m_imports)
1005 = case lookup m key_map of
1006 Nothing -> panic "reverse_topological_sort"
1007 Just mk -> (summ, mk,
1008 -- ignore imports not from the home package
1009 mapCatMaybes (flip lookup key_map) m_imports)
1011 edges = map toEdge summaries
1012 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1013 scc_input = map mash_edge edges
1014 sccs = stronglyConnComp scc_input
1019 -----------------------------------------------------------------------------
1020 -- Downsweep (dependency analysis)
1022 -- Chase downwards from the specified root set, returning summaries
1023 -- for all home modules encountered. Only follow source-import
1026 -- We pass in the previous collection of summaries, which is used as a
1027 -- cache to avoid recalculating a module summary if the source is
1030 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1031 downsweep roots old_summaries
1032 = do rootSummaries <- mapM getRootSummary roots
1033 checkDuplicates rootSummaries
1035 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1036 (ms_imps m)) rootSummaries))
1037 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1038 let mod = ms_mod s, isHomeModule mod
1040 return all_summaries
1042 getRootSummary :: FilePath -> IO ModSummary
1044 | isHaskellSrcFilename file
1045 = do exists <- doesFileExist file
1046 if exists then summariseFile file else do
1047 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1049 = do exists <- doesFileExist hs_file
1050 if exists then summariseFile hs_file else do
1051 exists <- doesFileExist lhs_file
1052 if exists then summariseFile lhs_file else do
1053 let mod_name = mkModuleName file
1054 maybe_summary <- getSummary (file, mod_name)
1055 case maybe_summary of
1056 Nothing -> packageModErr mod_name
1059 hs_file = file ++ ".hs"
1060 lhs_file = file ++ ".lhs"
1062 -- In a root module, the filename is allowed to diverge from the module
1063 -- name, so we have to check that there aren't multiple root files
1064 -- defining the same module (otherwise the duplicates will be silently
1065 -- ignored, leading to confusing behaviour).
1066 checkDuplicates :: [ModSummary] -> IO ()
1067 checkDuplicates summaries = mapM_ check summaries
1072 many -> multiRootsErr modl many
1073 where modl = ms_mod summ
1075 [ fromJust (ml_hs_file (ms_location summ'))
1076 | summ' <- summaries, ms_mod summ' == modl ]
1078 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1079 getSummary (currentMod,nm)
1080 = do found <- findModule nm
1082 Right (mod, location) -> do
1083 let old_summary = findModInSummaries old_summaries mod
1084 summarise mod location old_summary
1087 dflags <- getDynFlags
1088 throwDyn (noModError dflags currentMod nm files)
1090 -- loop invariant: env doesn't contain package modules
1091 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1092 loop [] env = return (moduleEnvElts env)
1094 = do -- imports for modules we don't already have
1095 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1098 needed_summaries <- mapM getSummary needed_imps
1100 -- get just the "home" modules
1101 let new_home_summaries = [ s | Just s <- needed_summaries ]
1103 -- loop, checking the new imports
1104 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1105 (ms_imps m)) new_home_summaries)
1106 loop new_imps (extendModuleEnvList env
1107 [ (ms_mod s, s) | s <- new_home_summaries ])
1109 -- ToDo: we don't have a proper line number for this error
1110 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1111 hang (text loc <> colon) 4 $
1112 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1116 | verbosity dflags < 3 =
1117 text "(use -v to see a list of the files searched for)"
1119 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1121 -----------------------------------------------------------------------------
1122 -- Summarising modules
1124 -- We have two types of summarisation:
1126 -- * Summarise a file. This is used for the root module(s) passed to
1127 -- cmLoadModules. The file is read, and used to determine the root
1128 -- module name. The module name may differ from the filename.
1130 -- * Summarise a module. We are given a module name, and must provide
1131 -- a summary. The finder is used to locate the file in which the module
1134 summariseFile :: FilePath -> IO ModSummary
1136 = do hspp_fn <- preprocess file
1137 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1139 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1140 the_imps = filter (/= gHC_PRIM_Name) imps
1142 (mod, location) <- mkHomeModLocation mod_name file
1145 <- case ml_hs_file location of
1146 Nothing -> noHsFileErr mod_name
1147 Just src_fn -> getModificationTime src_fn
1149 return (ModSummary { ms_mod = mod,
1150 ms_location = location{ml_hspp_file=Just hspp_fn},
1151 ms_srcimps = srcimps, ms_imps = the_imps,
1152 ms_hs_date = src_timestamp })
1154 -- Summarise a module, and pick up source and timestamp.
1155 summarise :: Module -> ModLocation -> Maybe ModSummary
1156 -> IO (Maybe ModSummary)
1157 summarise mod location old_summary
1158 | not (isHomeModule mod) = return Nothing
1160 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1162 case ml_hs_file location of {
1163 Nothing -> noHsFileErr mod;
1166 src_timestamp <- getModificationTime src_fn
1168 -- return the cached summary if the source didn't change
1169 case old_summary of {
1170 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1173 hspp_fn <- preprocess hs_fn
1174 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1176 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1177 the_imps = filter (/= gHC_PRIM_Name) imps
1179 when (mod_name /= moduleName mod) $
1180 throwDyn (ProgramError
1181 (showSDoc (text hs_fn
1182 <> text ": file name does not match module name"
1183 <+> quotes (ppr (moduleName mod)))))
1185 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1186 srcimps the_imps src_timestamp))
1192 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1195 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1196 quotes (ppr mod) <+>
1197 text "is a package module")))
1199 multiRootsErr mod files
1200 = throwDyn (ProgramError (showSDoc (
1201 text "module" <+> quotes (ppr mod) <+>
1202 text "is defined in multiple files:" <+>
1203 sep (map text files))))
1207 %************************************************************************
1211 %************************************************************************
1214 -- The ModLocation contains both the original source filename and the
1215 -- filename of the cleaned-up source file after all preprocessing has been
1216 -- done. The point is that the summariser will have to cpp/unlit/whatever
1217 -- all files anyway, and there's no point in doing this twice -- just
1218 -- park the result in a temp file, put the name of it in the location,
1219 -- and let @compile@ read from that file on the way back up.
1222 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1224 emptyMG :: ModuleGraph
1229 ms_mod :: Module, -- name, package
1230 ms_location :: ModLocation, -- location
1231 ms_srcimps :: [ModuleName], -- source imports
1232 ms_imps :: [ModuleName], -- non-source imports
1233 ms_hs_date :: ClockTime -- timestamp of summarised file
1236 instance Outputable ModSummary where
1238 = sep [text "ModSummary {",
1239 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1240 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1241 text "ms_imps =" <+> ppr (ms_imps ms),
1242 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1246 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1248 modSummaryName :: ModSummary -> ModuleName
1249 modSummaryName = moduleName . ms_mod