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)
47 findModuleLinkable_maybe, -- Exported to InteractiveUI
50 cmGetBindings, -- :: CmState -> [TyThing]
51 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
53 sandboxIO -- Should be somewhere else
58 #include "HsVersions.h"
60 import DriverPipeline ( CompResult(..), preprocess, compile, link )
61 import HscMain ( newHscEnv )
62 import DriverState ( v_Output_file, v_NoHsMain )
66 import PrelNames ( gHC_PRIM_Name )
67 import Module ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
68 ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
69 extendModuleEnvList, extendModuleEnv,
74 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
75 import ErrUtils ( showPass )
76 import SysTools ( cleanTempFilesExcept )
77 import BasicTypes ( SuccessFlag(..), succeeded, failed )
81 import CmdLineOpts ( DynFlags(..), getDynFlags )
82 import Maybes ( expectJust, orElse, mapCatMaybes )
84 import DATA_IOREF ( readIORef )
87 import HscMain ( hscThing, hscStmt, hscTcExpr )
88 import TcRnDriver ( mkExportEnv, getModuleContents )
89 import IfaceSyn ( IfaceDecl )
93 import Type ( tidyType )
94 import VarEnv ( emptyTidyEnv )
95 import BasicTypes ( Fixity )
96 import Linker ( HValue, unload, extendLinkEnv )
97 import GHC.Exts ( unsafeCoerce# )
99 import Control.Exception as Exception ( Exception, try )
102 import EXCEPTION ( throwDyn )
105 import Directory ( getModificationTime, doesFileExist )
110 import Time ( ClockTime )
115 -- Persistent state for the entire system
118 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
184 export_env <- mkExportEnv (cm_hsc cmstate)
185 (map mkModuleName exports)
187 putStrLn (showSDoc (text "export env" $$ ppr export_env))
188 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
189 ic_exports = exports,
190 ic_rn_gbl_env = export_env } }
192 cmGetContext :: CmState -> IO ([String],[String])
193 cmGetContext CmState{cm_ic=ic} =
194 return (ic_toplev_scope ic, ic_exports ic)
196 cmModuleIsInterpreted :: CmState -> String -> IO Bool
197 cmModuleIsInterpreted cmstate str
198 = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
199 Just details -> return (isJust (hm_globals details))
200 _not_a_home_module -> return False
202 -----------------------------------------------------------------------------
203 cmSetDFlags :: CmState -> DynFlags -> CmState
204 cmSetDFlags cm_state dflags
205 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
207 -----------------------------------------------------------------------------
208 -- cmInfoThing: convert a String to a TyThing
210 -- A string may refer to more than one TyThing (eg. a constructor,
211 -- and type constructor), so we return a list of all the possible TyThings.
213 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity)]
214 cmInfoThing cmstate id
215 = hscThing (cm_hsc cmstate) (cm_ic cmstate) id
217 -- ---------------------------------------------------------------------------
218 -- cmBrowseModule: get all the TyThings defined in a module
220 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
221 cmBrowseModule cmstate str exports_only
222 = getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
223 (mkModuleName str) exports_only
226 -----------------------------------------------------------------------------
227 -- cmRunStmt: Run a statement/expr.
230 = CmRunOk [Name] -- names bound by this evaluation
232 | CmRunException Exception -- statement raised an exception
234 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
235 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
237 maybe_stuff <- hscStmt hsc_env icontext expr
240 Nothing -> return (cmstate, CmRunFailed)
241 Just (new_ic, names, hval) -> do
243 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
244 either_hvals <- sandboxIO thing_to_run
248 -- on error, keep the *old* interactive context,
249 -- so that 'it' is not bound to something
250 -- that doesn't exist.
251 return ( cmstate, CmRunException e )
254 -- Get the newly bound things, and bind them.
255 -- Don't need to delete any shadowed bindings;
256 -- the new ones override the old ones.
257 extendLinkEnv (zip names hvals)
259 return (cmstate{ cm_ic=new_ic },
263 -- We run the statement in a "sandbox" to protect the rest of the
264 -- system from anything the expression might do. For now, this
265 -- consists of just wrapping it in an exception handler, but see below
266 -- for another version.
268 sandboxIO :: IO a -> IO (Either Exception a)
269 sandboxIO thing = Exception.try thing
272 -- This version of sandboxIO runs the expression in a completely new
273 -- RTS main thread. It is disabled for now because ^C exceptions
274 -- won't be delivered to the new thread, instead they'll be delivered
275 -- to the (blocked) GHCi main thread.
277 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
279 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
281 st_thing <- newStablePtr (Exception.try thing)
282 alloca $ \ p_st_result -> do
283 stat <- rts_evalStableIO st_thing p_st_result
284 freeStablePtr st_thing
286 then do st_result <- peek p_st_result
287 result <- deRefStablePtr st_result
288 freeStablePtr st_result
289 return (Right result)
291 return (Left (fromIntegral stat))
293 foreign import "rts_evalStableIO" {- safe -}
294 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
295 -- more informative than the C type!
298 -----------------------------------------------------------------------------
299 -- cmTypeOfExpr: returns a string representing the type of an expression
301 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
302 cmTypeOfExpr cmstate expr
303 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
306 Nothing -> return Nothing
307 Just ty -> return (Just str)
309 str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
310 unqual = icPrintUnqual (cm_ic cmstate)
311 tidy_ty = tidyType emptyTidyEnv ty
314 -----------------------------------------------------------------------------
315 -- cmTypeOfName: returns a string representing the type of a name.
317 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
318 cmTypeOfName CmState{ cm_ic=ic } name
320 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
321 case lookupNameEnv (ic_type_env ic) name of
322 Nothing -> return Nothing
323 Just (AnId id) -> return (Just str)
325 unqual = icPrintUnqual ic
326 ty = tidyType emptyTidyEnv (idType id)
327 str = showSDocForUser unqual (ppr ty)
329 _ -> panic "cmTypeOfName"
331 -----------------------------------------------------------------------------
332 -- cmCompileExpr: compile an expression and deliver an HValue
334 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
335 cmCompileExpr cmstate expr
338 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
339 ("let __cmCompileExpr = "++expr)
342 Nothing -> return Nothing
343 Just (new_ic, names, hval) -> do
346 hvals <- (unsafeCoerce# hval) :: IO [HValue]
348 case (names,hvals) of
349 ([n],[hv]) -> return (Just hv)
350 _ -> panic "cmCompileExpr"
356 %************************************************************************
358 Loading and unloading
360 %************************************************************************
363 -----------------------------------------------------------------------------
364 -- Unload the compilation manager's state: everything it knows about the
365 -- current collection of modules in the Home package.
367 cmUnload :: CmState -> IO CmState
368 cmUnload state@CmState{ cm_hsc = hsc_env }
369 = do -- Throw away the old home dir cache
372 -- Unload everything the linker knows about
375 -- Start with a fresh CmState, but keep the PersistentCompilerState
376 return (discardCMInfo state)
378 cm_unload hsc_env linkables
379 = case hsc_mode hsc_env of
382 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
384 Interactive -> panic "unload: no interpreter"
388 -----------------------------------------------------------------------------
389 -- Trace dependency graph
391 -- This is a seperate pass so that the caller can back off and keep
392 -- the current state if the downsweep fails. Typically the caller
393 -- might go cmDepAnal
396 -- He wants to do the dependency analysis before the unload, so that
397 -- if the former fails he can use the later
399 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
400 cmDepAnal cmstate rootnames
401 = do showPass dflags "Chasing dependencies"
402 when (verbosity dflags >= 1 && gmode == Batch) $
403 hPutStrLn stderr (showSDoc (hcat [
404 text "Chasing modules from: ",
405 hcat (punctuate comma (map text rootnames))]))
406 downsweep rootnames (cm_mg cmstate)
408 hsc_env = cm_hsc cmstate
409 dflags = hsc_dflags hsc_env
410 gmode = hsc_mode hsc_env
412 -----------------------------------------------------------------------------
413 -- The real business of the compilation manager: given a system state and
414 -- a module name, try and bring the module up to date, probably changing
415 -- the system state at the same time.
417 cmLoadModules :: CmState -- The HPT may not be as up to date
418 -> ModuleGraph -- Bang up to date
419 -> IO (CmState, -- new state
420 SuccessFlag, -- was successful
421 [String]) -- list of modules loaded
423 cmLoadModules cmstate1 mg2unsorted
424 = do -- version 1's are the original, before downsweep
425 let hsc_env = cm_hsc cmstate1
426 let hpt1 = hsc_HPT hsc_env
427 let ghci_mode = hsc_mode hsc_env -- this never changes
428 let dflags = hsc_dflags hsc_env -- this never changes
430 -- Do the downsweep to reestablish the module graph
431 let verb = verbosity dflags
433 -- Find out if we have a Main module
435 = any ((=="Main").moduleNameUserString.modSummaryName)
438 let mg2unsorted_names = map modSummaryName mg2unsorted
440 -- reachable_from follows source as well as normal imports
441 let reachable_from :: ModuleName -> [ModuleName]
442 reachable_from = downwards_closure_of_module mg2unsorted
444 -- should be cycle free; ignores 'import source's
445 let mg2 = topological_sort False mg2unsorted
446 -- ... whereas this takes them into account. Used for
447 -- backing out partially complete cycles following a failed
448 -- upsweep, and for removing from hpt all the modules
449 -- not in strict downwards closure, during calls to compile.
450 let mg2_with_srcimps = topological_sort True mg2unsorted
452 -- Sort out which linkables we wish to keep in the unlinked image.
453 -- See getValidLinkables below for details.
454 (valid_old_linkables, new_linkables)
455 <- getValidLinkables ghci_mode (hptLinkables hpt1)
456 mg2unsorted_names mg2_with_srcimps
458 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
460 -- Uniq of ModuleName is the same as Module, fortunately...
461 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
462 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
464 -- When (verb >= 2) $
465 -- putStrLn (showSDoc (text "Valid linkables:"
466 -- <+> ppr valid_linkables))
468 -- Figure out a stable set of modules which can be retained
469 -- the top level envs, to avoid upsweeping them. Goes to a
470 -- bit of trouble to avoid upsweeping module cycles.
472 -- Construct a set S of stable modules like this:
473 -- Travel upwards, over the sccified graph. For each scc
474 -- of modules ms, add ms to S only if:
475 -- 1. All home imports of ms are either in ms or S
476 -- 2. A valid old linkable exists for each module in ms
478 stable_mods <- preUpsweep valid_old_linkables
479 mg2unsorted_names [] mg2_with_srcimps
482 = concatMap (findInSummaries mg2unsorted) stable_mods
485 = filter (\m -> linkableModName m `elem` stable_mods)
489 hPutStrLn stderr (showSDoc (text "Stable modules:"
490 <+> sep (map (text.moduleNameUserString) stable_mods)))
492 -- Unload any modules which are going to be re-linked this
494 cm_unload hsc_env2 stable_linkables
496 -- we can now glom together our linkable sets
497 let valid_linkables = valid_old_linkables ++ new_linkables
499 -- We could at this point detect cycles which aren't broken by
500 -- a source-import, and complain immediately, but it seems better
501 -- to let upsweep_mods do this, so at least some useful work gets
502 -- done before the upsweep is abandoned.
504 = filter (\scc -> any (`notElem` stable_mods)
505 (map modSummaryName (flattenSCC scc)))
508 --hPutStrLn stderr "after tsort:\n"
509 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
511 -- Because we don't take into account source imports when doing
512 -- the topological sort, there shouldn't be any cycles in mg2.
513 -- If there is, we complain and give up -- the user needs to
514 -- break the cycle using a boot file.
516 -- Now do the upsweep, calling compile for each module in
517 -- turn. Final result is version 3 of everything.
519 -- clean up between compilations
520 let cleanup = cleanTempFilesExcept verb
521 (ppFilesFromSummaries (flattenSCCs mg2))
523 (upsweep_ok, hsc_env3, modsUpswept)
524 <- upsweep_mods hsc_env2 valid_linkables reachable_from
525 cleanup upsweep_these
527 -- At this point, modsUpswept and newLis should have the same
528 -- length, so there is one new (or old) linkable for each
529 -- mod which was processed (passed to compile).
531 -- Make modsDone be the summaries for each home module now
532 -- available; this should equal the domain of hpt3.
533 -- (NOT STRICTLY TRUE if an interactive session was started
534 -- with some object on disk ???)
535 -- Get in in a roughly top .. bottom order (hence reverse).
537 let modsDone = reverse modsUpswept ++ stable_summaries
539 -- Try and do linking in some form, depending on whether the
540 -- upsweep was completely or only partially successful.
542 if succeeded upsweep_ok
545 -- Easy; just relink it all.
546 do when (verb >= 2) $
547 hPutStrLn stderr "Upsweep completely successful."
549 -- clean up after ourselves
550 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
552 ofile <- readIORef v_Output_file
553 no_hs_main <- readIORef v_NoHsMain
555 -- Issue a warning for the confusing case where the user
556 -- said '-o foo' but we're not going to do any linking.
557 -- We attempt linking if either (a) one of the modules is
558 -- called Main, or (b) the user said -no-hs-main, indicating
559 -- that main() is going to come from somewhere else.
561 let do_linking = a_root_is_Main || no_hs_main
562 when (ghci_mode == Batch && isJust ofile && not do_linking
564 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
566 -- link everything together
567 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
569 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
570 cmLoadFinish Succeeded linkresult cmstate3
573 -- Tricky. We need to back out the effects of compiling any
574 -- half-done cycles, both so as to clean up the top level envs
575 -- and to avoid telling the interactive linker to link them.
576 do when (verb >= 2) $
577 hPutStrLn stderr "Upsweep partially successful."
580 = map modSummaryName modsDone
581 let mods_to_zap_names
582 = findPartiallyCompletedCycles modsDone_names
585 = filter ((`notElem` mods_to_zap_names).modSummaryName)
588 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
591 -- Clean up after ourselves
592 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
594 -- Link everything together
595 linkresult <- link ghci_mode dflags False hpt4
597 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
598 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
599 cmLoadFinish Failed linkresult cmstate3
602 -- Finish up after a cmLoad.
604 -- If the link failed, unload everything and return.
605 cmLoadFinish ok Failed cmstate
606 = do cm_unload (cm_hsc cmstate) []
607 return (discardCMInfo cmstate, Failed, [])
609 -- Empty the interactive context and set the module context to the topmost
610 -- newly loaded module, or the Prelude if none were loaded.
611 cmLoadFinish ok Succeeded cmstate
612 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
613 mods_loaded = map (moduleNameUserString.modSummaryName)
616 return (new_cmstate, ok, mods_loaded)
618 -- used to fish out the preprocess output files for the purposes of
619 -- cleaning up. The preprocessed file *might* be the same as the
620 -- source file, but that doesn't do any harm.
621 ppFilesFromSummaries summaries
622 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
624 -----------------------------------------------------------------------------
627 -- For each module (or SCC of modules), we take:
629 -- - an on-disk linkable, if this is the first time around and one
632 -- - the old linkable, otherwise (and if one is available).
634 -- and we throw away the linkable if it is older than the source file.
635 -- In interactive mode, we also ignore the on-disk linkables unless
636 -- all of the dependents of this SCC also have on-disk linkables (we
637 -- can't have dynamically loaded objects that depend on interpreted
640 -- If a module has a valid linkable, then it may be STABLE (see below),
641 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
644 -- ToDo: this pass could be merged with the preUpsweep.
648 -> [Linkable] -- old linkables
649 -> [ModuleName] -- all home modules
650 -> [SCC ModSummary] -- all modules in the program, dependency order
651 -> IO ( [Linkable], -- still-valid linkables
652 [Linkable] -- new linkables we just found
655 getValidLinkables mode old_linkables all_home_mods module_graph = do
656 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
658 return (partition_it ls [] [])
660 partition_it [] valid new = (valid,new)
661 partition_it ((l,b):ls) valid new
662 | b = partition_it ls valid (l:new)
663 | otherwise = partition_it ls (l:valid) new
666 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
668 scc = flattenSCC scc0
669 scc_names = map modSummaryName scc
670 home_module m = m `elem` all_home_mods && m `notElem` scc_names
671 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
672 -- NB. ms_imps, not ms_allimps above. We don't want to
673 -- force a module's SOURCE imports to be already compiled for
674 -- its object linkable to be valid.
677 case findModuleLinkable_maybe (map fst new_linkables) m of
679 Just l -> isObjectLinkable l
681 objects_allowed = mode == Batch || all has_object scc_allhomeimps
685 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
687 -- since an scc can contain only all objects or no objects at all,
688 -- we have to check whether we got all objects or not, and re-do
689 -- the linkable check if not.
692 && not (all isObjectLinkable (map fst new_linkables'))
693 then foldM (getValidLinkable old_linkables False) [] scc
694 else return new_linkables'
696 return (new_linkables ++ new_linkables')
699 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
700 -> IO [(Linkable,Bool)]
701 -- True <=> linkable is new; i.e. freshly discovered on the disk
702 -- presumably generated 'on the side'
703 -- by a separate GHC run
704 getValidLinkable old_linkables objects_allowed new_linkables summary
705 -- 'objects_allowed' says whether we permit this module to
706 -- have a .o-file linkable. We only permit it if all the
707 -- modules it depends on also have .o files; a .o file can't
708 -- link to a bytecode module
709 = do let mod_name = modSummaryName summary
712 <- if (not objects_allowed)
715 else findLinkable mod_name (ms_location summary)
717 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
720 case (old_linkable, maybe_disk_linkable) of
721 (Nothing, Nothing) -> []
723 -- new object linkable just appeared
724 (Nothing, Just l) -> up_to_date l True
727 | isObjectLinkable l -> []
728 -- object linkable disappeared! In case we need to
729 -- relink the module, disregard the old linkable and
730 -- just interpret the module from now on.
731 | otherwise -> up_to_date l False
732 -- old byte code linkable
735 | not (isObjectLinkable l) -> up_to_date l False
736 -- if the previous linkable was interpreted, then we
737 -- ignore a newly compiled version, because the version
738 -- numbers in the interface file will be out-of-sync with
739 -- our internal ones.
740 | linkableTime l' > linkableTime l -> up_to_date l' True
741 | linkableTime l' == linkableTime l -> up_to_date l False
743 -- on-disk linkable has been replaced by an older one!
744 -- again, disregard the previous one.
747 | linkableTime l < ms_hs_date summary = []
748 | otherwise = [(l,b)]
749 -- why '<' rather than '<=' above? If the filesystem stores
750 -- times to the nearset second, we may occasionally find that
751 -- the object & source have the same modification time,
752 -- especially if the source was automatically generated
753 -- and compiled. Using >= is slightly unsafe, but it matches
756 return (new_linkables' ++ new_linkables)
759 hptLinkables :: HomePackageTable -> [Linkable]
760 -- Get all the linkables from the home package table, one for each module
761 -- Once the HPT is up to date, these are the ones we should link
762 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
765 -----------------------------------------------------------------------------
766 -- Do a pre-upsweep without use of "compile", to establish a
767 -- (downward-closed) set of stable modules for which we won't call compile.
770 -- * has a valid linkable (see getValidLinkables above)
771 -- * depends only on stable modules
772 -- * has an interface in the HPT (interactive mode only)
774 preUpsweep :: [Linkable] -- new valid linkables
775 -> [ModuleName] -- names of all mods encountered in downsweep
776 -> [ModuleName] -- accumulating stable modules
777 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
778 -> IO [ModuleName] -- stable modules
780 preUpsweep valid_lis all_home_mods stable [] = return stable
781 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
782 = do let scc = flattenSCC scc0
783 scc_allhomeimps :: [ModuleName]
785 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
786 all_imports_in_scc_or_stable
787 = all in_stable_or_scc scc_allhomeimps
789 = map modSummaryName scc
791 = m `elem` scc_names || m `elem` stable
793 -- now we check for valid linkables: each module in the SCC must
794 -- have a valid linkable (see getValidLinkables above).
795 has_valid_linkable new_summary
796 = isJust (findModuleLinkable_maybe valid_lis modname)
797 where modname = modSummaryName new_summary
799 scc_is_stable = all_imports_in_scc_or_stable
800 && all has_valid_linkable scc
803 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
804 else preUpsweep valid_lis all_home_mods stable sccs
807 -- Helper for preUpsweep. Assuming that new_summary's imports are all
808 -- stable (in the sense of preUpsweep), determine if new_summary is itself
809 -- stable, and, if so, in batch mode, return its linkable.
810 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
811 findInSummaries old_summaries mod_name
812 = [s | s <- old_summaries, modSummaryName s == mod_name]
814 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
815 findModInSummaries old_summaries mod
816 = case [s | s <- old_summaries, ms_mod s == mod] of
820 -- Return (names of) all those in modsDone who are part of a cycle
821 -- as defined by theGraph.
822 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
823 findPartiallyCompletedCycles modsDone theGraph
827 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
828 chew ((CyclicSCC vs):rest)
829 = let names_in_this_cycle = nub (map modSummaryName vs)
831 = nub ([done | done <- modsDone,
832 done `elem` names_in_this_cycle])
833 chewed_rest = chew rest
835 if notNull mods_in_this_cycle
836 && length mods_in_this_cycle < length names_in_this_cycle
837 then mods_in_this_cycle ++ chewed_rest
841 -- Compile multiple modules, stopping as soon as an error appears.
842 -- There better had not be any cyclic groups here -- we check for them.
843 upsweep_mods :: HscEnv -- Includes up-to-date HPT
844 -> [Linkable] -- Valid linkables
845 -> (ModuleName -> [ModuleName]) -- to construct downward closures
846 -> IO () -- how to clean up unwanted tmp files
847 -> [SCC ModSummary] -- mods to do (the worklist)
848 -- ...... RETURNING ......
850 HscEnv, -- With an updated HPT
851 [ModSummary]) -- Mods which succeeded
853 upsweep_mods hsc_env oldUI reachable_from cleanup
855 = return (Succeeded, hsc_env, [])
857 upsweep_mods hsc_env oldUI reachable_from cleanup
859 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
860 unwords (map (moduleNameUserString.modSummaryName) ms))
861 return (Failed, hsc_env, [])
863 upsweep_mods hsc_env oldUI reachable_from cleanup
864 ((AcyclicSCC mod):mods)
865 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
866 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
868 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
869 (reachable_from (modSummaryName mod))
871 cleanup -- Remove unwanted tmp files between compilations
873 if failed ok_flag then
874 return (Failed, hsc_env1, [])
876 (restOK, hsc_env2, modOKs)
877 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
878 return (restOK, hsc_env2, mod:modOKs)
881 -- Compile a single module. Always produce a Linkable for it if
882 -- successful. If no compilation happened, return the old Linkable.
883 upsweep_mod :: HscEnv
888 HscEnv) -- With updated HPT
890 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
892 let this_mod = ms_mod summary1
893 location = ms_location summary1
894 mod_name = moduleName this_mod
895 hpt1 = hsc_HPT hsc_env
897 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
898 Just mod_info -> Just (hm_iface mod_info)
901 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
902 source_unchanged = isJust maybe_old_linkable
904 reachable_only = filter (/= mod_name) reachable_inc_me
906 -- In interactive mode, all home modules below us *must* have an
907 -- interface in the HPT. We never demand-load home interfaces in
910 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
911 retainInTopLevelEnvs reachable_only hpt1
912 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
914 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
917 | Just l <- maybe_old_linkable, isObjectLinkable l = True
920 compresult <- compile hsc_env_strictDC this_mod location
921 source_unchanged have_object mb_old_iface
925 -- Compilation "succeeded", and may or may not have returned a new
926 -- linkable (depending on whether compilation was actually performed
928 CompOK new_details new_globals new_iface maybe_new_linkable
930 new_linkable = maybe_new_linkable `orElse` old_linkable
931 new_info = HomeModInfo { hm_iface = new_iface,
932 hm_globals = new_globals,
933 hm_details = new_details,
934 hm_linkable = new_linkable }
935 hpt2 = extendModuleEnv hpt1 this_mod new_info
937 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
939 -- Compilation failed. Compile may still have updated the PCS, tho.
940 CompErrs -> return (Failed, hsc_env)
942 -- Filter modules in the HPT
943 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
944 retainInTopLevelEnvs keep_these hpt
945 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
947 maybeLookupUFM ufm u = case lookupUFM ufm u of
949 Just val -> [(u, val)]
951 -- Needed to clean up HPT so that we don't get duplicates in inst env
952 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
953 downwards_closure_of_module summaries root
954 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
955 toEdge summ = (modSummaryName summ,
956 filter (`elem` all_mods) (ms_allimps summ))
958 all_mods = map modSummaryName summaries
960 res = simple_transitive_closure (map toEdge summaries) [root]
962 -- trace (showSDoc (text "DC of mod" <+> ppr root
963 -- <+> text "=" <+> ppr res)) $
966 -- Calculate transitive closures from a set of roots given an adjacency list
967 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
968 simple_transitive_closure graph set
969 = let set2 = nub (concatMap dsts set ++ set)
970 dsts node = fromMaybe [] (lookup node graph)
972 if length set == length set2
974 else simple_transitive_closure graph set2
977 -- Calculate SCCs of the module graph, with or without taking into
978 -- account source imports.
979 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
980 topological_sort include_source_imports summaries
982 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
984 = (summ, modSummaryName summ,
985 (if include_source_imports
986 then ms_srcimps summ else []) ++ ms_imps summ)
988 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
989 mash_edge (summ, m, m_imports)
990 = case lookup m key_map of
991 Nothing -> panic "reverse_topological_sort"
992 Just mk -> (summ, mk,
993 -- ignore imports not from the home package
994 mapCatMaybes (flip lookup key_map) m_imports)
996 edges = map toEdge summaries
997 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
998 scc_input = map mash_edge edges
999 sccs = stronglyConnComp scc_input
1004 -----------------------------------------------------------------------------
1005 -- Downsweep (dependency analysis)
1007 -- Chase downwards from the specified root set, returning summaries
1008 -- for all home modules encountered. Only follow source-import
1011 -- We pass in the previous collection of summaries, which is used as a
1012 -- cache to avoid recalculating a module summary if the source is
1015 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1016 downsweep roots old_summaries
1017 = do rootSummaries <- mapM getRootSummary roots
1018 checkDuplicates rootSummaries
1020 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1021 (ms_imps m)) rootSummaries))
1022 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1023 let mod = ms_mod s, isHomeModule mod
1025 return all_summaries
1027 getRootSummary :: FilePath -> IO ModSummary
1029 | haskellish_src_file file
1030 = do exists <- doesFileExist file
1031 if exists then summariseFile file else do
1032 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1034 = do exists <- doesFileExist hs_file
1035 if exists then summariseFile hs_file else do
1036 exists <- doesFileExist lhs_file
1037 if exists then summariseFile lhs_file else do
1038 let mod_name = mkModuleName file
1039 maybe_summary <- getSummary (file, mod_name)
1040 case maybe_summary of
1041 Nothing -> packageModErr mod_name
1044 hs_file = file ++ ".hs"
1045 lhs_file = file ++ ".lhs"
1047 -- In a root module, the filename is allowed to diverge from the module
1048 -- name, so we have to check that there aren't multiple root files
1049 -- defining the same module (otherwise the duplicates will be silently
1050 -- ignored, leading to confusing behaviour).
1051 checkDuplicates :: [ModSummary] -> IO ()
1052 checkDuplicates summaries = mapM_ check summaries
1057 many -> multiRootsErr modl many
1058 where modl = ms_mod summ
1060 [ fromJust (ml_hs_file (ms_location summ'))
1061 | summ' <- summaries, ms_mod summ' == modl ]
1063 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1064 getSummary (currentMod,nm)
1065 = do found <- findModule nm
1067 Right (mod, location) -> do
1068 let old_summary = findModInSummaries old_summaries mod
1069 summarise mod location old_summary
1072 dflags <- getDynFlags
1073 throwDyn (noModError dflags currentMod nm files)
1075 -- loop invariant: env doesn't contain package modules
1076 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1077 loop [] env = return (moduleEnvElts env)
1079 = do -- imports for modules we don't already have
1080 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1083 needed_summaries <- mapM getSummary needed_imps
1085 -- get just the "home" modules
1086 let new_home_summaries = [ s | Just s <- needed_summaries ]
1088 -- loop, checking the new imports
1089 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1090 (ms_imps m)) new_home_summaries)
1091 loop new_imps (extendModuleEnvList env
1092 [ (ms_mod s, s) | s <- new_home_summaries ])
1094 -- ToDo: we don't have a proper line number for this error
1095 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1096 hang (text loc <> colon) 4 $
1097 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1101 | verbosity dflags < 3 =
1102 text "(use -v to see a list of the files searched for)"
1104 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1106 -----------------------------------------------------------------------------
1107 -- Summarising modules
1109 -- We have two types of summarisation:
1111 -- * Summarise a file. This is used for the root module(s) passed to
1112 -- cmLoadModules. The file is read, and used to determine the root
1113 -- module name. The module name may differ from the filename.
1115 -- * Summarise a module. We are given a module name, and must provide
1116 -- a summary. The finder is used to locate the file in which the module
1119 summariseFile :: FilePath -> IO ModSummary
1121 = do hspp_fn <- preprocess file
1122 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1124 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1125 the_imps = filter (/= gHC_PRIM_Name) imps
1127 (mod, location) <- mkHomeModLocation mod_name file
1130 <- case ml_hs_file location of
1131 Nothing -> noHsFileErr mod_name
1132 Just src_fn -> getModificationTime src_fn
1134 return (ModSummary { ms_mod = mod,
1135 ms_location = location{ml_hspp_file=Just hspp_fn},
1136 ms_srcimps = srcimps, ms_imps = the_imps,
1137 ms_hs_date = src_timestamp })
1139 -- Summarise a module, and pick up source and timestamp.
1140 summarise :: Module -> ModLocation -> Maybe ModSummary
1141 -> IO (Maybe ModSummary)
1142 summarise mod location old_summary
1143 | not (isHomeModule mod) = return Nothing
1145 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1147 case ml_hs_file location of {
1148 Nothing -> noHsFileErr mod;
1151 src_timestamp <- getModificationTime src_fn
1153 -- return the cached summary if the source didn't change
1154 case old_summary of {
1155 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1158 hspp_fn <- preprocess hs_fn
1159 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1161 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1162 the_imps = filter (/= gHC_PRIM_Name) imps
1164 when (mod_name /= moduleName mod) $
1165 throwDyn (ProgramError
1166 (showSDoc (text hs_fn
1167 <> text ": file name does not match module name"
1168 <+> quotes (ppr (moduleName mod)))))
1170 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1171 srcimps the_imps src_timestamp))
1177 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1180 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1181 quotes (ppr mod) <+>
1182 text "is a package module")))
1184 multiRootsErr mod files
1185 = throwDyn (ProgramError (showSDoc (
1186 text "module" <+> quotes (ppr mod) <+>
1187 text "is defined in multiple files:" <+>
1188 sep (map text files))))
1192 %************************************************************************
1196 %************************************************************************
1199 -- The ModLocation contains both the original source filename and the
1200 -- filename of the cleaned-up source file after all preprocessing has been
1201 -- done. The point is that the summariser will have to cpp/unlit/whatever
1202 -- all files anyway, and there's no point in doing this twice -- just
1203 -- park the result in a temp file, put the name of it in the location,
1204 -- and let @compile@ read from that file on the way back up.
1207 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1209 emptyMG :: ModuleGraph
1214 ms_mod :: Module, -- name, package
1215 ms_location :: ModLocation, -- location
1216 ms_srcimps :: [ModuleName], -- source imports
1217 ms_imps :: [ModuleName], -- non-source imports
1218 ms_hs_date :: ClockTime -- timestamp of summarised file
1221 instance Outputable ModSummary where
1223 = sep [text "ModSummary {",
1224 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1225 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1226 text "ms_imps =" <+> ppr (ms_imps ms),
1227 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1231 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1233 modSummaryName :: ModSummary -> ModuleName
1234 modSummaryName = moduleName . ms_mod