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 = fmap normalise a == fmap normalise b
725 -- a hack, because sometimes we strip off the leading "./" from a
727 normalise ('.':'/':f) = f
730 -----------------------------------------------------------------------------
733 -- For each module (or SCC of modules), we take:
735 -- - an on-disk linkable, if this is the first time around and one
738 -- - the old linkable, otherwise (and if one is available).
740 -- and we throw away the linkable if it is older than the source file.
741 -- In interactive mode, we also ignore the on-disk linkables unless
742 -- all of the dependents of this SCC also have on-disk linkables (we
743 -- can't have dynamically loaded objects that depend on interpreted
746 -- If a module has a valid linkable, then it may be STABLE (see below),
747 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
750 -- ToDo: this pass could be merged with the preUpsweep.
754 -> [Linkable] -- old linkables
755 -> [ModuleName] -- all home modules
756 -> [SCC ModSummary] -- all modules in the program, dependency order
757 -> IO ( [Linkable], -- still-valid linkables
758 [Linkable] -- new linkables we just found
761 getValidLinkables mode old_linkables all_home_mods module_graph = do
762 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
764 return (partition_it ls [] [])
766 partition_it [] valid new = (valid,new)
767 partition_it ((l,b):ls) valid new
768 | b = partition_it ls valid (l:new)
769 | otherwise = partition_it ls (l:valid) new
772 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
774 scc = flattenSCC scc0
775 scc_names = map modSummaryName scc
776 home_module m = m `elem` all_home_mods && m `notElem` scc_names
777 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
778 -- NB. ms_imps, not ms_allimps above. We don't want to
779 -- force a module's SOURCE imports to be already compiled for
780 -- its object linkable to be valid.
783 case findModuleLinkable_maybe (map fst new_linkables) m of
785 Just l -> isObjectLinkable l
787 objects_allowed = mode == Batch || all has_object scc_allhomeimps
791 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
793 -- since an scc can contain only all objects or no objects at all,
794 -- we have to check whether we got all objects or not, and re-do
795 -- the linkable check if not.
798 && not (all isObjectLinkable (map fst new_linkables'))
799 then foldM (getValidLinkable old_linkables False) [] scc
800 else return new_linkables'
802 return (new_linkables ++ new_linkables')
805 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
806 -> IO [(Linkable,Bool)]
807 -- True <=> linkable is new; i.e. freshly discovered on the disk
808 -- presumably generated 'on the side'
809 -- by a separate GHC run
810 getValidLinkable old_linkables objects_allowed new_linkables summary
811 -- 'objects_allowed' says whether we permit this module to
812 -- have a .o-file linkable. We only permit it if all the
813 -- modules it depends on also have .o files; a .o file can't
814 -- link to a bytecode module
815 = do let mod_name = modSummaryName summary
818 <- if (not objects_allowed)
821 else findLinkable mod_name (ms_location summary)
823 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
826 case (old_linkable, maybe_disk_linkable) of
827 (Nothing, Nothing) -> []
829 -- new object linkable just appeared
830 (Nothing, Just l) -> up_to_date l True
833 | isObjectLinkable l -> []
834 -- object linkable disappeared! In case we need to
835 -- relink the module, disregard the old linkable and
836 -- just interpret the module from now on.
837 | otherwise -> up_to_date l False
838 -- old byte code linkable
841 | not (isObjectLinkable l) -> up_to_date l False
842 -- if the previous linkable was interpreted, then we
843 -- ignore a newly compiled version, because the version
844 -- numbers in the interface file will be out-of-sync with
845 -- our internal ones.
846 | linkableTime l' > linkableTime l -> up_to_date l' True
847 | linkableTime l' == linkableTime l -> up_to_date l False
849 -- on-disk linkable has been replaced by an older one!
850 -- again, disregard the previous one.
853 | linkableTime l < ms_hs_date summary = []
854 | otherwise = [(l,b)]
855 -- why '<' rather than '<=' above? If the filesystem stores
856 -- times to the nearset second, we may occasionally find that
857 -- the object & source have the same modification time,
858 -- especially if the source was automatically generated
859 -- and compiled. Using >= is slightly unsafe, but it matches
862 return (new_linkables' ++ new_linkables)
865 hptLinkables :: HomePackageTable -> [Linkable]
866 -- Get all the linkables from the home package table, one for each module
867 -- Once the HPT is up to date, these are the ones we should link
868 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
871 -----------------------------------------------------------------------------
872 -- Do a pre-upsweep without use of "compile", to establish a
873 -- (downward-closed) set of stable modules for which we won't call compile.
876 -- * has a valid linkable (see getValidLinkables above)
877 -- * depends only on stable modules
878 -- * has an interface in the HPT (interactive mode only)
880 preUpsweep :: [Linkable] -- new valid linkables
881 -> [ModuleName] -- names of all mods encountered in downsweep
882 -> [ModuleName] -- accumulating stable modules
883 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
884 -> IO [ModuleName] -- stable modules
886 preUpsweep valid_lis all_home_mods stable [] = return stable
887 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
888 = do let scc = flattenSCC scc0
889 scc_allhomeimps :: [ModuleName]
891 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
892 all_imports_in_scc_or_stable
893 = all in_stable_or_scc scc_allhomeimps
895 = map modSummaryName scc
897 = m `elem` scc_names || m `elem` stable
899 -- now we check for valid linkables: each module in the SCC must
900 -- have a valid linkable (see getValidLinkables above).
901 has_valid_linkable new_summary
902 = isJust (findModuleLinkable_maybe valid_lis modname)
903 where modname = modSummaryName new_summary
905 scc_is_stable = all_imports_in_scc_or_stable
906 && all has_valid_linkable scc
909 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
910 else preUpsweep valid_lis all_home_mods stable sccs
913 -- Helper for preUpsweep. Assuming that new_summary's imports are all
914 -- stable (in the sense of preUpsweep), determine if new_summary is itself
915 -- stable, and, if so, in batch mode, return its linkable.
916 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
917 findInSummaries old_summaries mod_name
918 = [s | s <- old_summaries, modSummaryName s == mod_name]
920 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
921 findModInSummaries old_summaries mod
922 = case [s | s <- old_summaries, ms_mod s == mod] of
926 -- Return (names of) all those in modsDone who are part of a cycle
927 -- as defined by theGraph.
928 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
929 findPartiallyCompletedCycles modsDone theGraph
933 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
934 chew ((CyclicSCC vs):rest)
935 = let names_in_this_cycle = nub (map modSummaryName vs)
937 = nub ([done | done <- modsDone,
938 done `elem` names_in_this_cycle])
939 chewed_rest = chew rest
941 if notNull mods_in_this_cycle
942 && length mods_in_this_cycle < length names_in_this_cycle
943 then mods_in_this_cycle ++ chewed_rest
947 data CmThreaded -- stuff threaded through individual module compilations
948 = CmThreaded PersistentCompilerState HomePackageTable
951 -- Compile multiple modules, stopping as soon as an error appears.
952 -- There better had not be any cyclic groups here -- we check for them.
953 upsweep_mods :: GhciMode
955 -> [Linkable] -- Valid linkables
956 -> (ModuleName -> [ModuleName]) -- to construct downward closures
957 -> CmThreaded -- PCS & HPT
958 -> IO () -- how to clean up unwanted tmp files
959 -> [SCC ModSummary] -- mods to do (the worklist)
960 -- ...... RETURNING ......
962 CmThreaded, -- Includes linkables
963 [ModSummary]) -- Mods which succeeded
965 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
967 = return (Succeeded, threaded, [])
969 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
971 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
972 unwords (map (moduleNameUserString.modSummaryName) ms))
973 return (Failed, threaded, [])
975 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
976 ((AcyclicSCC mod):mods)
977 = do --case threaded of
978 -- CmThreaded pcsz hptz
979 -- -> putStrLn ("UPSWEEP_MOD: hpt = " ++
980 -- show (map (moduleNameUserString.moduleName.mi_module.hm_iface) (eltsUFM hptz)))
982 (ok_flag, threaded1) <- upsweep_mod ghci_mode dflags oldUI threaded mod
983 (reachable_from (modSummaryName mod))
985 cleanup -- Remove unwanted tmp files between compilations
987 if failed ok_flag then
988 return (Failed, threaded1, [])
990 (restOK, threaded2, modOKs)
991 <- upsweep_mods ghci_mode dflags oldUI reachable_from
992 threaded1 cleanup mods
993 return (restOK, threaded2, mod:modOKs)
996 -- Compile a single module. Always produce a Linkable for it if
997 -- successful. If no compilation happened, return the old Linkable.
998 upsweep_mod :: GhciMode
1004 -> IO (SuccessFlag, CmThreaded)
1006 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1008 let this_mod = ms_mod summary1
1009 location = ms_location summary1
1010 mod_name = moduleName this_mod
1012 let (CmThreaded pcs1 hpt1) = threaded1
1013 let mb_old_iface = case lookupModuleEnvByName hpt1 mod_name of
1014 Just mod_info -> Just (hm_iface mod_info)
1017 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1018 source_unchanged = isJust maybe_old_linkable
1020 reachable_only = filter (/= mod_name) reachable_inc_me
1022 -- In interactive mode, all home modules below us *must* have an
1023 -- interface in the HPT. We never demand-load home interfaces in
1024 -- interactive mode.
1026 = ASSERT(ghci_mode == Batch || all (`elemUFM` hpt1) reachable_only)
1027 retainInTopLevelEnvs reachable_only hpt1
1029 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1032 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1035 compresult <- compile ghci_mode this_mod location source_unchanged
1036 have_object mb_old_iface hpt1_strictDC pcs1
1040 -- Compilation "succeeded", and may or may not have returned a new
1041 -- linkable (depending on whether compilation was actually performed
1043 CompOK pcs2 new_details new_iface maybe_new_linkable
1045 new_linkable = maybe_new_linkable `orElse` old_linkable
1046 new_info = HomeModInfo { hm_iface = new_iface,
1047 hm_details = new_details,
1048 hm_linkable = new_linkable }
1049 hpt2 = extendModuleEnv hpt1 this_mod new_info
1051 return (Succeeded, CmThreaded pcs2 hpt2)
1053 -- Compilation failed. Compile may still have updated the PCS, tho.
1054 CompErrs pcs2 -> return (Failed, CmThreaded pcs2 hpt1)
1056 -- Filter modules in the HPT
1057 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1058 retainInTopLevelEnvs keep_these hpt
1059 = listToUFM (concatMap (maybeLookupUFM hpt) keep_these)
1061 maybeLookupUFM ufm u = case lookupUFM ufm u of
1063 Just val -> [(u, val)]
1065 -- Needed to clean up HPT so that we don't get duplicates in inst env
1066 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1067 downwards_closure_of_module summaries root
1068 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1069 toEdge summ = (modSummaryName summ,
1070 filter (`elem` all_mods) (ms_allimps summ))
1072 all_mods = map modSummaryName summaries
1074 res = simple_transitive_closure (map toEdge summaries) [root]
1076 -- trace (showSDoc (text "DC of mod" <+> ppr root
1077 -- <+> text "=" <+> ppr res)) $
1080 -- Calculate transitive closures from a set of roots given an adjacency list
1081 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1082 simple_transitive_closure graph set
1083 = let set2 = nub (concatMap dsts set ++ set)
1084 dsts node = fromMaybe [] (lookup node graph)
1086 if length set == length set2
1088 else simple_transitive_closure graph set2
1091 -- Calculate SCCs of the module graph, with or without taking into
1092 -- account source imports.
1093 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1094 topological_sort include_source_imports summaries
1096 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1098 = (summ, modSummaryName summ,
1099 (if include_source_imports
1100 then ms_srcimps summ else []) ++ ms_imps summ)
1102 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1103 mash_edge (summ, m, m_imports)
1104 = case lookup m key_map of
1105 Nothing -> panic "reverse_topological_sort"
1106 Just mk -> (summ, mk,
1107 -- ignore imports not from the home package
1108 catMaybes (map (flip lookup key_map) m_imports))
1110 edges = map toEdge summaries
1111 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1112 scc_input = map mash_edge edges
1113 sccs = stronglyConnComp scc_input
1118 -----------------------------------------------------------------------------
1119 -- Downsweep (dependency analysis)
1121 -- Chase downwards from the specified root set, returning summaries
1122 -- for all home modules encountered. Only follow source-import
1125 -- We pass in the previous collection of summaries, which is used as a
1126 -- cache to avoid recalculating a module summary if the source is
1129 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1130 downsweep roots old_summaries
1131 = do rootSummaries <- mapM getRootSummary roots
1132 checkDuplicates rootSummaries
1134 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1135 (ms_imps m)) rootSummaries))
1136 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1137 let mod = ms_mod s, isHomeModule mod
1139 return all_summaries
1141 getRootSummary :: FilePath -> IO ModSummary
1143 | haskellish_src_file file
1144 = do exists <- doesFileExist file
1145 if exists then summariseFile file else do
1146 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1148 = do exists <- doesFileExist hs_file
1149 if exists then summariseFile hs_file else do
1150 exists <- doesFileExist lhs_file
1151 if exists then summariseFile lhs_file else do
1152 let mod_name = mkModuleName file
1153 maybe_summary <- getSummary (file, mod_name)
1154 case maybe_summary of
1155 Nothing -> packageModErr mod_name
1158 hs_file = file ++ ".hs"
1159 lhs_file = file ++ ".lhs"
1161 -- In a root module, the filename is allowed to diverge from the module
1162 -- name, so we have to check that there aren't multiple root files
1163 -- defining the same module (otherwise the duplicates will be silently
1164 -- ignored, leading to confusing behaviour).
1165 checkDuplicates :: [ModSummary] -> IO ()
1166 checkDuplicates summaries = mapM_ check summaries
1171 many -> multiRootsErr modl many
1172 where modl = ms_mod summ
1174 [ fromJust (ml_hs_file (ms_location summ'))
1175 | summ' <- summaries, ms_mod summ' == modl ]
1177 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1178 getSummary (currentMod,nm)
1179 = do found <- findModule nm
1181 Right (mod, location) -> do
1182 let old_summary = findModInSummaries old_summaries mod
1183 summarise mod location old_summary
1186 dflags <- getDynFlags
1187 throwDyn (noModError dflags currentMod nm files)
1189 -- loop invariant: env doesn't contain package modules
1190 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1191 loop [] env = return (moduleEnvElts env)
1193 = do -- imports for modules we don't already have
1194 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1197 needed_summaries <- mapM getSummary needed_imps
1199 -- get just the "home" modules
1200 let new_home_summaries = [ s | Just s <- needed_summaries ]
1202 -- loop, checking the new imports
1203 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1204 (ms_imps m)) new_home_summaries)
1205 loop new_imps (extendModuleEnvList env
1206 [ (ms_mod s, s) | s <- new_home_summaries ])
1208 -- ToDo: we don't have a proper line number for this error
1209 noModError dflags loc mod_nm files = ProgramError (showSDoc (
1210 hang (text loc <> colon) 4 $
1211 (text "Can't find module" <+> quotes (ppr mod_nm) $$ extra)
1215 | verbosity dflags < 3 =
1216 text "(use -v to see a list of the files searched for)"
1218 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1220 -----------------------------------------------------------------------------
1221 -- Summarising modules
1223 -- We have two types of summarisation:
1225 -- * Summarise a file. This is used for the root module(s) passed to
1226 -- cmLoadModules. The file is read, and used to determine the root
1227 -- module name. The module name may differ from the filename.
1229 -- * Summarise a module. We are given a module name, and must provide
1230 -- a summary. The finder is used to locate the file in which the module
1233 summariseFile :: FilePath -> IO ModSummary
1235 = do hspp_fn <- preprocess file
1236 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1238 let -- GHC.Prim doesn't exist physically, so don't go looking for it.
1239 the_imps = filter (/= gHC_PRIM_Name) imps
1241 (mod, location) <- mkHomeModLocation mod_name file
1244 <- case ml_hs_file location of
1245 Nothing -> noHsFileErr mod_name
1246 Just src_fn -> getModificationTime src_fn
1248 return (ModSummary { ms_mod = mod,
1249 ms_location = location{ml_hspp_file=Just hspp_fn},
1250 ms_srcimps = srcimps, ms_imps = the_imps,
1251 ms_hs_date = src_timestamp })
1253 -- Summarise a module, and pick up source and timestamp.
1254 summarise :: Module -> ModLocation -> Maybe ModSummary
1255 -> IO (Maybe ModSummary)
1256 summarise mod location old_summary
1257 | not (isHomeModule mod) = return Nothing
1259 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1261 case ml_hs_file location of {
1262 Nothing -> noHsFileErr mod;
1265 src_timestamp <- getModificationTime src_fn
1267 -- return the cached summary if the source didn't change
1268 case old_summary of {
1269 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1272 hspp_fn <- preprocess hs_fn
1273 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1275 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1276 the_imps = filter (/= gHC_PRIM_Name) imps
1278 when (mod_name /= moduleName mod) $
1279 throwDyn (ProgramError
1280 (showSDoc (text hs_fn
1281 <> text ": file name does not match module name"
1282 <+> quotes (ppr (moduleName mod)))))
1284 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1285 srcimps the_imps src_timestamp))
1291 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1294 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1295 quotes (ppr mod) <+>
1296 text "is a package module")))
1298 multiRootsErr mod files
1299 = throwDyn (ProgramError (showSDoc (
1300 text "module" <+> quotes (ppr mod) <+>
1301 text "is defined in multiple files:" <+>
1302 sep (map text files))))
1306 %************************************************************************
1310 %************************************************************************
1313 -- The ModLocation contains both the original source filename and the
1314 -- filename of the cleaned-up source file after all preprocessing has been
1315 -- done. The point is that the summariser will have to cpp/unlit/whatever
1316 -- all files anyway, and there's no point in doing this twice -- just
1317 -- park the result in a temp file, put the name of it in the location,
1318 -- and let @compile@ read from that file on the way back up.
1321 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
1323 emptyMG :: ModuleGraph
1328 ms_mod :: Module, -- name, package
1329 ms_location :: ModLocation, -- location
1330 ms_srcimps :: [ModuleName], -- source imports
1331 ms_imps :: [ModuleName], -- non-source imports
1332 ms_hs_date :: ClockTime -- timestamp of summarised file
1335 instance Outputable ModSummary where
1337 = sep [text "ModSummary {",
1338 nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
1339 text "ms_mod =" <+> ppr (ms_mod ms) <> comma,
1340 text "ms_imps =" <+> ppr (ms_imps ms),
1341 text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
1345 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
1347 modSummaryName :: ModSummary -> ModuleName
1348 modSummaryName = moduleName . ms_mod