2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
7 {-# OPTIONS -fvia-C #-}
9 ModuleGraph, ModSummary(..),
11 CmState, emptyCmState, -- abstract
13 cmInit, -- :: GhciMode -> 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
49 cmGetBindings, -- :: CmState -> [TyThing]
50 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
52 sandboxIO -- Should be somewhere else
57 #include "HsVersions.h"
59 import DriverPipeline ( CompResult(..), preprocess, compile, link )
60 import DriverState ( v_Output_file, v_NoHsMain )
64 import HscMain ( initPersistentCompilerState )
65 import HscTypes hiding ( moduleNameToModule )
67 import PrelNames ( gHC_PRIM_Name )
68 import Module ( Module, ModuleName, moduleName, mkModuleName, isHomeModule,
69 ModuleEnv, lookupModuleEnvByName, mkModuleEnv, moduleEnvElts,
70 extendModuleEnvList, extendModuleEnv,
75 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
76 import ErrUtils ( showPass )
77 import SysTools ( cleanTempFilesExcept )
78 import BasicTypes ( SuccessFlag(..), succeeded, failed )
82 import CmdLineOpts ( DynFlags(..), getDynFlags )
83 import Maybes ( expectJust, orElse )
85 import DATA_IOREF ( readIORef )
88 import HscMain ( hscThing, hscStmt, hscTcExpr )
89 import Module ( moduleUserString )
90 import TcRnDriver ( mkGlobalContext, getModuleContents )
91 import Name ( Name, NamedThing(..), isExternalName, nameModule )
93 import Type ( tidyType )
94 import VarEnv ( emptyTidyEnv )
95 import BasicTypes ( Fixity, FixitySig(..), defaultFixity )
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 gmode :: GhciMode, -- NEVER CHANGES
120 hpt :: HomePackageTable, -- Info about home package module
121 mg :: ModuleGraph, -- the module graph
122 ic :: InteractiveContext, -- command-line binding info
124 pcs :: PersistentCompilerState -- compile's persistent state
127 cmGetModInfo cmstate = (mg cmstate, hpt cmstate)
128 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
129 cmGetPrintUnqual cmstate = icPrintUnqual (ic cmstate)
131 emptyCmState :: GhciMode -> IO CmState
133 = do pcs <- initPersistentCompilerState
134 return (CmState { hpt = emptyHomePackageTable,
137 ic = emptyInteractiveContext,
140 cmInit :: GhciMode -> IO CmState
141 cmInit mode = emptyCmState mode
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)
153 emptyUI :: UnlinkedImage
156 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
157 findModuleLinkable_maybe lis mod
158 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
161 many -> pprPanic "findModuleLinkable" (ppr mod)
163 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
164 filterModuleLinkables p [] = []
165 filterModuleLinkables p (li:lis)
167 LM _ modnm _ -> if p modnm then retain else dump
169 dump = filterModuleLinkables p lis
172 linkableInSet :: Linkable -> [Linkable] -> Bool
173 linkableInSet l objs_loaded =
174 case findModuleLinkable_maybe objs_loaded (linkableModName l) of
176 Just m -> linkableTime l == linkableTime m
180 %************************************************************************
184 %************************************************************************
188 -----------------------------------------------------------------------------
189 -- Setting the context doesn't throw away any bindings; the bindings
190 -- we've built up in the InteractiveContext simply move to the new
191 -- module. They always shadow anything in scope in the current context.
194 :: CmState -> DynFlags
195 -> [String] -- take the top-level scopes of these modules
196 -> [String] -- and the just the exports from these
198 cmSetContext cmstate dflags toplevs exports = do
199 let CmState{ hpt=hpt, pcs=pcs, ic=old_ic } = cmstate
200 hsc_env = HscEnv { hsc_mode = Interactive, hsc_dflags = dflags,
203 toplev_mods <- mapM (getTopLevModule hpt) (map mkModuleName toplevs)
204 export_mods <- mapM (moduleNameToModule hpt) (map mkModuleName exports)
207 <- mkGlobalContext hsc_env pcs toplev_mods export_mods
210 Nothing -> return cmstate
211 Just env -> return cmstate{ pcs = new_pcs,
212 ic = old_ic{ ic_toplev_scope = toplev_mods,
213 ic_exports = export_mods,
214 ic_rn_gbl_env = env } }
216 getTopLevModule hpt mn =
217 case lookupModuleEnvByName hpt mn of
220 | isJust (mi_globals iface) -> return (mi_module iface)
222 iface = hm_iface mod_info
224 _other -> throwDyn (CmdLineError (
225 "cannot enter the top-level scope of a compiled module (module `" ++
226 moduleNameUserString mn ++ "')"))
228 moduleNameToModule :: HomePackageTable -> ModuleName -> IO Module
229 moduleNameToModule hpt mn = do
230 case lookupModuleEnvByName hpt mn of
231 Just mod_info -> return (mi_module (hm_iface mod_info))
232 _not_a_home_module -> do
233 maybe_stuff <- findModule mn
235 Left _ -> throwDyn (CmdLineError ("can't find module `"
236 ++ moduleNameUserString mn ++ "'"))
237 Right (m,_) -> return m
239 cmGetContext :: CmState -> IO ([String],[String])
240 cmGetContext CmState{ic=ic} =
241 return (map moduleUserString (ic_toplev_scope ic),
242 map moduleUserString (ic_exports ic))
244 cmModuleIsInterpreted :: CmState -> String -> IO Bool
245 cmModuleIsInterpreted cmstate str
246 = case lookupModuleEnvByName (hpt cmstate) (mkModuleName str) of
247 Just details -> return (isJust (mi_globals (hm_iface details)))
248 _not_a_home_module -> return False
250 -----------------------------------------------------------------------------
251 -- cmInfoThing: convert a String to a TyThing
253 -- A string may refer to more than one TyThing (eg. a constructor,
254 -- and type constructor), so we return a list of all the possible TyThings.
256 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
257 cmInfoThing cmstate dflags id
258 = do (new_pcs, things) <- hscThing hsc_env pcs icontext id
259 let new_pit = eps_PIT (pcs_EPS new_pcs)
260 pairs = map (\x -> (x, getFixity new_pit (getName x))) things
261 return (cmstate{ pcs=new_pcs }, pairs)
263 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
264 hsc_env = HscEnv { hsc_mode = Interactive,
268 getFixity :: PackageIfaceTable -> Name -> Fixity
270 | isExternalName name,
271 Just iface <- lookupIface hpt pit (nameModule name),
272 Just (FixitySig _ fixity _) <- lookupNameEnv (mi_fixities iface) name
277 -- ---------------------------------------------------------------------------
278 -- cmBrowseModule: get all the TyThings defined in a module
280 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
281 -> IO (CmState, [TyThing])
282 cmBrowseModule cmstate dflags str exports_only = do
283 let mn = mkModuleName str
284 mod <- moduleNameToModule hpt mn
285 (pcs1, maybe_ty_things)
286 <- getModuleContents hsc_env pcs mod exports_only
287 case maybe_ty_things of
288 Nothing -> return (cmstate{pcs=pcs1}, [])
289 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
291 hsc_env = HscEnv { hsc_mode = Interactive, hsc_dflags = dflags,
293 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
295 -----------------------------------------------------------------------------
296 -- cmRunStmt: Run a statement/expr.
299 = CmRunOk [Name] -- names bound by this evaluation
301 | CmRunException Exception -- statement raised an exception
303 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
304 cmRunStmt cmstate@CmState{ hpt=hpt, pcs=pcs, ic=icontext }
307 let hsc_env = HscEnv { hsc_mode = Interactive,
311 (new_pcs, maybe_stuff)
312 <- hscStmt hsc_env pcs icontext expr
315 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
316 Just (new_ic, names, hval) -> do
318 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
319 either_hvals <- sandboxIO thing_to_run
323 -- on error, keep the *old* interactive context,
324 -- so that 'it' is not bound to something
325 -- that doesn't exist.
326 return ( cmstate{ pcs=new_pcs }, CmRunException e )
329 -- Get the newly bound things, and bind them.
330 -- Don't need to delete any shadowed bindings;
331 -- the new ones override the old ones.
332 extendLinkEnv (zip names hvals)
334 return (cmstate{ pcs=new_pcs, ic=new_ic },
338 -- We run the statement in a "sandbox" to protect the rest of the
339 -- system from anything the expression might do. For now, this
340 -- consists of just wrapping it in an exception handler, but see below
341 -- for another version.
343 sandboxIO :: IO a -> IO (Either Exception a)
344 sandboxIO thing = Exception.try thing
347 -- This version of sandboxIO runs the expression in a completely new
348 -- RTS main thread. It is disabled for now because ^C exceptions
349 -- won't be delivered to the new thread, instead they'll be delivered
350 -- to the (blocked) GHCi main thread.
352 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
354 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
356 st_thing <- newStablePtr (Exception.try thing)
357 alloca $ \ p_st_result -> do
358 stat <- rts_evalStableIO st_thing p_st_result
359 freeStablePtr st_thing
361 then do st_result <- peek p_st_result
362 result <- deRefStablePtr st_result
363 freeStablePtr st_result
364 return (Right result)
366 return (Left (fromIntegral stat))
368 foreign import "rts_evalStableIO" {- safe -}
369 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
370 -- more informative than the C type!
373 -----------------------------------------------------------------------------
374 -- cmTypeOfExpr: returns a string representing the type of an expression
376 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
377 cmTypeOfExpr cmstate dflags expr
378 = do (new_pcs, maybe_stuff) <- hscTcExpr hsc_env pcs ic expr
380 let new_cmstate = cmstate{pcs = new_pcs}
383 Nothing -> return (new_cmstate, Nothing)
384 Just ty -> return (new_cmstate, Just str)
386 str = showSDocForUser unqual (text expr <+> dcolon <+> ppr tidy_ty)
387 unqual = icPrintUnqual ic
388 tidy_ty = tidyType emptyTidyEnv ty
390 CmState{ hpt=hpt, pcs=pcs, ic=ic } = cmstate
391 hsc_env = HscEnv { hsc_mode = Interactive,
397 -----------------------------------------------------------------------------
398 -- cmTypeOfName: returns a string representing the type of a name.
400 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
401 cmTypeOfName CmState{ pcs=pcs, ic=ic } name
403 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
404 case lookupNameEnv (ic_type_env ic) name of
405 Nothing -> return Nothing
406 Just (AnId id) -> return (Just str)
408 unqual = icPrintUnqual ic
409 ty = tidyType emptyTidyEnv (idType id)
410 str = showSDocForUser unqual (ppr ty)
412 _ -> panic "cmTypeOfName"
414 -----------------------------------------------------------------------------
415 -- cmCompileExpr: compile an expression and deliver an HValue
417 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
418 cmCompileExpr cmstate dflags expr
420 let hsc_env = HscEnv { hsc_mode = Interactive,
424 (new_pcs, maybe_stuff)
425 <- hscStmt hsc_env pcs icontext
426 ("let __cmCompileExpr = "++expr)
429 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
430 Just (new_ic, names, hval) -> do
433 hvals <- (unsafeCoerce# hval) :: IO [HValue]
435 case (names,hvals) of
436 ([n],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
437 _ -> panic "cmCompileExpr"
440 CmState{ hpt=hpt, pcs=pcs, ic=icontext } = cmstate
445 %************************************************************************
447 Loading and unloading
449 %************************************************************************
452 -----------------------------------------------------------------------------
453 -- Unload the compilation manager's state: everything it knows about the
454 -- current collection of modules in the Home package.
456 cmUnload :: CmState -> DynFlags -> IO CmState
457 cmUnload state@CmState{ gmode=mode, pcs=pcs } dflags
458 = do -- Throw away the old home dir cache
461 -- Unload everything the linker knows about
462 cm_unload mode dflags []
464 -- Start with a fresh CmState, but keep the PersistentCompilerState
465 new_state <- cmInit mode
466 return new_state{ pcs=pcs }
468 cm_unload Batch dflags linkables = return ()
471 cm_unload Interactive dflags linkables = Linker.unload dflags linkables
473 cm_unload Interactive dflags linkables = panic "unload: no interpreter"
477 -----------------------------------------------------------------------------
478 -- Trace dependency graph
480 -- This is a seperate pass so that the caller can back off and keep
481 -- the current state if the downsweep fails. Typically the caller
482 -- might go cmDepAnal
485 -- He wants to do the dependency analysis before the unload, so that
486 -- if the former fails he can use the later
488 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
489 cmDepAnal cmstate dflags rootnames
490 = do showPass dflags "Chasing dependencies"
491 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
492 hPutStrLn stderr (showSDoc (hcat [
493 text "Chasing modules from: ",
494 hcat (punctuate comma (map text rootnames))]))
495 downsweep rootnames (mg cmstate)
497 -----------------------------------------------------------------------------
498 -- The real business of the compilation manager: given a system state and
499 -- a module name, try and bring the module up to date, probably changing
500 -- the system state at the same time.
502 cmLoadModules :: CmState -- The HPT may not be as up to date
503 -> DynFlags -- as the ModuleGraph
504 -> ModuleGraph -- Bang up to date
505 -> IO (CmState, -- new state
506 SuccessFlag, -- was successful
507 [String]) -- list of modules loaded
509 cmLoadModules cmstate1 dflags mg2unsorted
510 = do -- version 1's are the original, before downsweep
511 let pcs1 = pcs cmstate1
512 let hpt1 = hpt cmstate1
514 let ghci_mode = gmode cmstate1 -- this never changes
516 -- Do the downsweep to reestablish the module graph
517 let verb = verbosity dflags
519 -- Find out if we have a Main module
521 = any ((=="Main").moduleNameUserString.modSummaryName)
524 let mg2unsorted_names = map modSummaryName mg2unsorted
526 -- reachable_from follows source as well as normal imports
527 let reachable_from :: ModuleName -> [ModuleName]
528 reachable_from = downwards_closure_of_module mg2unsorted
530 -- should be cycle free; ignores 'import source's
531 let mg2 = topological_sort False mg2unsorted
532 -- ... whereas this takes them into account. Used for
533 -- backing out partially complete cycles following a failed
534 -- upsweep, and for removing from hpt all the modules
535 -- not in strict downwards closure, during calls to compile.
536 let mg2_with_srcimps = topological_sort True mg2unsorted
538 -- Sort out which linkables we wish to keep in the unlinked image.
539 -- See getValidLinkables below for details.
540 (valid_old_linkables, new_linkables)
541 <- getValidLinkables ghci_mode (hptLinkables hpt1)
542 mg2unsorted_names mg2_with_srcimps
544 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
546 -- Uniq of ModuleName is the same as Module, fortunately...
547 let hpt2 = delListFromUFM hpt1 (map linkableModName new_linkables)
549 -- When (verb >= 2) $
550 -- putStrLn (showSDoc (text "Valid linkables:"
551 -- <+> ppr valid_linkables))
553 -- Figure out a stable set of modules which can be retained
554 -- the top level envs, to avoid upsweeping them. Goes to a
555 -- bit of trouble to avoid upsweeping module cycles.
557 -- Construct a set S of stable modules like this:
558 -- Travel upwards, over the sccified graph. For each scc
559 -- of modules ms, add ms to S only if:
560 -- 1. All home imports of ms are either in ms or S
561 -- 2. A valid old linkable exists for each module in ms
563 stable_mods <- preUpsweep valid_old_linkables
564 mg2unsorted_names [] mg2_with_srcimps
567 = concatMap (findInSummaries mg2unsorted) stable_mods
570 = filter (\m -> linkableModName m `elem` stable_mods)
574 hPutStrLn stderr (showSDoc (text "Stable modules:"
575 <+> sep (map (text.moduleNameUserString) stable_mods)))
577 -- Unload any modules which are going to be re-linked this
579 cm_unload ghci_mode dflags stable_linkables
581 -- we can now glom together our linkable sets
582 let valid_linkables = valid_old_linkables ++ new_linkables
584 -- We could at this point detect cycles which aren't broken by
585 -- a source-import, and complain immediately, but it seems better
586 -- to let upsweep_mods do this, so at least some useful work gets
587 -- done before the upsweep is abandoned.
589 = filter (\scc -> any (`notElem` stable_mods)
590 (map modSummaryName (flattenSCC scc)))
593 --hPutStrLn stderr "after tsort:\n"
594 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
596 -- Because we don't take into account source imports when doing
597 -- the topological sort, there shouldn't be any cycles in mg2.
598 -- If there is, we complain and give up -- the user needs to
599 -- break the cycle using a boot file.
601 -- Now do the upsweep, calling compile for each module in
602 -- turn. Final result is version 3 of everything.
604 let threaded2 = CmThreaded pcs1 hpt2
606 -- clean up between compilations
607 let cleanup = cleanTempFilesExcept verb
608 (ppFilesFromSummaries (flattenSCCs mg2))
610 (upsweep_ok, threaded3, modsUpswept)
611 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
612 threaded2 cleanup upsweep_these
614 let (CmThreaded pcs3 hpt3) = threaded3
616 -- At this point, modsUpswept and newLis should have the same
617 -- length, so there is one new (or old) linkable for each
618 -- mod which was processed (passed to compile).
620 -- Make modsDone be the summaries for each home module now
621 -- available; this should equal the domain of hpt3.
622 -- (NOT STRICTLY TRUE if an interactive session was started
623 -- with some object on disk ???)
624 -- Get in in a roughly top .. bottom order (hence reverse).
626 let modsDone = reverse modsUpswept ++ stable_summaries
628 -- Try and do linking in some form, depending on whether the
629 -- upsweep was completely or only partially successful.
631 if succeeded upsweep_ok
634 -- Easy; just relink it all.
635 do when (verb >= 2) $
636 hPutStrLn stderr "Upsweep completely successful."
638 -- clean up after ourselves
639 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
641 ofile <- readIORef v_Output_file
642 no_hs_main <- readIORef v_NoHsMain
644 -- Issue a warning for the confusing case where the user
645 -- said '-o foo' but we're not going to do any linking.
646 -- We attempt linking if either (a) one of the modules is
647 -- called Main, or (b) the user said -no-hs-main, indicating
648 -- that main() is going to come from somewhere else.
650 let do_linking = a_root_is_Main || no_hs_main
651 when (ghci_mode == Batch && isJust ofile && not do_linking
653 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
655 -- link everything together
656 linkresult <- link ghci_mode dflags do_linking hpt3
658 cmLoadFinish Succeeded linkresult
659 hpt3 modsDone ghci_mode pcs3
662 -- Tricky. We need to back out the effects of compiling any
663 -- half-done cycles, both so as to clean up the top level envs
664 -- and to avoid telling the interactive linker to link them.
665 do when (verb >= 2) $
666 hPutStrLn stderr "Upsweep partially successful."
669 = map modSummaryName modsDone
670 let mods_to_zap_names
671 = findPartiallyCompletedCycles modsDone_names
674 = filter ((`notElem` mods_to_zap_names).modSummaryName)
677 let hpt4 = retainInTopLevelEnvs (map modSummaryName mods_to_keep) hpt3
679 -- Clean up after ourselves
680 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
682 -- Link everything together
683 linkresult <- link ghci_mode dflags False hpt4
685 cmLoadFinish Failed linkresult
686 hpt4 mods_to_keep ghci_mode pcs3
689 -- Finish up after a cmLoad.
691 -- If the link failed, unload everything and return.
692 cmLoadFinish ok Failed hpt mods ghci_mode pcs = do
693 dflags <- getDynFlags
694 cm_unload ghci_mode dflags []
695 new_state <- cmInit ghci_mode
696 return (new_state{ pcs=pcs }, Failed, [])
698 -- Empty the interactive context and set the module context to the topmost
699 -- newly loaded module, or the Prelude if none were loaded.
700 cmLoadFinish ok Succeeded hpt mods ghci_mode pcs
701 = do let new_cmstate = CmState{ hpt=hpt, mg=mods,
702 gmode=ghci_mode, pcs=pcs,
703 ic = emptyInteractiveContext }
704 mods_loaded = map (moduleNameUserString.modSummaryName) mods
706 return (new_cmstate, ok, mods_loaded)
708 -- used to fish out the preprocess output files for the purposes
710 ppFilesFromSummaries summaries
711 = [ fn | Just fn <- map toPpFile summaries ]
714 | not (isSameFilePath hspp hs) = hspp
715 | otherwise = Nothing
717 loc = ms_location sum
718 hspp = ml_hspp_file loc
721 -- better make extra sure 'a' and 'b' are in canonical form
722 -- before using this equality test.
723 isSameFilePath a b = a == b
725 -----------------------------------------------------------------------------
728 -- For each module (or SCC of modules), we take:
730 -- - an on-disk linkable, if this is the first time around and one
733 -- - the old linkable, otherwise (and if one is available).
735 -- and we throw away the linkable if it is older than the source file.
736 -- In interactive mode, we also ignore the on-disk linkables unless
737 -- all of the dependents of this SCC also have on-disk linkables (we
738 -- can't have dynamically loaded objects that depend on interpreted
741 -- If a module has a valid linkable, then it may be STABLE (see below),
742 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
745 -- ToDo: this pass could be merged with the preUpsweep.
749 -> [Linkable] -- old linkables
750 -> [ModuleName] -- all home modules
751 -> [SCC ModSummary] -- all modules in the program, dependency order
752 -> IO ( [Linkable], -- still-valid linkables
753 [Linkable] -- new linkables we just found
756 getValidLinkables mode old_linkables all_home_mods module_graph = do
757 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
759 return (partition_it ls [] [])
761 partition_it [] valid new = (valid,new)
762 partition_it ((l,b):ls) valid new
763 | b = partition_it ls valid (l:new)
764 | otherwise = partition_it ls (l:valid) new
767 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
769 scc = flattenSCC scc0
770 scc_names = map modSummaryName scc
771 home_module m = m `elem` all_home_mods && m `notElem` scc_names
772 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
773 -- NB. ms_imps, not ms_allimps above. We don't want to
774 -- force a module's SOURCE imports to be already compiled for
775 -- its object linkable to be valid.
778 case findModuleLinkable_maybe (map fst new_linkables) m of
780 Just l -> isObjectLinkable l
782 objects_allowed = mode == Batch || all has_object scc_allhomeimps
786 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
788 -- since an scc can contain only all objects or no objects at all,
789 -- we have to check whether we got all objects or not, and re-do
790 -- the linkable check if not.
793 && not (all isObjectLinkable (map fst new_linkables'))
794 then foldM (getValidLinkable old_linkables False) [] scc
795 else return new_linkables'
797 return (new_linkables ++ new_linkables')
800 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
801 -> IO [(Linkable,Bool)]
802 -- True <=> linkable is new; i.e. freshly discovered on the disk
803 -- presumably generated 'on the side'
804 -- by a separate GHC run
805 getValidLinkable old_linkables objects_allowed new_linkables summary
806 -- 'objects_allowed' says whether we permit this module to
807 -- have a .o-file linkable. We only permit it if all the
808 -- modules it depends on also have .o files; a .o file can't
809 -- link to a bytecode module
810 = do let mod_name = modSummaryName summary
813 <- if (not objects_allowed)
816 else findLinkable mod_name (ms_location summary)
818 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
821 case (old_linkable, maybe_disk_linkable) of
822 (Nothing, Nothing) -> []
824 -- new object linkable just appeared
825 (Nothing, Just l) -> up_to_date l True
828 | isObjectLinkable l -> []
829 -- object linkable disappeared! In case we need to
830 -- relink the module, disregard the old linkable and
831 -- just interpret the module from now on.
832 | otherwise -> up_to_date l False
833 -- old byte code linkable
836 | not (isObjectLinkable l) -> up_to_date l False
837 -- if the previous linkable was interpreted, then we
838 -- ignore a newly compiled version, because the version
839 -- numbers in the interface file will be out-of-sync with
840 -- our internal ones.
841 | linkableTime l' > linkableTime l -> up_to_date l' True
842 | linkableTime l' == linkableTime l -> up_to_date l False
844 -- on-disk linkable has been replaced by an older one!
845 -- again, disregard the previous one.
848 | linkableTime l < ms_hs_date summary = []
849 | otherwise = [(l,b)]
850 -- why '<' rather than '<=' above? If the filesystem stores
851 -- times to the nearset second, we may occasionally find that
852 -- the object & source have the same modification time,
853 -- especially if the source was automatically generated
854 -- and compiled. Using >= is slightly unsafe, but it matches
857 return (new_linkables' ++ new_linkables)
860 hptLinkables :: HomePackageTable -> [Linkable]
861 -- Get all the linkables from the home package table, one for each module
862 -- Once the HPT is up to date, these are the ones we should link
863 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
866 -----------------------------------------------------------------------------
867 -- Do a pre-upsweep without use of "compile", to establish a
868 -- (downward-closed) set of stable modules for which we won't call compile.
871 -- * has a valid linkable (see getValidLinkables above)
872 -- * depends only on stable modules
873 -- * has an interface in the HPT (interactive mode only)
875 preUpsweep :: [Linkable] -- new valid linkables
876 -> [ModuleName] -- names of all mods encountered in downsweep
877 -> [ModuleName] -- accumulating stable modules
878 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
879 -> IO [ModuleName] -- stable modules
881 preUpsweep valid_lis all_home_mods stable [] = return stable
882 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
883 = do let scc = flattenSCC scc0
884 scc_allhomeimps :: [ModuleName]
886 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
887 all_imports_in_scc_or_stable
888 = all in_stable_or_scc scc_allhomeimps
890 = map modSummaryName scc
892 = m `elem` scc_names || m `elem` stable
894 -- now we check for valid linkables: each module in the SCC must
895 -- have a valid linkable (see getValidLinkables above).
896 has_valid_linkable new_summary
897 = isJust (findModuleLinkable_maybe valid_lis modname)
898 where modname = modSummaryName new_summary
900 scc_is_stable = all_imports_in_scc_or_stable
901 && all has_valid_linkable scc
904 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
905 else preUpsweep valid_lis all_home_mods stable sccs
908 -- Helper for preUpsweep. Assuming that new_summary's imports are all
909 -- stable (in the sense of preUpsweep), determine if new_summary is itself
910 -- stable, and, if so, in batch mode, return its linkable.
911 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
912 findInSummaries old_summaries mod_name
913 = [s | s <- old_summaries, modSummaryName s == mod_name]
915 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
916 findModInSummaries old_summaries mod
917 = case [s | s <- old_summaries, ms_mod s == mod] of
921 -- Return (names of) all those in modsDone who are part of a cycle
922 -- as defined by theGraph.
923 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
924 findPartiallyCompletedCycles modsDone theGraph
928 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
929 chew ((CyclicSCC vs):rest)
930 = let names_in_this_cycle = nub (map modSummaryName vs)
932 = nub ([done | done <- modsDone,
933 done `elem` names_in_this_cycle])
934 chewed_rest = chew rest
936 if notNull mods_in_this_cycle
937 && length mods_in_this_cycle < length names_in_this_cycle
938 then mods_in_this_cycle ++ chewed_rest
942 data CmThreaded -- stuff threaded through individual module compilations
943 = CmThreaded PersistentCompilerState HomePackageTable
946 -- Compile multiple modules, stopping as soon as an error appears.
947 -- There better had not be any cyclic groups here -- we check for them.
948 upsweep_mods :: GhciMode
950 -> [Linkable] -- Valid linkables
951 -> (ModuleName -> [ModuleName]) -- to construct downward closures
952 -> CmThreaded -- PCS & HPT
953 -> IO () -- how to clean up unwanted tmp files
954 -> [SCC ModSummary] -- mods to do (the worklist)
955 -- ...... RETURNING ......
957 CmThreaded, -- Includes linkables
958 [ModSummary]) -- Mods which succeeded
960 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
962 = return (Succeeded, threaded, [])
964 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
966 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
967 unwords (map (moduleNameUserString.modSummaryName) ms))
968 return (Failed, threaded, [])
970 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
971 ((AcyclicSCC mod):mods)
972 = do --case threaded of
973 -- CmThreaded pcsz hptz
974 -- -> putStrLn ("UPSWEEP_MOD: hpt = " ++
975 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM hptz)))
977 (ok_flag, threaded1) <- upsweep_mod ghci_mode dflags oldUI threaded mod
978 (reachable_from (modSummaryName mod))
980 cleanup -- Remove unwanted tmp files between compilations
982 if failed ok_flag then
983 return (Failed, threaded1, [])
985 (restOK, threaded2, modOKs)
986 <- upsweep_mods ghci_mode dflags oldUI reachable_from
987 threaded1 cleanup mods
988 return (restOK, threaded2, mod:modOKs)
991 -- Compile a single module. Always produce a Linkable for it if
992 -- successful. If no compilation happened, return the old Linkable.
993 upsweep_mod :: GhciMode
999 -> IO (SuccessFlag, CmThreaded)
1001 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1003 let this_mod = ms_mod summary1
1004 location = ms_location summary1
1005 mod_name = moduleName this_mod
1007 let (CmThreaded pcs1 hpt1) = threaded1
1008 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
1009 Just mod_info -> Just (hm_iface mod_info)
1012 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1013 source_unchanged = isJust maybe_old_linkable
1015 reachable_only = filter (/= mod_name) reachable_inc_me
1017 -- In interactive mode, all home modules below us *must* have an
1018 -- interface in the HPT. We never demand-load home interfaces in
1019 -- interactive mode.
1021 = ASSERT(ghci_mode == Batch || all (`elemUFM` hpt1) reachable_only)
1022 retainInTopLevelEnvs reachable_only hpt1
1024 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1027 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1030 compresult <- compile ghci_mode this_mod location source_unchanged
1031 have_object mb_old_iface hpt1_strictDC pcs1
1035 -- Compilation "succeeded", and may or may not have returned a new
1036 -- linkable (depending on whether compilation was actually performed
1038 CompOK pcs2 new_details new_iface maybe_new_linkable
1040 new_linkable = maybe_new_linkable `orElse` old_linkable
1041 new_info = HomeModInfo { hm_iface = new_iface,
1042 hm_details = new_details,
1043 hm_linkable = new_linkable }
1044 hpt2 = extendModuleEnv hpt1 this_mod new_info
1046 return (Succeeded, CmThreaded pcs2 hpt2)
1048 -- Compilation failed. Compile may still have updated the PCS, tho.
1049 CompErrs pcs2 -> return (Failed, CmThreaded pcs2 hpt1)
1051 -- Filter modules in the HPT
1052 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1053 retainInTopLevelEnvs keep_these hpt
1054 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
1056 maybeLookupUFM ufm u = case lookupUFM ufm u of
1058 Just val -> [(u, val)]
1060 -- Needed to clean up HPT so that we don't get duplicates in inst env
1061 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1062 downwards_closure_of_module summaries root
1063 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1064 toEdge summ = (modSummaryName summ,
1065 filter (`elem` all_mods) (ms_allimps summ))
1067 all_mods = map modSummaryName summaries
1069 res = simple_transitive_closure (map toEdge summaries) [root]
1071 -- trace (showSDoc (text "DC of mod" <+> ppr root
1072 -- <+> text "=" <+> ppr res)) $
1075 -- Calculate transitive closures from a set of roots given an adjacency list
1076 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1077 simple_transitive_closure graph set
1078 = let set2 = nub (concatMap dsts set ++ set)
1079 dsts node = fromMaybe [] (lookup node graph)
1081 if length set == length set2
1083 else simple_transitive_closure graph set2
1086 -- Calculate SCCs of the module graph, with or without taking into
1087 -- account source imports.
1088 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1089 topological_sort include_source_imports summaries
1091 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1093 = (summ, modSummaryName summ,
1094 (if include_source_imports
1095 then ms_srcimps summ else []) ++ ms_imps summ)
1097 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1098 mash_edge (summ, m, m_imports)
1099 = case lookup m key_map of
1100 Nothing -> panic "reverse_topological_sort"
1101 Just mk -> (summ, mk,
1102 -- ignore imports not from the home package
1103 catMaybes (map (flip lookup key_map) m_imports))
1105 edges = map toEdge summaries
1106 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1107 scc_input = map mash_edge edges
1108 sccs = stronglyConnComp scc_input
1113 -----------------------------------------------------------------------------
1114 -- Downsweep (dependency analysis)
1116 -- Chase downwards from the specified root set, returning summaries
1117 -- for all home modules encountered. Only follow source-import
1120 -- We pass in the previous collection of summaries, which is used as a
1121 -- cache to avoid recalculating a module summary if the source is
1124 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1125 downsweep roots old_summaries
1126 = do rootSummaries <- mapM getRootSummary roots
1127 checkDuplicates rootSummaries
1129 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1130 (ms_imps m)) rootSummaries))
1131 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1132 let mod = ms_mod s, isHomeModule mod
1134 return all_summaries
1136 getRootSummary :: FilePath -> IO ModSummary
1138 | haskellish_src_file file
1139 = do exists <- doesFileExist file
1140 if exists then summariseFile file else do
1141 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1143 = do exists <- doesFileExist hs_file
1144 if exists then summariseFile hs_file else do
1145 exists <- doesFileExist lhs_file
1146 if exists then summariseFile lhs_file else do
1147 let mod_name = mkModuleName file
1148 maybe_summary <- getSummary (file, mod_name)
1149 case maybe_summary of
1150 Nothing -> packageModErr mod_name
1153 hs_file = file ++ ".hs"
1154 lhs_file = file ++ ".lhs"
1156 -- In a root module, the filename is allowed to diverge from the module
1157 -- name, so we have to check that there aren't multiple root files
1158 -- defining the same module (otherwise the duplicates will be silently
1159 -- ignored, leading to confusing behaviour).
1160 checkDuplicates :: [ModSummary] -> IO ()
1161 checkDuplicates summaries = mapM_ check summaries
1166 many -> multiRootsErr modl many
1167 where modl = ms_mod summ
1169 [ fromJust (ml_hs_file (ms_location summ'))
1170 | summ' <- summaries, ms_mod summ' == modl ]
1172 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1173 getSummary (currentMod,nm)
1174 = do found <- findModule nm
1176 Right (mod, location) -> do
1177 let old_summary = findModInSummaries old_summaries mod
1178 summarise mod location old_summary
1181 dflags <- getDynFlags
1182 throwDyn (noModError dflags currentMod nm files)
1184 -- loop invariant: env doesn't contain package modules
1185 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1186 loop [] env = return (moduleEnvElts env)
1188 = do -- imports for modules we don't already have
1189 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1192 needed_summaries <- mapM getSummary needed_imps
1194 -- get just the "home" modules
1195 let new_home_summaries = [ s | Just s <- needed_summaries ]
1197 -- loop, checking the new imports
1198 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1199 (ms_imps m)) new_home_summaries)
1200 loop new_imps (extendModuleEnvList env
1201 [ (ms_mod s, s) | s <- new_home_summaries ])
1203 -- ToDo: we don't have a proper line number for this error
1204 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1205 hang (text loc <> colon) 4 $
1206 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1210 | verbosity dflags < 3 =
1211 text "(use -v to see a list of the files searched for)"
1213 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1215 -----------------------------------------------------------------------------
1216 -- Summarising modules
1218 -- We have two types of summarisation:
1220 -- * Summarise a file. This is used for the root module(s) passed to
1221 -- cmLoadModules. The file is read, and used to determine the root
1222 -- module name. The module name may differ from the filename.
1224 -- * Summarise a module. We are given a module name, and must provide
1225 -- a summary. The finder is used to locate the file in which the module
1228 summariseFile :: FilePath -> IO ModSummary
1230 = do hspp_fn <- preprocess file
1231 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1233 let (path, basename, ext) = splitFilename3 file
1234 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1235 the_imps = filter (/= gHC_PRIM_Name) imps
1237 (mod, location) <- mkHomeModLocation mod_name True{-is a root-}
1241 <- case ml_hs_file location of
1242 Nothing -> noHsFileErr mod_name
1243 Just src_fn -> getModificationTime src_fn
1245 return (ModSummary { ms_mod = mod,
1246 ms_location = location{ml_hspp_file=Just hspp_fn},
1247 ms_srcimps = srcimps, ms_imps = the_imps,
1248 ms_hs_date = src_timestamp })
1250 -- Summarise a module, and pick up source and timestamp.
1251 summarise :: Module -> ModLocation -> Maybe ModSummary
1252 -> IO (Maybe ModSummary)
1253 summarise mod location old_summary
1254 | not (isHomeModule mod) = return Nothing
1256 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1258 case ml_hs_file location of {
1259 Nothing -> noHsFileErr mod;
1262 src_timestamp <- getModificationTime src_fn
1264 -- return the cached summary if the source didn't change
1265 case old_summary of {
1266 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1269 hspp_fn <- preprocess hs_fn
1270 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1272 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1273 the_imps = filter (/= gHC_PRIM_Name) imps
1275 when (mod_name /= moduleName mod) $
1276 throwDyn (ProgramError
1277 (showSDoc (text hs_fn
1278 <> text ": file name does not match module name"
1279 <+> quotes (ppr (moduleName mod)))))
1281 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1282 srcimps the_imps src_timestamp))
1288 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1291 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1292 quotes (ppr mod) <+>
1293 text "is a package module")))
1295 multiRootsErr mod files
1296 = throwDyn (ProgramError (showSDoc (
1297 text "module" <+> quotes (ppr mod) <+>
1298 text "is defined in multiple files:" <+>
1299 sep (map text files))))
1303 %************************************************************************
1307 %************************************************************************
1310 -- The ModLocation contains both the original source filename and the
1311 -- filename of the cleaned-up source file after all preprocessing has been
1312 -- done. The point is that the summariser will have to cpp/unlit/whatever
1313 -- all files anyway, and there's no point in doing this twice -- just
1314 -- park the result in a temp file, put the name of it in the location,
1315 -- and let @compile@ read from that file on the way back up.
1318 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1320 emptyMG :: ModuleGraph
1325 ms_mod :: Module, -- name, package
1326 ms_location :: ModLocation, -- location
1327 ms_srcimps :: [ModuleName], -- source imports
1328 ms_imps :: [ModuleName], -- non-source imports
1329 ms_hs_date :: ClockTime -- timestamp of summarised file
1332 instance Outputable ModSummary where
1334 = sep [text "ModSummary {",
1335 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1336 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1337 text "ms_imps =" <+> ppr (ms_imps ms),
1338 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1342 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1344 modSummaryName :: ModSummary -> ModuleName
1345 modSummaryName = moduleName . ms_mod