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 mb_export_env <- mkExportEnv (cm_hsc cmstate)
185 (map mkModuleName exports)
187 case mb_export_env of
188 Nothing -> return cmstate -- Error already reported; do a no-op
190 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
191 ic_exports = exports,
192 ic_rn_gbl_env = export_env } }
194 cmGetContext :: CmState -> IO ([String],[String])
195 cmGetContext CmState{cm_ic=ic} =
196 return (ic_toplev_scope ic, ic_exports ic)
198 cmModuleIsInterpreted :: CmState -> String -> IO Bool
199 cmModuleIsInterpreted cmstate str
200 = case lookupModuleEnvByName (cmHPT cmstate) (mkModuleName str) of
201 Just details -> return (isJust (hm_globals details))
202 _not_a_home_module -> return False
204 -----------------------------------------------------------------------------
205 cmSetDFlags :: CmState -> DynFlags -> CmState
206 cmSetDFlags cm_state dflags
207 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
209 -----------------------------------------------------------------------------
210 -- cmInfoThing: convert a String to a TyThing
212 -- A string may refer to more than one TyThing (eg. a constructor,
213 -- and type constructor), so we return a list of all the possible TyThings.
215 cmInfoThing :: CmState -> String -> IO [(IfaceDecl,Fixity)]
216 cmInfoThing cmstate id
217 = hscThing (cm_hsc cmstate) (cm_ic cmstate) id
219 -- ---------------------------------------------------------------------------
220 -- cmBrowseModule: get all the TyThings defined in a module
222 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
223 cmBrowseModule cmstate str exports_only
224 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
225 (mkModuleName str) exports_only
227 Nothing -> return [] -- An error of some kind
232 -----------------------------------------------------------------------------
233 -- cmRunStmt: Run a statement/expr.
236 = CmRunOk [Name] -- names bound by this evaluation
238 | CmRunException Exception -- statement raised an exception
240 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
241 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
243 maybe_stuff <- hscStmt hsc_env icontext expr
246 Nothing -> return (cmstate, CmRunFailed)
247 Just (new_ic, names, hval) -> do
249 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
250 either_hvals <- sandboxIO thing_to_run
254 -- on error, keep the *old* interactive context,
255 -- so that 'it' is not bound to something
256 -- that doesn't exist.
257 return ( cmstate, CmRunException e )
260 -- Get the newly bound things, and bind them.
261 -- Don't need to delete any shadowed bindings;
262 -- the new ones override the old ones.
263 extendLinkEnv (zip names hvals)
265 return (cmstate{ cm_ic=new_ic },
269 -- We run the statement in a "sandbox" to protect the rest of the
270 -- system from anything the expression might do. For now, this
271 -- consists of just wrapping it in an exception handler, but see below
272 -- for another version.
274 sandboxIO :: IO a -> IO (Either Exception a)
275 sandboxIO thing = Exception.try thing
278 -- This version of sandboxIO runs the expression in a completely new
279 -- RTS main thread. It is disabled for now because ^C exceptions
280 -- won't be delivered to the new thread, instead they'll be delivered
281 -- to the (blocked) GHCi main thread.
283 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
285 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
287 st_thing <- newStablePtr (Exception.try thing)
288 alloca $ \ p_st_result -> do
289 stat <- rts_evalStableIO st_thing p_st_result
290 freeStablePtr st_thing
292 then do st_result <- peek p_st_result
293 result <- deRefStablePtr st_result
294 freeStablePtr st_result
295 return (Right result)
297 return (Left (fromIntegral stat))
299 foreign import "rts_evalStableIO" {- safe -}
300 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
301 -- more informative than the C type!
304 -----------------------------------------------------------------------------
305 -- cmTypeOfExpr: returns a string representing the type of an expression
307 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
308 cmTypeOfExpr cmstate expr
309 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
312 Nothing -> return Nothing
313 Just ty -> return (Just str)
315 str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
316 unqual = icPrintUnqual (cm_ic cmstate)
317 tidy_ty = tidyType emptyTidyEnv ty
320 -----------------------------------------------------------------------------
321 -- cmTypeOfName: returns a string representing the type of a name.
323 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
324 cmTypeOfName CmState{ cm_ic=ic } name
326 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
327 case lookupNameEnv (ic_type_env ic) name of
328 Nothing -> return Nothing
329 Just (AnId id) -> return (Just str)
331 unqual = icPrintUnqual ic
332 ty = tidyType emptyTidyEnv (idType id)
333 str = showSDocForUser unqual (ppr ty)
335 _ -> panic "cmTypeOfName"
337 -----------------------------------------------------------------------------
338 -- cmCompileExpr: compile an expression and deliver an HValue
340 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
341 cmCompileExpr cmstate expr
344 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
345 ("let __cmCompileExpr = "++expr)
348 Nothing -> return Nothing
349 Just (new_ic, names, hval) -> do
352 hvals <- (unsafeCoerce# hval) :: IO [HValue]
354 case (names,hvals) of
355 ([n],[hv]) -> return (Just hv)
356 _ -> panic "cmCompileExpr"
362 %************************************************************************
364 Loading and unloading
366 %************************************************************************
369 -----------------------------------------------------------------------------
370 -- Unload the compilation manager's state: everything it knows about the
371 -- current collection of modules in the Home package.
373 cmUnload :: CmState -> IO CmState
374 cmUnload state@CmState{ cm_hsc = hsc_env }
375 = do -- Throw away the old home dir cache
378 -- Unload everything the linker knows about
381 -- Start with a fresh CmState, but keep the PersistentCompilerState
382 return (discardCMInfo state)
384 cm_unload hsc_env linkables
385 = case hsc_mode hsc_env of
388 Interactive -> Linker.unload (hsc_dflags hsc_env) linkables
390 Interactive -> panic "unload: no interpreter"
394 -----------------------------------------------------------------------------
395 -- Trace dependency graph
397 -- This is a seperate pass so that the caller can back off and keep
398 -- the current state if the downsweep fails. Typically the caller
399 -- might go cmDepAnal
402 -- He wants to do the dependency analysis before the unload, so that
403 -- if the former fails he can use the later
405 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
406 cmDepAnal cmstate rootnames
407 = do showPass dflags "Chasing dependencies"
408 when (verbosity dflags >= 1 && gmode == Batch) $
409 hPutStrLn stderr (showSDoc (hcat [
410 text "Chasing modules from: ",
411 hcat (punctuate comma (map text rootnames))]))
412 downsweep rootnames (cm_mg cmstate)
414 hsc_env = cm_hsc cmstate
415 dflags = hsc_dflags hsc_env
416 gmode = hsc_mode hsc_env
418 -----------------------------------------------------------------------------
419 -- The real business of the compilation manager: given a system state and
420 -- a module name, try and bring the module up to date, probably changing
421 -- the system state at the same time.
423 cmLoadModules :: CmState -- The HPT may not be as up to date
424 -> ModuleGraph -- Bang up to date
425 -> IO (CmState, -- new state
426 SuccessFlag, -- was successful
427 [String]) -- list of modules loaded
429 cmLoadModules cmstate1 mg2unsorted
430 = do -- version 1's are the original, before downsweep
431 let hsc_env = cm_hsc cmstate1
432 let hpt1 = hsc_HPT hsc_env
433 let ghci_mode = hsc_mode hsc_env -- this never changes
434 let dflags = hsc_dflags hsc_env -- this never changes
436 -- Do the downsweep to reestablish the module graph
437 let verb = verbosity dflags
439 -- Find out if we have a Main module
441 = any ((=="Main").moduleNameUserString.modSummaryName)
444 let mg2unsorted_names = map modSummaryName mg2unsorted
446 -- reachable_from follows source as well as normal imports
447 let reachable_from :: ModuleName -> [ModuleName]
448 reachable_from = downwards_closure_of_module mg2unsorted
450 -- should be cycle free; ignores 'import source's
451 let mg2 = topological_sort False mg2unsorted
452 -- ... whereas this takes them into account. Used for
453 -- backing out partially complete cycles following a failed
454 -- upsweep, and for removing from hpt all the modules
455 -- not in strict downwards closure, during calls to compile.
456 let mg2_with_srcimps = topological_sort True mg2unsorted
458 -- Sort out which linkables we wish to keep in the unlinked image.
459 -- See getValidLinkables below for details.
460 (valid_old_linkables, new_linkables)
461 <- getValidLinkables ghci_mode (hptLinkables hpt1)
462 mg2unsorted_names mg2_with_srcimps
464 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
466 -- Uniq of ModuleName is the same as Module, fortunately...
467 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
468 hsc_env2 = hsc_env { hsc_HPT = hpt2 }
470 -- When (verb >= 2) $
471 -- putStrLn (showSDoc (text "Valid linkables:"
472 -- <+> ppr valid_linkables))
474 -- Figure out a stable set of modules which can be retained
475 -- the top level envs, to avoid upsweeping them. Goes to a
476 -- bit of trouble to avoid upsweeping module cycles.
478 -- Construct a set S of stable modules like this:
479 -- Travel upwards, over the sccified graph. For each scc
480 -- of modules ms, add ms to S only if:
481 -- 1. All home imports of ms are either in ms or S
482 -- 2. A valid old linkable exists for each module in ms
484 stable_mods <- preUpsweep valid_old_linkables
485 mg2unsorted_names [] mg2_with_srcimps
488 = concatMap (findInSummaries mg2unsorted) stable_mods
491 = filter (\m -> linkableModName m `elem` stable_mods)
495 hPutStrLn stderr (showSDoc (text "Stable modules:"
496 <+> sep (map (text.moduleNameUserString) stable_mods)))
498 -- Unload any modules which are going to be re-linked this
500 cm_unload hsc_env2 stable_linkables
502 -- we can now glom together our linkable sets
503 let valid_linkables = valid_old_linkables ++ new_linkables
505 -- We could at this point detect cycles which aren't broken by
506 -- a source-import, and complain immediately, but it seems better
507 -- to let upsweep_mods do this, so at least some useful work gets
508 -- done before the upsweep is abandoned.
510 = filter (\scc -> any (`notElem` stable_mods)
511 (map modSummaryName (flattenSCC scc)))
514 --hPutStrLn stderr "after tsort:\n"
515 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
517 -- Because we don't take into account source imports when doing
518 -- the topological sort, there shouldn't be any cycles in mg2.
519 -- If there is, we complain and give up -- the user needs to
520 -- break the cycle using a boot file.
522 -- Now do the upsweep, calling compile for each module in
523 -- turn. Final result is version 3 of everything.
525 -- clean up between compilations
526 let cleanup = cleanTempFilesExcept verb
527 (ppFilesFromSummaries (flattenSCCs mg2))
529 (upsweep_ok, hsc_env3, modsUpswept)
530 <- upsweep_mods hsc_env2 valid_linkables reachable_from
531 cleanup upsweep_these
533 -- At this point, modsUpswept and newLis should have the same
534 -- length, so there is one new (or old) linkable for each
535 -- mod which was processed (passed to compile).
537 -- Make modsDone be the summaries for each home module now
538 -- available; this should equal the domain of hpt3.
539 -- (NOT STRICTLY TRUE if an interactive session was started
540 -- with some object on disk ???)
541 -- Get in in a roughly top .. bottom order (hence reverse).
543 let modsDone = reverse modsUpswept ++ stable_summaries
545 -- Try and do linking in some form, depending on whether the
546 -- upsweep was completely or only partially successful.
548 if succeeded upsweep_ok
551 -- Easy; just relink it all.
552 do when (verb >= 2) $
553 hPutStrLn stderr "Upsweep completely successful."
555 -- clean up after ourselves
556 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
558 ofile <- readIORef v_Output_file
559 no_hs_main <- readIORef v_NoHsMain
561 -- Issue a warning for the confusing case where the user
562 -- said '-o foo' but we're not going to do any linking.
563 -- We attempt linking if either (a) one of the modules is
564 -- called Main, or (b) the user said -no-hs-main, indicating
565 -- that main() is going to come from somewhere else.
567 let do_linking = a_root_is_Main || no_hs_main
568 when (ghci_mode == Batch && isJust ofile && not do_linking
570 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
572 -- link everything together
573 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
575 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
576 cmLoadFinish Succeeded linkresult cmstate3
579 -- Tricky. We need to back out the effects of compiling any
580 -- half-done cycles, both so as to clean up the top level envs
581 -- and to avoid telling the interactive linker to link them.
582 do when (verb >= 2) $
583 hPutStrLn stderr "Upsweep partially successful."
586 = map modSummaryName modsDone
587 let mods_to_zap_names
588 = findPartiallyCompletedCycles modsDone_names
591 = filter ((`notElem` mods_to_zap_names).modSummaryName)
594 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
597 -- Clean up after ourselves
598 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
600 -- Link everything together
601 linkresult <- link ghci_mode dflags False hpt4
603 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
604 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
605 cmLoadFinish Failed linkresult cmstate3
608 -- Finish up after a cmLoad.
610 -- If the link failed, unload everything and return.
611 cmLoadFinish ok Failed cmstate
612 = do cm_unload (cm_hsc cmstate) []
613 return (discardCMInfo cmstate, Failed, [])
615 -- Empty the interactive context and set the module context to the topmost
616 -- newly loaded module, or the Prelude if none were loaded.
617 cmLoadFinish ok Succeeded cmstate
618 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
619 mods_loaded = map (moduleNameUserString.modSummaryName)
622 return (new_cmstate, ok, mods_loaded)
624 -- used to fish out the preprocess output files for the purposes of
625 -- cleaning up. The preprocessed file *might* be the same as the
626 -- source file, but that doesn't do any harm.
627 ppFilesFromSummaries summaries
628 = [ fn | Just fn <- map (ml_hspp_file.ms_location) summaries ]
630 -----------------------------------------------------------------------------
633 -- For each module (or SCC of modules), we take:
635 -- - an on-disk linkable, if this is the first time around and one
638 -- - the old linkable, otherwise (and if one is available).
640 -- and we throw away the linkable if it is older than the source file.
641 -- In interactive mode, we also ignore the on-disk linkables unless
642 -- all of the dependents of this SCC also have on-disk linkables (we
643 -- can't have dynamically loaded objects that depend on interpreted
646 -- If a module has a valid linkable, then it may be STABLE (see below),
647 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
650 -- ToDo: this pass could be merged with the preUpsweep.
654 -> [Linkable] -- old linkables
655 -> [ModuleName] -- all home modules
656 -> [SCC ModSummary] -- all modules in the program, dependency order
657 -> IO ( [Linkable], -- still-valid linkables
658 [Linkable] -- new linkables we just found
661 getValidLinkables mode old_linkables all_home_mods module_graph = do
662 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
664 return (partition_it ls [] [])
666 partition_it [] valid new = (valid,new)
667 partition_it ((l,b):ls) valid new
668 | b = partition_it ls valid (l:new)
669 | otherwise = partition_it ls (l:valid) new
672 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
674 scc = flattenSCC scc0
675 scc_names = map modSummaryName scc
676 home_module m = m `elem` all_home_mods && m `notElem` scc_names
677 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
678 -- NB. ms_imps, not ms_allimps above. We don't want to
679 -- force a module's SOURCE imports to be already compiled for
680 -- its object linkable to be valid.
683 case findModuleLinkable_maybe (map fst new_linkables) m of
685 Just l -> isObjectLinkable l
687 objects_allowed = mode == Batch || all has_object scc_allhomeimps
691 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
693 -- since an scc can contain only all objects or no objects at all,
694 -- we have to check whether we got all objects or not, and re-do
695 -- the linkable check if not.
698 && not (all isObjectLinkable (map fst new_linkables'))
699 then foldM (getValidLinkable old_linkables False) [] scc
700 else return new_linkables'
702 return (new_linkables ++ new_linkables')
705 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
706 -> IO [(Linkable,Bool)]
707 -- True <=> linkable is new; i.e. freshly discovered on the disk
708 -- presumably generated 'on the side'
709 -- by a separate GHC run
710 getValidLinkable old_linkables objects_allowed new_linkables summary
711 -- 'objects_allowed' says whether we permit this module to
712 -- have a .o-file linkable. We only permit it if all the
713 -- modules it depends on also have .o files; a .o file can't
714 -- link to a bytecode module
715 = do let mod_name = modSummaryName summary
718 <- if (not objects_allowed)
721 else findLinkable mod_name (ms_location summary)
723 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
726 case (old_linkable, maybe_disk_linkable) of
727 (Nothing, Nothing) -> []
729 -- new object linkable just appeared
730 (Nothing, Just l) -> up_to_date l True
733 | isObjectLinkable l -> []
734 -- object linkable disappeared! In case we need to
735 -- relink the module, disregard the old linkable and
736 -- just interpret the module from now on.
737 | otherwise -> up_to_date l False
738 -- old byte code linkable
741 | not (isObjectLinkable l) -> up_to_date l False
742 -- if the previous linkable was interpreted, then we
743 -- ignore a newly compiled version, because the version
744 -- numbers in the interface file will be out-of-sync with
745 -- our internal ones.
746 | linkableTime l' > linkableTime l -> up_to_date l' True
747 | linkableTime l' == linkableTime l -> up_to_date l False
749 -- on-disk linkable has been replaced by an older one!
750 -- again, disregard the previous one.
753 | linkableTime l < ms_hs_date summary = []
754 | otherwise = [(l,b)]
755 -- why '<' rather than '<=' above? If the filesystem stores
756 -- times to the nearset second, we may occasionally find that
757 -- the object & source have the same modification time,
758 -- especially if the source was automatically generated
759 -- and compiled. Using >= is slightly unsafe, but it matches
762 return (new_linkables' ++ new_linkables)
765 hptLinkables :: HomePackageTable -> [Linkable]
766 -- Get all the linkables from the home package table, one for each module
767 -- Once the HPT is up to date, these are the ones we should link
768 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
771 -----------------------------------------------------------------------------
772 -- Do a pre-upsweep without use of "compile", to establish a
773 -- (downward-closed) set of stable modules for which we won't call compile.
776 -- * has a valid linkable (see getValidLinkables above)
777 -- * depends only on stable modules
778 -- * has an interface in the HPT (interactive mode only)
780 preUpsweep :: [Linkable] -- new valid linkables
781 -> [ModuleName] -- names of all mods encountered in downsweep
782 -> [ModuleName] -- accumulating stable modules
783 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
784 -> IO [ModuleName] -- stable modules
786 preUpsweep valid_lis all_home_mods stable [] = return stable
787 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
788 = do let scc = flattenSCC scc0
789 scc_allhomeimps :: [ModuleName]
791 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
792 all_imports_in_scc_or_stable
793 = all in_stable_or_scc scc_allhomeimps
795 = map modSummaryName scc
797 = m `elem` scc_names || m `elem` stable
799 -- now we check for valid linkables: each module in the SCC must
800 -- have a valid linkable (see getValidLinkables above).
801 has_valid_linkable new_summary
802 = isJust (findModuleLinkable_maybe valid_lis modname)
803 where modname = modSummaryName new_summary
805 scc_is_stable = all_imports_in_scc_or_stable
806 && all has_valid_linkable scc
809 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
810 else preUpsweep valid_lis all_home_mods stable sccs
813 -- Helper for preUpsweep. Assuming that new_summary's imports are all
814 -- stable (in the sense of preUpsweep), determine if new_summary is itself
815 -- stable, and, if so, in batch mode, return its linkable.
816 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
817 findInSummaries old_summaries mod_name
818 = [s | s <- old_summaries, modSummaryName s == mod_name]
820 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
821 findModInSummaries old_summaries mod
822 = case [s | s <- old_summaries, ms_mod s == mod] of
826 -- Return (names of) all those in modsDone who are part of a cycle
827 -- as defined by theGraph.
828 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
829 findPartiallyCompletedCycles modsDone theGraph
833 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
834 chew ((CyclicSCC vs):rest)
835 = let names_in_this_cycle = nub (map modSummaryName vs)
837 = nub ([done | done <- modsDone,
838 done `elem` names_in_this_cycle])
839 chewed_rest = chew rest
841 if notNull mods_in_this_cycle
842 && length mods_in_this_cycle < length names_in_this_cycle
843 then mods_in_this_cycle ++ chewed_rest
847 -- Compile multiple modules, stopping as soon as an error appears.
848 -- There better had not be any cyclic groups here -- we check for them.
849 upsweep_mods :: HscEnv -- Includes up-to-date HPT
850 -> [Linkable] -- Valid linkables
851 -> (ModuleName -> [ModuleName]) -- to construct downward closures
852 -> IO () -- how to clean up unwanted tmp files
853 -> [SCC ModSummary] -- mods to do (the worklist)
854 -- ...... RETURNING ......
856 HscEnv, -- With an updated HPT
857 [ModSummary]) -- Mods which succeeded
859 upsweep_mods hsc_env oldUI reachable_from cleanup
861 = return (Succeeded, hsc_env, [])
863 upsweep_mods hsc_env oldUI reachable_from cleanup
865 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
866 unwords (map (moduleNameUserString.modSummaryName) ms))
867 return (Failed, hsc_env, [])
869 upsweep_mods hsc_env oldUI reachable_from cleanup
870 ((AcyclicSCC mod):mods)
871 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
872 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM (hsc_HPT hsc_env)))
874 (ok_flag, hsc_env1) <- upsweep_mod hsc_env oldUI mod
875 (reachable_from (modSummaryName mod))
877 cleanup -- Remove unwanted tmp files between compilations
879 if failed ok_flag then
880 return (Failed, hsc_env1, [])
882 (restOK, hsc_env2, modOKs)
883 <- upsweep_mods hsc_env1 oldUI reachable_from cleanup mods
884 return (restOK, hsc_env2, mod:modOKs)
887 -- Compile a single module. Always produce a Linkable for it if
888 -- successful. If no compilation happened, return the old Linkable.
889 upsweep_mod :: HscEnv
894 HscEnv) -- With updated HPT
896 upsweep_mod hsc_env oldUI summary1 reachable_inc_me
898 let this_mod = ms_mod summary1
899 location = ms_location summary1
900 mod_name = moduleName this_mod
901 hpt1 = hsc_HPT hsc_env
903 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
904 Just mod_info -> Just (hm_iface mod_info)
907 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
908 source_unchanged = isJust maybe_old_linkable
910 reachable_only = filter (/= mod_name) reachable_inc_me
912 -- In interactive mode, all home modules below us *must* have an
913 -- interface in the HPT. We never demand-load home interfaces in
916 = ASSERT(hsc_mode hsc_env == Batch || all (`elemUFM` hpt1) reachable_only)
917 retainInTopLevelEnvs reachable_only hpt1
918 hsc_env_strictDC = hsc_env { hsc_HPT = hpt1_strictDC }
920 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
923 | Just l <- maybe_old_linkable, isObjectLinkable l = True
926 compresult <- compile hsc_env_strictDC this_mod location
927 source_unchanged have_object mb_old_iface
931 -- Compilation "succeeded", and may or may not have returned a new
932 -- linkable (depending on whether compilation was actually performed
934 CompOK new_details new_globals new_iface maybe_new_linkable
936 new_linkable = maybe_new_linkable `orElse` old_linkable
937 new_info = HomeModInfo { hm_iface = new_iface,
938 hm_globals = new_globals,
939 hm_details = new_details,
940 hm_linkable = new_linkable }
941 hpt2 = extendModuleEnv hpt1 this_mod new_info
943 return (Succeeded, hsc_env { hsc_HPT = hpt2 })
945 -- Compilation failed. Compile may still have updated the PCS, tho.
946 CompErrs -> return (Failed, hsc_env)
948 -- Filter modules in the HPT
949 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
950 retainInTopLevelEnvs keep_these hpt
951 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
953 maybeLookupUFM ufm u = case lookupUFM ufm u of
955 Just val -> [(u, val)]
957 -- Needed to clean up HPT so that we don't get duplicates in inst env
958 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
959 downwards_closure_of_module summaries root
960 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
961 toEdge summ = (modSummaryName summ,
962 filter (`elem` all_mods) (ms_allimps summ))
964 all_mods = map modSummaryName summaries
966 res = simple_transitive_closure (map toEdge summaries) [root]
968 -- trace (showSDoc (text "DC of mod" <+> ppr root
969 -- <+> text "=" <+> ppr res)) $
972 -- Calculate transitive closures from a set of roots given an adjacency list
973 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
974 simple_transitive_closure graph set
975 = let set2 = nub (concatMap dsts set ++ set)
976 dsts node = fromMaybe [] (lookup node graph)
978 if length set == length set2
980 else simple_transitive_closure graph set2
983 -- Calculate SCCs of the module graph, with or without taking into
984 -- account source imports.
985 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
986 topological_sort include_source_imports summaries
988 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
990 = (summ, modSummaryName summ,
991 (if include_source_imports
992 then ms_srcimps summ else []) ++ ms_imps summ)
994 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
995 mash_edge (summ, m, m_imports)
996 = case lookup m key_map of
997 Nothing -> panic "reverse_topological_sort"
998 Just mk -> (summ, mk,
999 -- ignore imports not from the home package
1000 mapCatMaybes (flip lookup key_map) m_imports)
1002 edges = map toEdge summaries
1003 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1004 scc_input = map mash_edge edges
1005 sccs = stronglyConnComp scc_input
1010 -----------------------------------------------------------------------------
1011 -- Downsweep (dependency analysis)
1013 -- Chase downwards from the specified root set, returning summaries
1014 -- for all home modules encountered. Only follow source-import
1017 -- We pass in the previous collection of summaries, which is used as a
1018 -- cache to avoid recalculating a module summary if the source is
1021 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1022 downsweep roots old_summaries
1023 = do rootSummaries <- mapM getRootSummary roots
1024 checkDuplicates rootSummaries
1026 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1027 (ms_imps m)) rootSummaries))
1028 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1029 let mod = ms_mod s, isHomeModule mod
1031 return all_summaries
1033 getRootSummary :: FilePath -> IO ModSummary
1035 | isHaskellSrcFilename file
1036 = do exists <- doesFileExist file
1037 if exists then summariseFile file else do
1038 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1040 = do exists <- doesFileExist hs_file
1041 if exists then summariseFile hs_file else do
1042 exists <- doesFileExist lhs_file
1043 if exists then summariseFile lhs_file else do
1044 let mod_name = mkModuleName file
1045 maybe_summary <- getSummary (file, mod_name)
1046 case maybe_summary of
1047 Nothing -> packageModErr mod_name
1050 hs_file = file ++ ".hs"
1051 lhs_file = file ++ ".lhs"
1053 -- In a root module, the filename is allowed to diverge from the module
1054 -- name, so we have to check that there aren't multiple root files
1055 -- defining the same module (otherwise the duplicates will be silently
1056 -- ignored, leading to confusing behaviour).
1057 checkDuplicates :: [ModSummary] -> IO ()
1058 checkDuplicates summaries = mapM_ check summaries
1063 many -> multiRootsErr modl many
1064 where modl = ms_mod summ
1066 [ fromJust (ml_hs_file (ms_location summ'))
1067 | summ' <- summaries, ms_mod summ' == modl ]
1069 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1070 getSummary (currentMod,nm)
1071 = do found <- findModule nm
1073 Right (mod, location) -> do
1074 let old_summary = findModInSummaries old_summaries mod
1075 summarise mod location old_summary
1078 dflags <- getDynFlags
1079 throwDyn (noModError dflags currentMod nm files)
1081 -- loop invariant: env doesn't contain package modules
1082 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1083 loop [] env = return (moduleEnvElts env)
1085 = do -- imports for modules we don't already have
1086 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1089 needed_summaries <- mapM getSummary needed_imps
1091 -- get just the "home" modules
1092 let new_home_summaries = [ s | Just s <- needed_summaries ]
1094 -- loop, checking the new imports
1095 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1096 (ms_imps m)) new_home_summaries)
1097 loop new_imps (extendModuleEnvList env
1098 [ (ms_mod s, s) | s <- new_home_summaries ])
1100 -- ToDo: we don't have a proper line number for this error
1101 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1102 hang (text loc <> colon) 4 $
1103 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1107 | verbosity dflags < 3 =
1108 text "(use -v to see a list of the files searched for)"
1110 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1112 -----------------------------------------------------------------------------
1113 -- Summarising modules
1115 -- We have two types of summarisation:
1117 -- * Summarise a file. This is used for the root module(s) passed to
1118 -- cmLoadModules. The file is read, and used to determine the root
1119 -- module name. The module name may differ from the filename.
1121 -- * Summarise a module. We are given a module name, and must provide
1122 -- a summary. The finder is used to locate the file in which the module
1125 summariseFile :: FilePath -> IO ModSummary
1127 = do hspp_fn <- preprocess file
1128 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1130 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1131 the_imps = filter (/= gHC_PRIM_Name) imps
1133 (mod, location) <- mkHomeModLocation mod_name file
1136 <- case ml_hs_file location of
1137 Nothing -> noHsFileErr mod_name
1138 Just src_fn -> getModificationTime src_fn
1140 return (ModSummary { ms_mod = mod,
1141 ms_location = location{ml_hspp_file=Just hspp_fn},
1142 ms_srcimps = srcimps, ms_imps = the_imps,
1143 ms_hs_date = src_timestamp })
1145 -- Summarise a module, and pick up source and timestamp.
1146 summarise :: Module -> ModLocation -> Maybe ModSummary
1147 -> IO (Maybe ModSummary)
1148 summarise mod location old_summary
1149 | not (isHomeModule mod) = return Nothing
1151 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1153 case ml_hs_file location of {
1154 Nothing -> noHsFileErr mod;
1157 src_timestamp <- getModificationTime src_fn
1159 -- return the cached summary if the source didn't change
1160 case old_summary of {
1161 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1164 hspp_fn <- preprocess hs_fn
1165 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1167 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1168 the_imps = filter (/= gHC_PRIM_Name) imps
1170 when (mod_name /= moduleName mod) $
1171 throwDyn (ProgramError
1172 (showSDoc (text hs_fn
1173 <> text ": file name does not match module name"
1174 <+> quotes (ppr (moduleName mod)))))
1176 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1177 srcimps the_imps src_timestamp))
1183 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1186 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1187 quotes (ppr mod) <+>
1188 text "is a package module")))
1190 multiRootsErr mod files
1191 = throwDyn (ProgramError (showSDoc (
1192 text "module" <+> quotes (ppr mod) <+>
1193 text "is defined in multiple files:" <+>
1194 sep (map text files))))
1198 %************************************************************************
1202 %************************************************************************
1205 -- The ModLocation contains both the original source filename and the
1206 -- filename of the cleaned-up source file after all preprocessing has been
1207 -- done. The point is that the summariser will have to cpp/unlit/whatever
1208 -- all files anyway, and there's no point in doing this twice -- just
1209 -- park the result in a temp file, put the name of it in the location,
1210 -- and let @compile@ read from that file on the way back up.
1213 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1215 emptyMG :: ModuleGraph
1220 ms_mod :: Module, -- name, package
1221 ms_location :: ModLocation, -- location
1222 ms_srcimps :: [ModuleName], -- source imports
1223 ms_imps :: [ModuleName], -- non-source imports
1224 ms_hs_date :: ClockTime -- timestamp of summarised file
1227 instance Outputable ModSummary where
1229 = sep [text "ModSummary {",
1230 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1231 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1232 text "ms_imps =" <+> ppr (ms_imps ms),
1233 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1237 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1239 modSummaryName :: ModSummary -> ModuleName
1240 modSummaryName = moduleName . ms_mod