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 -> String -> IO (CmState, [(TyThing,Fixity)])
29 cmBrowseModule, -- :: CmState -> IO [TyThing]
32 cmRunStmt, -- :: CmState -> DynFlags -> String
33 -- -> IO (CmState, CmRunResult)
35 cmTypeOfExpr, -- :: CmState -> DynFlags -> String
36 -- -> IO (CmState, Maybe String)
38 cmKindOfType, -- :: CmState -> DynFlags -> String
39 -- -> IO (CmState, Maybe String)
41 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
44 cmCompileExpr, -- :: CmState -> DynFlags -> String
45 -- -> IO (CmState, Maybe HValue)
47 cmGetModInfo, -- :: CmState -> (ModuleGraph, HomePackageTable)
50 cmGetBindings, -- :: CmState -> [TyThing]
51 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
56 #include "HsVersions.h"
58 import DriverPipeline ( CompResult(..), preprocess, compile, link )
59 import HscMain ( newHscEnv )
60 import DriverState ( v_Output_file, v_NoHsMain, v_MainModIs )
64 import PrelNames ( gHC_PRIM_Name )
65 import Module ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
66 ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
67 extendModuleEnvList, extendModuleEnv,
72 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
73 import ErrUtils ( showPass )
74 import SysTools ( cleanTempFilesExcept )
75 import BasicTypes ( SuccessFlag(..), succeeded, failed )
79 import CmdLineOpts ( DynFlags(..), getDynFlags )
80 import Maybes ( expectJust, orElse, mapCatMaybes )
82 import DATA_IOREF ( readIORef )
85 import HscMain ( hscThing, hscStmt, hscTcExpr, hscKcType )
86 import TcRnDriver ( mkExportEnv, getModuleContents )
87 import IfaceSyn ( IfaceDecl )
88 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
92 import Type ( tidyType )
93 import VarEnv ( emptyTidyEnv )
94 import BasicTypes ( Fixity )
95 import Linker ( HValue, unload, extendLinkEnv )
96 import GHC.Exts ( unsafeCoerce# )
98 import SrcLoc ( SrcLoc )
99 import Control.Exception as Exception ( Exception, try )
102 import EXCEPTION ( throwDyn )
105 import Directory ( getModificationTime, doesFileExist )
110 import Time ( ClockTime )
115 -- Persistent state for the entire system
118 cm_hsc :: HscEnv, -- Includes the home-package table
119 cm_mg :: ModuleGraph, -- The module graph
120 cm_ic :: InteractiveContext -- Command-line binding info
124 cmGetModInfo cmstate = (cm_mg cmstate, hsc_HPT (cm_hsc cmstate))
125 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
126 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
127 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
130 cmInit :: GhciMode -> DynFlags -> IO CmState
131 cmInit ghci_mode dflags
132 = do { hsc_env <- newHscEnv ghci_mode dflags
133 ; return (CmState { cm_hsc = hsc_env,
135 cm_ic = emptyInteractiveContext })}
137 discardCMInfo :: CmState -> CmState
138 -- Forget the compilation manager's state, including the home package table
139 -- but retain the persistent info in HscEnv
140 discardCMInfo cm_state
141 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
142 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
144 -------------------------------------------------------------------
145 -- The unlinked image
147 -- The compilation manager keeps a list of compiled, but as-yet unlinked
148 -- binaries (byte code or object code). Even when it links bytecode
149 -- it keeps the unlinked version so it can re-link it later without
152 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
154 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
155 findModuleLinkable_maybe lis mod
156 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
159 many -> pprPanic "findModuleLinkable" (ppr mod)
163 %************************************************************************
167 %************************************************************************
171 -----------------------------------------------------------------------------
172 -- Setting the context doesn't throw away any bindings; the bindings
173 -- we've built up in the InteractiveContext simply move to the new
174 -- module. They always shadow anything in scope in the current context.
178 -> [String] -- take the top-level scopes of these modules
179 -> [String] -- and the just the exports from these
181 cmSetContext cmstate toplevs exports = do
182 let old_ic = cm_ic cmstate
183 hsc_env = cm_hsc cmstate
184 hpt = hsc_HPT hsc_env
186 export_env <- mkExportEnv hsc_env (map mkModuleName exports)
187 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
189 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
190 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
191 ic_exports = exports,
192 ic_rn_gbl_env = all_env } }
194 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
196 = case lookupModuleEnvByName hpt (mkModuleName mod) of
197 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
198 Just details -> case hm_globals details of
199 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
200 Just env -> return env
202 cmGetContext :: CmState -> IO ([String],[String])
203 cmGetContext CmState{cm_ic=ic} =
204 return (ic_toplev_scope ic, ic_exports ic)
206 cmModuleIsInterpreted :: CmState -> String -> IO Bool
207 cmModuleIsInterpreted cmstate str
208 = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
209 Just details -> return (isJust (hm_globals details))
210 _not_a_home_module -> return False
212 -----------------------------------------------------------------------------
213 cmSetDFlags :: CmState -> DynFlags -> CmState
214 cmSetDFlags cm_state dflags
215 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
217 -----------------------------------------------------------------------------
218 -- cmInfoThing: convert a String to a TyThing
220 -- A string may refer to more than one TyThing (eg. a constructor,
221 -- and type constructor), so we return a list of all the possible TyThings.
223 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity,SrcLoc)]
224 cmInfoThing cmstate id
225 = hscThing (cm_hsc cmstate) (cm_ic cmstate) id
227 -- ---------------------------------------------------------------------------
228 -- cmBrowseModule: get all the TyThings defined in a module
230 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
231 cmBrowseModule cmstate str exports_only
232 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
233 (mkModuleName str) exports_only
235 Nothing -> return [] -- An error of some kind
240 -----------------------------------------------------------------------------
241 -- cmRunStmt: Run a statement/expr.
244 = CmRunOk [Name] -- names bound by this evaluation
246 | CmRunException Exception -- statement raised an exception
248 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
249 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
251 maybe_stuff <- hscStmt hsc_env icontext expr
254 Nothing -> return (cmstate, CmRunFailed)
255 Just (new_ic, names, hval) -> do
257 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
258 either_hvals <- sandboxIO thing_to_run
262 -- on error, keep the *old* interactive context,
263 -- so that 'it' is not bound to something
264 -- that doesn't exist.
265 return ( cmstate, CmRunException e )
268 -- Get the newly bound things, and bind them.
269 -- Don't need to delete any shadowed bindings;
270 -- the new ones override the old ones.
271 extendLinkEnv (zip names hvals)
273 return (cmstate{ cm_ic=new_ic },
277 -- We run the statement in a "sandbox" to protect the rest of the
278 -- system from anything the expression might do. For now, this
279 -- consists of just wrapping it in an exception handler, but see below
280 -- for another version.
282 sandboxIO :: IO a -> IO (Either Exception a)
283 sandboxIO thing = Exception.try thing
286 -- This version of sandboxIO runs the expression in a completely new
287 -- RTS main thread. It is disabled for now because ^C exceptions
288 -- won't be delivered to the new thread, instead they'll be delivered
289 -- to the (blocked) GHCi main thread.
291 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
293 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
295 st_thing <- newStablePtr (Exception.try thing)
296 alloca $ \ p_st_result -> do
297 stat <- rts_evalStableIO st_thing p_st_result
298 freeStablePtr st_thing
300 then do st_result <- peek p_st_result
301 result <- deRefStablePtr st_result
302 freeStablePtr st_result
303 return (Right result)
305 return (Left (fromIntegral stat))
307 foreign import "rts_evalStableIO" {- safe -}
308 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
309 -- more informative than the C type!
312 -----------------------------------------------------------------------------
313 -- cmTypeOfExpr: returns a string representing the type of an expression
315 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
316 cmTypeOfExpr cmstate expr
317 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
320 Nothing -> return Nothing
321 Just ty -> return (Just res_str)
323 res_str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
324 unqual = icPrintUnqual (cm_ic cmstate)
325 tidy_ty = tidyType emptyTidyEnv ty
328 -----------------------------------------------------------------------------
329 -- cmKindOfType: returns a string representing the kind of a type
331 cmKindOfType :: CmState -> String -> IO (Maybe String)
332 cmKindOfType cmstate str
333 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
335 Nothing -> return Nothing
336 Just kind -> return (Just res_str)
338 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
339 unqual = icPrintUnqual (cm_ic cmstate)
341 -----------------------------------------------------------------------------
342 -- cmTypeOfName: returns a string representing the type of a name.
344 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
345 cmTypeOfName CmState{ cm_ic=ic } name
347 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
348 case lookupNameEnv (ic_type_env ic) name of
349 Nothing -> return Nothing
350 Just (AnId id) -> return (Just str)
352 unqual = icPrintUnqual ic
353 ty = tidyType emptyTidyEnv (idType id)
354 str = showSDocForUser unqual (ppr ty)
356 _ -> panic "cmTypeOfName"
358 -----------------------------------------------------------------------------
359 -- cmCompileExpr: compile an expression and deliver an HValue
361 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
362 cmCompileExpr cmstate expr
365 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
366 ("let __cmCompileExpr = "++expr)
369 Nothing -> return Nothing
370 Just (new_ic, names, hval) -> do
373 hvals <- (unsafeCoerce# hval) :: IO [HValue]
375 case (names,hvals) of
376 ([n],[hv]) -> return (Just hv)
377 _ -> panic "cmCompileExpr"
383 %************************************************************************
385 Loading and unloading
387 %************************************************************************
390 -----------------------------------------------------------------------------
391 -- Unload the compilation manager's state: everything it knows about the
392 -- current collection of modules in the Home package.
394 cmUnload :: CmState -> IO CmState
395 cmUnload state@CmState{ cm_hsc = hsc_env }
396 = do -- Throw away the old home dir cache
399 -- Unload everything the linker knows about
402 -- Start with a fresh CmState, but keep the PersistentCompilerState
403 return (discardCMInfo state)
405 cm_unload hsc_env linkables
406 = case hsc_mode hsc_env of
409 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
411 Interactive -> panic "unload: no interpreter"
415 -----------------------------------------------------------------------------
416 -- Trace dependency graph
418 -- This is a seperate pass so that the caller can back off and keep
419 -- the current state if the downsweep fails. Typically the caller
420 -- might go cmDepAnal
423 -- He wants to do the dependency analysis before the unload, so that
424 -- if the former fails he can use the later
426 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
427 cmDepAnal cmstate rootnames
428 = do showPass dflags "Chasing dependencies"
429 when (verbosity dflags >= 1 && gmode == Batch) $
430 hPutStrLn stderr (showSDoc (hcat [
431 text "Chasing modules from: ",
432 hcat (punctuate comma (map text rootnames))]))
433 downsweep rootnames (cm_mg cmstate)
435 hsc_env = cm_hsc cmstate
436 dflags = hsc_dflags hsc_env
437 gmode = hsc_mode hsc_env
439 -----------------------------------------------------------------------------
440 -- The real business of the compilation manager: given a system state and
441 -- a module name, try and bring the module up to date, probably changing
442 -- the system state at the same time.
444 cmLoadModules :: CmState -- The HPT may not be as up to date
445 -> ModuleGraph -- Bang up to date
446 -> IO (CmState, -- new state
447 SuccessFlag, -- was successful
448 [String]) -- list of modules loaded
450 cmLoadModules cmstate1 mg2unsorted
451 = do -- version 1's are the original, before downsweep
452 let hsc_env = cm_hsc cmstate1
453 let hpt1 = hsc_HPT hsc_env
454 let ghci_mode = hsc_mode hsc_env -- this never changes
455 let dflags = hsc_dflags hsc_env -- this never changes
457 -- Do the downsweep to reestablish the module graph
458 let verb = verbosity dflags
460 -- Find out if we have a Main module
461 mb_main_mod <- readIORef v_MainModIs
463 main_mod = mb_main_mod `orElse` "Main"
465 = any ((==main_mod).moduleNameUserString.modSummaryName)
468 let mg2unsorted_names = map modSummaryName mg2unsorted
470 -- reachable_from follows source as well as normal imports
471 let reachable_from :: ModuleName -> [ModuleName]
472 reachable_from = downwards_closure_of_module mg2unsorted
474 -- should be cycle free; ignores 'import source's
475 let mg2 = topological_sort False mg2unsorted
476 -- ... whereas this takes them into account. Used for
477 -- backing out partially complete cycles following a failed
478 -- upsweep, and for removing from hpt all the modules
479 -- not in strict downwards closure, during calls to compile.
480 let mg2_with_srcimps = topological_sort True mg2unsorted
482 -- Sort out which linkables we wish to keep in the unlinked image.
483 -- See getValidLinkables below for details.
484 (valid_old_linkables, new_linkables)
485 <- getValidLinkables ghci_mode (hptLinkables hpt1)
486 mg2unsorted_names mg2_with_srcimps
488 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
490 -- Uniq of ModuleName is the same as Module, fortunately...
491 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
492 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
494 -- When (verb >= 2) $
495 -- putStrLn (showSDoc (text "Valid linkables:"
496 -- <+> ppr valid_linkables))
498 -- Figure out a stable set of modules which can be retained
499 -- the top level envs, to avoid upsweeping them. Goes to a
500 -- bit of trouble to avoid upsweeping module cycles.
502 -- Construct a set S of stable modules like this:
503 -- Travel upwards, over the sccified graph. For each scc
504 -- of modules ms, add ms to S only if:
505 -- 1. All home imports of ms are either in ms or S
506 -- 2. A valid old linkable exists for each module in ms
508 stable_mods <- preUpsweep valid_old_linkables
509 mg2unsorted_names [] mg2_with_srcimps
512 = concatMap (findInSummaries mg2unsorted) stable_mods
515 = filter (\m -> linkableModName m `elem` stable_mods)
519 hPutStrLn stderr (showSDoc (text "Stable modules:"
520 <+> sep (map (text.moduleNameUserString) stable_mods)))
522 -- Unload any modules which are going to be re-linked this
524 cm_unload hsc_env2 stable_linkables
526 -- we can now glom together our linkable sets
527 let valid_linkables = valid_old_linkables ++ new_linkables
529 -- We could at this point detect cycles which aren't broken by
530 -- a source-import, and complain immediately, but it seems better
531 -- to let upsweep_mods do this, so at least some useful work gets
532 -- done before the upsweep is abandoned.
534 = filter (\scc -> any (`notElem` stable_mods)
535 (map modSummaryName (flattenSCC scc)))
538 --hPutStrLn stderr "after tsort:\n"
539 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
541 -- Because we don't take into account source imports when doing
542 -- the topological sort, there shouldn't be any cycles in mg2.
543 -- If there is, we complain and give up -- the user needs to
544 -- break the cycle using a boot file.
546 -- Now do the upsweep, calling compile for each module in
547 -- turn. Final result is version 3 of everything.
549 -- clean up between compilations
550 let cleanup = cleanTempFilesExcept verb
551 (ppFilesFromSummaries (flattenSCCs mg2))
553 (upsweep_ok, hsc_env3, modsUpswept)
554 <- upsweep_mods hsc_env2 valid_linkables reachable_from
555 cleanup upsweep_these
557 -- At this point, modsUpswept and newLis should have the same
558 -- length, so there is one new (or old) linkable for each
559 -- mod which was processed (passed to compile).
561 -- Make modsDone be the summaries for each home module now
562 -- available; this should equal the domain of hpt3.
563 -- (NOT STRICTLY TRUE if an interactive session was started
564 -- with some object on disk ???)
565 -- Get in in a roughly top .. bottom order (hence reverse).
567 let modsDone = reverse modsUpswept ++ stable_summaries
569 -- Try and do linking in some form, depending on whether the
570 -- upsweep was completely or only partially successful.
572 if succeeded upsweep_ok
575 -- Easy; just relink it all.
576 do when (verb >= 2) $
577 hPutStrLn stderr "Upsweep completely successful."
579 -- clean up after ourselves
580 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
582 ofile <- readIORef v_Output_file
583 no_hs_main <- readIORef v_NoHsMain
585 -- Issue a warning for the confusing case where the user
586 -- said '-o foo' but we're not going to do any linking.
587 -- We attempt linking if either (a) one of the modules is
588 -- called Main, or (b) the user said -no-hs-main, indicating
589 -- that main() is going to come from somewhere else.
591 let do_linking = a_root_is_Main || no_hs_main
592 when (ghci_mode == Batch && isJust ofile && not do_linking
594 hPutStrLn stderr ("Warning: output was redirected with -o, but no output will be generated\nbecause there is no " ++ main_mod ++ " module.")
596 -- link everything together
597 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
599 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
600 cmLoadFinish Succeeded linkresult cmstate3
603 -- Tricky. We need to back out the effects of compiling any
604 -- half-done cycles, both so as to clean up the top level envs
605 -- and to avoid telling the interactive linker to link them.
606 do when (verb >= 2) $
607 hPutStrLn stderr "Upsweep partially successful."
610 = map modSummaryName modsDone
611 let mods_to_zap_names
612 = findPartiallyCompletedCycles modsDone_names
615 = filter ((`notElem` mods_to_zap_names).modSummaryName)
618 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
621 -- Clean up after ourselves
622 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
624 -- Link everything together
625 linkresult <- link ghci_mode dflags False hpt4
627 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
628 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
629 cmLoadFinish Failed linkresult cmstate3
632 -- Finish up after a cmLoad.
634 -- If the link failed, unload everything and return.
635 cmLoadFinish ok Failed cmstate
636 = do cm_unload (cm_hsc cmstate) []
637 return (discardCMInfo cmstate, Failed, [])
639 -- Empty the interactive context and set the module context to the topmost
640 -- newly loaded module, or the Prelude if none were loaded.
641 cmLoadFinish ok Succeeded cmstate
642 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
643 mods_loaded = map (moduleNameUserString.modSummaryName)
646 return (new_cmstate, ok, mods_loaded)
648 -- used to fish out the preprocess output files for the purposes of
649 -- cleaning up. The preprocessed file *might* be the same as the
650 -- source file, but that doesn't do any harm.
651 ppFilesFromSummaries summaries
652 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
654 -----------------------------------------------------------------------------
657 -- For each module (or SCC of modules), we take:
659 -- - an on-disk linkable, if this is the first time around and one
662 -- - the old linkable, otherwise (and if one is available).
664 -- and we throw away the linkable if it is older than the source file.
665 -- In interactive mode, we also ignore the on-disk linkables unless
666 -- all of the dependents of this SCC also have on-disk linkables (we
667 -- can't have dynamically loaded objects that depend on interpreted
670 -- If a module has a valid linkable, then it may be STABLE (see below),
671 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
674 -- ToDo: this pass could be merged with the preUpsweep.
678 -> [Linkable] -- old linkables
679 -> [ModuleName] -- all home modules
680 -> [SCC ModSummary] -- all modules in the program, dependency order
681 -> IO ( [Linkable], -- still-valid linkables
682 [Linkable] -- new linkables we just found
685 getValidLinkables mode old_linkables all_home_mods module_graph = do
686 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
688 return (partition_it ls [] [])
690 partition_it [] valid new = (valid,new)
691 partition_it ((l,b):ls) valid new
692 | b = partition_it ls valid (l:new)
693 | otherwise = partition_it ls (l:valid) new
696 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
698 scc = flattenSCC scc0
699 scc_names = map modSummaryName scc
700 home_module m = m `elem` all_home_mods && m `notElem` scc_names
701 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
702 -- NB. ms_imps, not ms_allimps above. We don't want to
703 -- force a module's SOURCE imports to be already compiled for
704 -- its object linkable to be valid.
707 case findModuleLinkable_maybe (map fst new_linkables) m of
709 Just l -> isObjectLinkable l
711 objects_allowed = mode == Batch || all has_object scc_allhomeimps
715 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
717 -- since an scc can contain only all objects or no objects at all,
718 -- we have to check whether we got all objects or not, and re-do
719 -- the linkable check if not.
722 && not (all isObjectLinkable (map fst new_linkables'))
723 then foldM (getValidLinkable old_linkables False) [] scc
724 else return new_linkables'
726 return (new_linkables ++ new_linkables')
729 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
730 -> IO [(Linkable,Bool)]
731 -- True <=> linkable is new; i.e. freshly discovered on the disk
732 -- presumably generated 'on the side'
733 -- by a separate GHC run
734 getValidLinkable old_linkables objects_allowed new_linkables summary
735 -- 'objects_allowed' says whether we permit this module to
736 -- have a .o-file linkable. We only permit it if all the
737 -- modules it depends on also have .o files; a .o file can't
738 -- link to a bytecode module
739 = do let mod_name = modSummaryName summary
742 <- if (not objects_allowed)
745 else findLinkable mod_name (ms_location summary)
747 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
750 case (old_linkable, maybe_disk_linkable) of
751 (Nothing, Nothing) -> []
753 -- new object linkable just appeared
754 (Nothing, Just l) -> up_to_date l True
757 | isObjectLinkable l -> []
758 -- object linkable disappeared! In case we need to
759 -- relink the module, disregard the old linkable and
760 -- just interpret the module from now on.
761 | otherwise -> up_to_date l False
762 -- old byte code linkable
765 | not (isObjectLinkable l) -> up_to_date l False
766 -- if the previous linkable was interpreted, then we
767 -- ignore a newly compiled version, because the version
768 -- numbers in the interface file will be out-of-sync with
769 -- our internal ones.
770 | linkableTime l' > linkableTime l -> up_to_date l' True
771 | linkableTime l' == linkableTime l -> up_to_date l False
773 -- on-disk linkable has been replaced by an older one!
774 -- again, disregard the previous one.
777 | linkableTime l < ms_hs_date summary = []
778 | otherwise = [(l,b)]
779 -- why '<' rather than '<=' above? If the filesystem stores
780 -- times to the nearset second, we may occasionally find that
781 -- the object & source have the same modification time,
782 -- especially if the source was automatically generated
783 -- and compiled. Using >= is slightly unsafe, but it matches
786 return (new_linkables' ++ new_linkables)
789 hptLinkables :: HomePackageTable -> [Linkable]
790 -- Get all the linkables from the home package table, one for each module
791 -- Once the HPT is up to date, these are the ones we should link
792 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
795 -----------------------------------------------------------------------------
796 -- Do a pre-upsweep without use of "compile", to establish a
797 -- (downward-closed) set of stable modules for which we won't call compile.
800 -- * has a valid linkable (see getValidLinkables above)
801 -- * depends only on stable modules
802 -- * has an interface in the HPT (interactive mode only)
804 preUpsweep :: [Linkable] -- new valid linkables
805 -> [ModuleName] -- names of all mods encountered in downsweep
806 -> [ModuleName] -- accumulating stable modules
807 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
808 -> IO [ModuleName] -- stable modules
810 preUpsweep valid_lis all_home_mods stable [] = return stable
811 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
812 = do let scc = flattenSCC scc0
813 scc_allhomeimps :: [ModuleName]
815 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
816 all_imports_in_scc_or_stable
817 = all in_stable_or_scc scc_allhomeimps
819 = map modSummaryName scc
821 = m `elem` scc_names || m `elem` stable
823 -- now we check for valid linkables: each module in the SCC must
824 -- have a valid linkable (see getValidLinkables above).
825 has_valid_linkable new_summary
826 = isJust (findModuleLinkable_maybe valid_lis modname)
827 where modname = modSummaryName new_summary
829 scc_is_stable = all_imports_in_scc_or_stable
830 && all has_valid_linkable scc
833 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
834 else preUpsweep valid_lis all_home_mods stable sccs
837 -- Helper for preUpsweep. Assuming that new_summary's imports are all
838 -- stable (in the sense of preUpsweep), determine if new_summary is itself
839 -- stable, and, if so, in batch mode, return its linkable.
840 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
841 findInSummaries old_summaries mod_name
842 = [s | s <- old_summaries, modSummaryName s == mod_name]
844 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
845 findModInSummaries old_summaries mod
846 = case [s | s <- old_summaries, ms_mod s == mod] of
850 -- Return (names of) all those in modsDone who are part of a cycle
851 -- as defined by theGraph.
852 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
853 findPartiallyCompletedCycles modsDone theGraph
857 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
858 chew ((CyclicSCC vs):rest)
859 = let names_in_this_cycle = nub (map modSummaryName vs)
861 = nub ([done | done <- modsDone,
862 done `elem` names_in_this_cycle])
863 chewed_rest = chew rest
865 if notNull mods_in_this_cycle
866 && length mods_in_this_cycle < length names_in_this_cycle
867 then mods_in_this_cycle ++ chewed_rest
871 -- Compile multiple modules, stopping as soon as an error appears.
872 -- There better had not be any cyclic groups here -- we check for them.
873 upsweep_mods :: HscEnv -- Includes up-to-date HPT
874 -> [Linkable] -- Valid linkables
875 -> (ModuleName -> [ModuleName]) -- to construct downward closures
876 -> IO () -- how to clean up unwanted tmp files
877 -> [SCC ModSummary] -- mods to do (the worklist)
878 -- ...... RETURNING ......
880 HscEnv, -- With an updated HPT
881 [ModSummary]) -- Mods which succeeded
883 upsweep_mods hsc_env oldUI reachable_from cleanup
885 = return (Succeeded, hsc_env, [])
887 upsweep_mods hsc_env oldUI reachable_from cleanup
889 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
890 unwords (map (moduleNameUserString.modSummaryName) ms))
891 return (Failed, hsc_env, [])
893 upsweep_mods hsc_env oldUI reachable_from cleanup
894 ((AcyclicSCC mod):mods)
895 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
896 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
898 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
899 (reachable_from (modSummaryName mod))
901 cleanup -- Remove unwanted tmp files between compilations
903 if failed ok_flag then
904 return (Failed, hsc_env1, [])
906 (restOK, hsc_env2, modOKs)
907 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
908 return (restOK, hsc_env2, mod:modOKs)
911 -- Compile a single module. Always produce a Linkable for it if
912 -- successful. If no compilation happened, return the old Linkable.
913 upsweep_mod :: HscEnv
918 HscEnv) -- With updated HPT
920 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
922 let this_mod = ms_mod summary1
923 location = ms_location summary1
924 mod_name = moduleName this_mod
925 hpt1 = hsc_HPT hsc_env
927 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
928 Just mod_info -> Just (hm_iface mod_info)
931 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
932 source_unchanged = isJust maybe_old_linkable
934 reachable_only = filter (/= mod_name) reachable_inc_me
936 -- In interactive mode, all home modules below us *must* have an
937 -- interface in the HPT. We never demand-load home interfaces in
940 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
941 retainInTopLevelEnvs reachable_only hpt1
942 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
944 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
947 | Just l <- maybe_old_linkable, isObjectLinkable l = True
950 compresult <- compile hsc_env_strictDC this_mod location
951 (ms_hs_date summary1)
952 source_unchanged have_object mb_old_iface
956 -- Compilation "succeeded", and may or may not have returned a new
957 -- linkable (depending on whether compilation was actually performed
959 CompOK new_details new_globals new_iface maybe_new_linkable
961 new_linkable = maybe_new_linkable `orElse` old_linkable
962 new_info = HomeModInfo { hm_iface = new_iface,
963 hm_globals = new_globals,
964 hm_details = new_details,
965 hm_linkable = new_linkable }
966 hpt2 = extendModuleEnv hpt1 this_mod new_info
968 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
970 -- Compilation failed. Compile may still have updated the PCS, tho.
971 CompErrs -> return (Failed, hsc_env)
973 -- Filter modules in the HPT
974 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
975 retainInTopLevelEnvs keep_these hpt
976 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
978 maybeLookupUFM ufm u = case lookupUFM ufm u of
980 Just val -> [(u, val)]
982 -- Needed to clean up HPT so that we don't get duplicates in inst env
983 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
984 downwards_closure_of_module summaries root
985 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
986 toEdge summ = (modSummaryName summ,
987 filter (`elem` all_mods) (ms_allimps summ))
989 all_mods = map modSummaryName summaries
991 res = simple_transitive_closure (map toEdge summaries) [root]
993 -- trace (showSDoc (text "DC of mod" <+> ppr root
994 -- <+> text "=" <+> ppr res)) $
997 -- Calculate transitive closures from a set of roots given an adjacency list
998 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
999 simple_transitive_closure graph set
1000 = let set2 = nub (concatMap dsts set ++ set)
1001 dsts node = fromMaybe [] (lookup node graph)
1003 if length set == length set2
1005 else simple_transitive_closure graph set2
1008 -- Calculate SCCs of the module graph, with or without taking into
1009 -- account source imports.
1010 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1011 topological_sort include_source_imports summaries
1013 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1015 = (summ, modSummaryName summ,
1016 (if include_source_imports
1017 then ms_srcimps summ else []) ++ ms_imps summ)
1019 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1020 mash_edge (summ, m, m_imports)
1021 = case lookup m key_map of
1022 Nothing -> panic "reverse_topological_sort"
1023 Just mk -> (summ, mk,
1024 -- ignore imports not from the home package
1025 mapCatMaybes (flip lookup key_map) m_imports)
1027 edges = map toEdge summaries
1028 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1029 scc_input = map mash_edge edges
1030 sccs = stronglyConnComp scc_input
1035 -----------------------------------------------------------------------------
1036 -- Downsweep (dependency analysis)
1038 -- Chase downwards from the specified root set, returning summaries
1039 -- for all home modules encountered. Only follow source-import
1042 -- We pass in the previous collection of summaries, which is used as a
1043 -- cache to avoid recalculating a module summary if the source is
1046 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1047 downsweep roots old_summaries
1048 = do rootSummaries <- mapM getRootSummary roots
1049 checkDuplicates rootSummaries
1051 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1052 (ms_imps m)) rootSummaries))
1053 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1054 let mod = ms_mod s, isHomeModule mod
1056 return all_summaries
1058 getRootSummary :: FilePath -> IO ModSummary
1060 | isHaskellSrcFilename file
1061 = do exists <- doesFileExist file
1062 if exists then summariseFile file else do
1063 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1065 = do exists <- doesFileExist hs_file
1066 if exists then summariseFile hs_file else do
1067 exists <- doesFileExist lhs_file
1068 if exists then summariseFile lhs_file else do
1069 let mod_name = mkModuleName file
1070 maybe_summary <- getSummary (file, mod_name)
1071 case maybe_summary of
1072 Nothing -> packageModErr mod_name
1075 hs_file = file ++ ".hs"
1076 lhs_file = file ++ ".lhs"
1078 -- In a root module, the filename is allowed to diverge from the module
1079 -- name, so we have to check that there aren't multiple root files
1080 -- defining the same module (otherwise the duplicates will be silently
1081 -- ignored, leading to confusing behaviour).
1082 checkDuplicates :: [ModSummary] -> IO ()
1083 checkDuplicates summaries = mapM_ check summaries
1088 many -> multiRootsErr modl many
1089 where modl = ms_mod summ
1091 [ fromJust (ml_hs_file (ms_location summ'))
1092 | summ' <- summaries, ms_mod summ' == modl ]
1094 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1095 getSummary (currentMod,nm)
1096 = do found <- findModule nm
1098 Right (mod, location) -> do
1099 let old_summary = findModInSummaries old_summaries mod
1100 summarise mod location old_summary
1103 dflags <- getDynFlags
1104 throwDyn (noModError dflags currentMod nm files)
1106 -- loop invariant: env doesn't contain package modules
1107 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1108 loop [] env = return (moduleEnvElts env)
1110 = do -- imports for modules we don't already have
1111 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1114 needed_summaries <- mapM getSummary needed_imps
1116 -- get just the "home" modules
1117 let new_home_summaries = [ s | Just s <- needed_summaries ]
1119 -- loop, checking the new imports
1120 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1121 (ms_imps m)) new_home_summaries)
1122 loop new_imps (extendModuleEnvList env
1123 [ (ms_mod s, s) | s <- new_home_summaries ])
1125 -- ToDo: we don't have a proper line number for this error
1126 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1127 hang (text loc <> colon) 4 $
1128 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1132 | verbosity dflags < 3 =
1133 text "(use -v to see a list of the files searched for)"
1135 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1137 -----------------------------------------------------------------------------
1138 -- Summarising modules
1140 -- We have two types of summarisation:
1142 -- * Summarise a file. This is used for the root module(s) passed to
1143 -- cmLoadModules. The file is read, and used to determine the root
1144 -- module name. The module name may differ from the filename.
1146 -- * Summarise a module. We are given a module name, and must provide
1147 -- a summary. The finder is used to locate the file in which the module
1150 summariseFile :: FilePath -> IO ModSummary
1152 = do hspp_fn <- preprocess file
1153 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1155 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1156 the_imps = filter (/= gHC_PRIM_Name) imps
1158 (mod, location) <- mkHomeModLocation mod_name file
1161 <- case ml_hs_file location of
1162 Nothing -> noHsFileErr mod_name
1163 Just src_fn -> getModificationTime src_fn
1165 return (ModSummary { ms_mod = mod,
1166 ms_location = location{ml_hspp_file=Just hspp_fn},
1167 ms_srcimps = srcimps, ms_imps = the_imps,
1168 ms_hs_date = src_timestamp })
1170 -- Summarise a module, and pick up source and timestamp.
1171 summarise :: Module -> ModLocation -> Maybe ModSummary
1172 -> IO (Maybe ModSummary)
1173 summarise mod location old_summary
1174 | not (isHomeModule mod) = return Nothing
1176 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1178 case ml_hs_file location of {
1179 Nothing -> noHsFileErr mod;
1182 src_timestamp <- getModificationTime src_fn
1184 -- return the cached summary if the source didn't change
1185 case old_summary of {
1186 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1189 hspp_fn <- preprocess hs_fn
1190 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1192 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1193 the_imps = filter (/= gHC_PRIM_Name) imps
1195 when (mod_name /= moduleName mod) $
1196 throwDyn (ProgramError
1197 (showSDoc (text hs_fn
1198 <> text ": file name does not match module name"
1199 <+> quotes (ppr (moduleName mod)))))
1201 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1202 srcimps the_imps src_timestamp))
1208 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1211 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1212 quotes (ppr mod) <+>
1213 text "is a package module")))
1215 multiRootsErr mod files
1216 = throwDyn (ProgramError (showSDoc (
1217 text "module" <+> quotes (ppr mod) <+>
1218 text "is defined in multiple files:" <+>
1219 sep (map text files))))
1223 %************************************************************************
1227 %************************************************************************
1230 -- The ModLocation contains both the original source filename and the
1231 -- filename of the cleaned-up source file after all preprocessing has been
1232 -- done. The point is that the summariser will have to cpp/unlit/whatever
1233 -- all files anyway, and there's no point in doing this twice -- just
1234 -- park the result in a temp file, put the name of it in the location,
1235 -- and let @compile@ read from that file on the way back up.
1238 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1240 emptyMG :: ModuleGraph
1245 ms_mod :: Module, -- name, package
1246 ms_location :: ModLocation, -- location
1247 ms_srcimps :: [ModuleName], -- source imports
1248 ms_imps :: [ModuleName], -- non-source imports
1249 ms_hs_date :: ClockTime -- timestamp of summarised file
1252 instance Outputable ModSummary where
1254 = sep [text "ModSummary {",
1255 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1256 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1257 text "ms_imps =" <+> ppr (ms_imps ms),
1258 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1262 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1264 modSummaryName :: ModSummary -> ModuleName
1265 modSummaryName = moduleName . ms_mod