2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
7 {-# OPTIONS -fvia-C #-}
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 cmGetModuleGraph, -- :: CmState -> ModuleGraph
47 cmGetLinkables, -- :: CmState -> [Linkable]
49 cmGetBindings, -- :: CmState -> [TyThing]
50 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
58 #include "HsVersions.h"
63 import DriverState ( v_Output_file )
68 import HscMain ( initPersistentCompilerState, hscThing,
71 import HscMain ( initPersistentCompilerState )
73 import HscTypes hiding ( moduleNameToModule )
74 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
75 isHomePackageName, isExternalName )
77 import PrelNames ( gHC_PRIM_Name )
78 import Rename ( mkGlobalContext )
79 import RdrName ( emptyRdrEnv )
83 import Unique ( Uniquable )
84 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
85 import ErrUtils ( showPass )
86 import SysTools ( cleanTempFilesExcept )
90 import CmdLineOpts ( DynFlags(..), getDynFlags )
91 import Maybes ( expectJust )
96 import RdrName ( lookupRdrEnv )
97 import Id ( idType, idName )
98 import Type ( tidyType )
99 import VarEnv ( emptyTidyEnv )
100 import BasicTypes ( Fixity, defaultFixity )
101 import Interpreter ( HValue )
102 import HscMain ( hscStmt )
103 import GlaExts ( unsafeCoerce# )
106 import Exception ( Exception, try )
109 import EXCEPTION ( throwDyn )
112 import Directory ( getModificationTime, doesFileExist )
121 -- Persistent state for the entire system
124 hst :: HomeSymbolTable, -- home symbol table
125 hit :: HomeIfaceTable, -- home interface table
126 ui :: UnlinkedImage, -- the unlinked images
127 mg :: ModuleGraph, -- the module graph
128 gmode :: GhciMode, -- NEVER CHANGES
129 ic :: InteractiveContext, -- command-line binding info
131 pcs :: PersistentCompilerState, -- compile's persistent state
132 pls :: PersistentLinkerState -- link's persistent state
135 emptyCmState :: GhciMode -> IO CmState
137 = do pcs <- initPersistentCompilerState
139 return (CmState { hst = emptySymbolTable,
140 hit = emptyIfaceTable,
144 ic = emptyInteractiveContext,
148 emptyInteractiveContext
149 = InteractiveContext { ic_toplev_scope = [],
151 ic_rn_gbl_env = emptyRdrEnv,
152 ic_print_unqual = alwaysQualify,
153 ic_rn_local_env = emptyRdrEnv,
154 ic_type_env = emptyTypeEnv }
157 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
158 emptyUI :: UnlinkedImage
161 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
162 emptyMG :: ModuleGraph
165 -----------------------------------------------------------------------------
166 -- Produce an initial CmState.
168 cmInit :: GhciMode -> IO CmState
169 cmInit mode = emptyCmState mode
171 -----------------------------------------------------------------------------
172 -- Grab information from the CmState
174 cmGetModuleGraph = mg
177 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
178 cmGetPrintUnqual cmstate = ic_print_unqual (ic cmstate)
180 -----------------------------------------------------------------------------
181 -- Setting the context doesn't throw away any bindings; the bindings
182 -- we've built up in the InteractiveContext simply move to the new
183 -- module. They always shadow anything in scope in the current context.
186 :: CmState -> DynFlags
187 -> [String] -- take the top-level scopes of these modules
188 -> [String] -- and the just the exports from these
190 cmSetContext cmstate dflags toplevs exports = do
191 let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
193 toplev_mods <- mapM (getTopLevModule hit) (map mkModuleName toplevs)
194 export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
196 (new_pcs, print_unqual, maybe_env)
197 <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
200 Nothing -> return cmstate
201 Just env -> return cmstate{ pcs = new_pcs,
202 ic = old_ic{ ic_toplev_scope = toplev_mods,
203 ic_exports = export_mods,
205 ic_print_unqual = print_unqual } }
207 getTopLevModule hit mn =
208 case lookupModuleEnvByName hit mn of
210 | Just _ <- mi_globals iface -> return (mi_module iface)
211 _other -> throwDyn (CmdLineError (
212 "cannot enter the top-level scope of a compiled module (module `" ++
213 moduleNameUserString mn ++ "')"))
215 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
216 moduleNameToModule hit mn = do
217 case lookupModuleEnvByName hit mn of
218 Just iface -> return (mi_module iface)
219 _not_a_home_module -> do
220 maybe_stuff <- findModule mn
222 Nothing -> throwDyn (CmdLineError ("can't find module `"
223 ++ moduleNameUserString mn ++ "'"))
224 Just (m,_) -> return m
226 cmGetContext :: CmState -> IO ([String],[String])
227 cmGetContext CmState{ic=ic} =
228 return (map moduleUserString (ic_toplev_scope ic),
229 map moduleUserString (ic_exports ic))
231 cmModuleIsInterpreted :: CmState -> String -> IO Bool
232 cmModuleIsInterpreted cmstate str
233 = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
234 Just iface -> return (not (isNothing (mi_globals iface)))
235 _not_a_home_module -> return False
237 -----------------------------------------------------------------------------
238 -- cmInfoThing: convert a String to a TyThing
240 -- A string may refer to more than one TyThing (eg. a constructor,
241 -- and type constructor), so we return a list of all the possible TyThings.
244 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
245 cmInfoThing cmstate dflags id
246 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
247 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
248 return (cmstate{ pcs=new_pcs }, pairs)
250 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
252 getFixity :: PersistentCompilerState -> Name -> Fixity
254 | isExternalName name,
255 Just iface <- lookupModuleEnv iface_table (nameModule name),
256 Just fixity <- lookupNameEnv (mi_fixities iface) name
260 where iface_table | isHomePackageName name = hit
261 | otherwise = pcs_PIT pcs
264 -- ---------------------------------------------------------------------------
265 -- cmBrowseModule: get all the TyThings defined in a module
268 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
269 -> IO (CmState, [TyThing])
270 cmBrowseModule cmstate dflags str exports_only = do
271 let mn = mkModuleName str
272 mod <- moduleNameToModule hit mn
273 (pcs1, maybe_ty_things)
274 <- hscModuleContents dflags hst hit pcs mod exports_only
275 case maybe_ty_things of
276 Nothing -> return (cmstate{pcs=pcs1}, [])
277 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
279 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
282 -----------------------------------------------------------------------------
283 -- cmRunStmt: Run a statement/expr.
287 = CmRunOk [Name] -- names bound by this evaluation
289 | CmRunException Exception -- statement raised an exception
291 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
292 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
295 let InteractiveContext {
296 ic_rn_local_env = rn_env,
297 ic_type_env = type_env } = icontext
299 (new_pcs, maybe_stuff)
300 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
303 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
304 Just (ids, _, bcos) -> do
306 -- update the interactive context
308 names = map idName ids
310 -- these names have just been shadowed
311 shadowed = [ n | r <- map nameRdrName names,
312 Just n <- [lookupRdrEnv rn_env r] ]
314 new_rn_env = extendLocalRdrEnv rn_env names
316 -- remove any shadowed bindings from the type_env
317 filtered_type_env = delListFromNameEnv type_env shadowed
319 new_type_env = extendNameEnvList filtered_type_env
320 [ (getName id, AnId id) | id <- ids]
322 new_ic = icontext { ic_rn_local_env = new_rn_env,
323 ic_type_env = new_type_env }
326 hval <- linkExpr pls bcos
329 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
330 either_hvals <- sandboxIO thing_to_run
333 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
334 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
339 return ( cmstate{ pcs=new_pcs, ic=new_ic },
342 -- Get the newly bound things, and bind them.
343 -- Don't forget to delete any shadowed bindings from the
344 -- closure_env, lest we end up with a space leak.
345 pls <- delListFromClosureEnv pls shadowed
346 new_pls <- addListToClosureEnv pls (zip names hvals)
348 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
352 -- We run the statement in a "sandbox" to protect the rest of the
353 -- system from anything the expression might do. For now, this
354 -- consists of just wrapping it in an exception handler, but see below
355 -- for another version.
357 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
359 r <- Exception.try thing
363 -- This version of sandboxIO runs the expression in a completely new
364 -- RTS main thread. It is disabled for now because ^C exceptions
365 -- won't be delivered to the new thread, instead they'll be delivered
366 -- to the (blocked) GHCi main thread.
368 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
370 st_thing <- newStablePtr (Exception.try thing)
371 alloca $ \ p_st_result -> do
372 stat <- rts_evalStableIO st_thing p_st_result
373 freeStablePtr st_thing
375 then do st_result <- peek p_st_result
376 result <- deRefStablePtr st_result
377 freeStablePtr st_result
378 return (Right result)
380 return (Left (fromIntegral stat))
382 foreign import "rts_evalStableIO" {- safe -}
383 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
384 -- more informative than the C type!
388 -----------------------------------------------------------------------------
389 -- cmTypeOfExpr: returns a string representing the type of an expression
392 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
393 cmTypeOfExpr cmstate dflags expr
394 = do (new_pcs, maybe_stuff)
395 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
397 let new_cmstate = cmstate{pcs = new_pcs}
400 Nothing -> return (new_cmstate, Nothing)
401 Just (_, ty, _) -> return (new_cmstate, Just str)
403 str = showSDocForUser unqual (ppr tidy_ty)
404 unqual = ic_print_unqual ic
405 tidy_ty = tidyType emptyTidyEnv ty
407 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
410 -----------------------------------------------------------------------------
411 -- cmTypeOfName: returns a string representing the type of a name.
414 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
415 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
416 = case lookupNameEnv (ic_type_env ic) name of
417 Nothing -> return Nothing
418 Just (AnId id) -> return (Just str)
420 unqual = ic_print_unqual ic
421 ty = tidyType emptyTidyEnv (idType id)
422 str = showSDocForUser unqual (ppr ty)
424 _ -> panic "cmTypeOfName"
427 -----------------------------------------------------------------------------
428 -- cmCompileExpr: compile an expression and deliver an HValue
431 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
432 cmCompileExpr cmstate dflags expr
434 let InteractiveContext {
435 ic_rn_local_env = rn_env,
436 ic_type_env = type_env } = icontext
438 (new_pcs, maybe_stuff)
439 <- hscStmt dflags hst hit pcs icontext
440 ("let __cmCompileExpr = "++expr) False{-stmt-}
443 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
444 Just (ids, _, bcos) -> do
447 hval <- linkExpr pls bcos
450 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
451 hvals <- thing_to_run
454 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
455 _ -> panic "cmCompileExpr"
458 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
461 -----------------------------------------------------------------------------
462 -- Unload the compilation manager's state: everything it knows about the
463 -- current collection of modules in the Home package.
465 cmUnload :: CmState -> DynFlags -> IO CmState
466 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
467 = do -- Throw away the old home dir cache
470 -- Unload everything the linker knows about
471 new_pls <- CmLink.unload mode dflags [] pls
473 -- Start with a fresh CmState, but keep the PersistentCompilerState
474 new_state <- cmInit mode
475 return new_state{ pcs=pcs, pls=new_pls }
478 -----------------------------------------------------------------------------
479 -- Trace dependency graph
481 -- This is a seperate pass so that the caller can back off and keep
482 -- the current state if the downsweep fails.
484 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
485 cmDepAnal cmstate dflags rootnames
486 = do showPass dflags "Chasing dependencies"
487 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
488 hPutStrLn stderr (showSDoc (hcat [
489 text progName, text ": chasing modules from: ",
490 hcat (punctuate comma (map text rootnames))]))
491 downsweep rootnames (mg cmstate)
493 -----------------------------------------------------------------------------
494 -- The real business of the compilation manager: given a system state and
495 -- a module name, try and bring the module up to date, probably changing
496 -- the system state at the same time.
498 cmLoadModules :: CmState
501 -> IO (CmState, -- new state
502 Bool, -- was successful
503 [String]) -- list of modules loaded
505 cmLoadModules cmstate1 dflags mg2unsorted
506 = do -- version 1's are the original, before downsweep
507 let pls1 = pls cmstate1
508 let pcs1 = pcs cmstate1
509 let hst1 = hst cmstate1
510 let hit1 = hit cmstate1
511 -- similarly, ui1 is the (complete) set of linkables from
512 -- the previous pass, if any.
513 let ui1 = ui cmstate1
515 let ghci_mode = gmode cmstate1 -- this never changes
517 -- Do the downsweep to reestablish the module graph
518 let verb = verbosity dflags
520 -- Find out if we have a Main module
522 = any ((=="Main").moduleNameUserString.modSummaryName)
525 let mg2unsorted_names = map modSummaryName mg2unsorted
527 -- reachable_from follows source as well as normal imports
528 let reachable_from :: ModuleName -> [ModuleName]
529 reachable_from = downwards_closure_of_module mg2unsorted
531 -- should be cycle free; ignores 'import source's
532 let mg2 = topological_sort False mg2unsorted
533 -- ... whereas this takes them into account. Used for
534 -- backing out partially complete cycles following a failed
535 -- upsweep, and for removing from hst/hit all the modules
536 -- not in strict downwards closure, during calls to compile.
537 let mg2_with_srcimps = topological_sort True mg2unsorted
539 -- Sort out which linkables we wish to keep in the unlinked image.
540 -- See getValidLinkables below for details.
541 (valid_old_linkables, new_linkables)
542 <- getValidLinkables ghci_mode ui1
543 mg2unsorted_names mg2_with_srcimps
545 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
547 -- uniq of ModuleName is the same as Module, fortunately...
548 let hit2 = delListFromUFM hit1 (map linkableModName new_linkables)
550 -- When (verb >= 2) $
551 -- putStrLn (showSDoc (text "Valid linkables:"
552 -- <+> ppr valid_linkables))
554 -- Figure out a stable set of modules which can be retained
555 -- the top level envs, to avoid upsweeping them. Goes to a
556 -- bit of trouble to avoid upsweeping module cycles.
558 -- Construct a set S of stable modules like this:
559 -- Travel upwards, over the sccified graph. For each scc
560 -- of modules ms, add ms to S only if:
561 -- 1. All home imports of ms are either in ms or S
562 -- 2. A valid old linkable exists for each module in ms
564 stable_mods <- preUpsweep valid_old_linkables
565 mg2unsorted_names [] mg2_with_srcimps
568 = concatMap (findInSummaries mg2unsorted) stable_mods
571 = filter (\m -> linkableModName m `elem` stable_mods)
575 putStrLn (showSDoc (text "Stable modules:"
576 <+> sep (map (text.moduleNameUserString) stable_mods)))
578 -- unload any modules which are going to be re-linked this
580 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
582 -- we can now glom together our linkable sets
583 let valid_linkables = valid_old_linkables ++ new_linkables
585 -- We could at this point detect cycles which aren't broken by
586 -- a source-import, and complain immediately, but it seems better
587 -- to let upsweep_mods do this, so at least some useful work gets
588 -- done before the upsweep is abandoned.
590 = filter (\scc -> any (`notElem` stable_mods)
591 (map modSummaryName (flattenSCC scc)))
594 --hPutStrLn stderr "after tsort:\n"
595 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
597 -- Because we don't take into account source imports when doing
598 -- the topological sort, there shouldn't be any cycles in mg2.
599 -- If there is, we complain and give up -- the user needs to
600 -- break the cycle using a boot file.
602 -- Now do the upsweep, calling compile for each module in
603 -- turn. Final result is version 3 of everything.
605 let threaded2 = CmThreaded pcs1 hst1 hit2
607 -- clean up between compilations
608 let cleanup = cleanTempFilesExcept verb
609 (ppFilesFromSummaries (flattenSCCs mg2))
611 (upsweep_complete_success, threaded3, modsUpswept, newLis)
612 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
613 threaded2 cleanup upsweep_these
615 let ui3 = add_to_ui valid_linkables newLis
616 let (CmThreaded pcs3 hst3 hit3) = threaded3
618 -- At this point, modsUpswept and newLis should have the same
619 -- length, so there is one new (or old) linkable for each
620 -- mod which was processed (passed to compile).
622 -- Make modsDone be the summaries for each home module now
623 -- available; this should equal the domains of hst3 and hit3.
624 -- (NOT STRICTLY TRUE if an interactive session was started
625 -- with some object on disk ???)
626 -- Get in in a roughly top .. bottom order (hence reverse).
628 let modsDone = reverse modsUpswept ++ stable_summaries
630 -- Try and do linking in some form, depending on whether the
631 -- upsweep was completely or only partially successful.
633 if upsweep_complete_success
636 -- Easy; just relink it all.
637 do when (verb >= 2) $
638 hPutStrLn stderr "Upsweep completely successful."
640 -- clean up after ourselves
641 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
643 -- issue a warning for the confusing case where the user said '-o foo'
644 -- but we're not going to do any linking.
645 ofile <- readIORef v_Output_file
646 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
648 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
650 -- link everything together
651 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
653 cmLoadFinish True linkresult
654 hst3 hit3 ui3 modsDone ghci_mode pcs3
657 -- Tricky. We need to back out the effects of compiling any
658 -- half-done cycles, both so as to clean up the top level envs
659 -- and to avoid telling the interactive linker to link them.
660 do when (verb >= 2) $
661 hPutStrLn stderr "Upsweep partially successful."
664 = map modSummaryName modsDone
665 let mods_to_zap_names
666 = findPartiallyCompletedCycles modsDone_names
669 = filter ((`notElem` mods_to_zap_names).modSummaryName)
672 let (hst4, hit4, ui4)
673 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
676 -- clean up after ourselves
677 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
679 -- link everything together
680 linkresult <- link ghci_mode dflags False ui4 pls2
682 cmLoadFinish False linkresult
683 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
686 -- Finish up after a cmLoad.
688 -- If the link failed, unload everything and return.
689 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
690 dflags <- getDynFlags
691 new_pls <- CmLink.unload ghci_mode dflags [] pls
692 new_state <- cmInit ghci_mode
693 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
695 -- Empty the interactive context and set the module context to the topmost
696 -- newly loaded module, or the Prelude if none were loaded.
697 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
698 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
699 gmode=ghci_mode, pcs=pcs, pls=pls,
700 ic = emptyInteractiveContext }
701 mods_loaded = map (moduleNameUserString.modSummaryName) mods
703 return (new_cmstate, ok, mods_loaded)
705 -- used to fish out the preprocess output files for the purposes
707 ppFilesFromSummaries summaries
708 = [ fn | Just fn <- map toPpFile summaries ]
711 | hspp /= ml_hs_file loc = hspp
712 | otherwise = Nothing
714 loc = ms_location sum
715 hspp = ml_hspp_file loc
718 -----------------------------------------------------------------------------
721 -- For each module (or SCC of modules), we take:
723 -- - an on-disk linkable, if this is the first time around and one
726 -- - the old linkable, otherwise (and if one is available).
728 -- and we throw away the linkable if it is older than the source file.
729 -- In interactive mode, we also ignore the on-disk linkables unless
730 -- all of the dependents of this SCC also have on-disk linkables (we
731 -- can't have dynamically loaded objects that depend on interpreted
734 -- If a module has a valid linkable, then it may be STABLE (see below),
735 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
738 -- ToDo: this pass could be merged with the preUpsweep.
742 -> [Linkable] -- old linkables
743 -> [ModuleName] -- all home modules
744 -> [SCC ModSummary] -- all modules in the program, dependency order
745 -> IO ( [Linkable], -- still-valid linkables
746 [Linkable] -- new linkables we just found
749 getValidLinkables mode old_linkables all_home_mods module_graph = do
750 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
752 return (partition_it ls [] [])
754 partition_it [] valid new = (valid,new)
755 partition_it ((l,b):ls) valid new
756 | b = partition_it ls valid (l:new)
757 | otherwise = partition_it ls (l:valid) new
760 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
762 scc = flattenSCC scc0
763 scc_names = map modSummaryName scc
764 home_module m = m `elem` all_home_mods && m `notElem` scc_names
765 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
766 -- NB. ms_imps, not ms_allimps above. We don't want to
767 -- force a module's SOURCE imports to be already compiled for
768 -- its object linkable to be valid.
771 case findModuleLinkable_maybe (map fst new_linkables) m of
773 Just l -> isObjectLinkable l
775 objects_allowed = mode == Batch || all has_object scc_allhomeimps
779 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
781 -- since an scc can contain only all objects or no objects at all,
782 -- we have to check whether we got all objects or not, and re-do
783 -- the linkable check if not.
786 && not (all isObjectLinkable (map fst new_linkables'))
787 then foldM (getValidLinkable old_linkables False) [] scc
788 else return new_linkables'
790 return (new_linkables ++ new_linkables')
793 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
794 -> IO [(Linkable,Bool)]
795 -- True <=> linkable is new
796 getValidLinkable old_linkables objects_allowed new_linkables summary
797 = do let mod_name = modSummaryName summary
800 <- if (not objects_allowed)
803 else case ml_obj_file (ms_location summary) of
804 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
805 Nothing -> return Nothing
807 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
810 case (old_linkable, maybe_disk_linkable) of
811 (Nothing, Nothing) -> []
813 -- new object linkable just appeared
814 (Nothing, Just l) -> up_to_date l True
817 | isObjectLinkable l -> []
818 -- object linkable disappeared! In case we need to
819 -- relink the module, disregard the old linkable and
820 -- just interpret the module from now on.
821 | otherwise -> up_to_date l False
822 -- old byte code linkable
825 | not (isObjectLinkable l) -> up_to_date l False
826 -- if the previous linkable was interpreted, then we
827 -- ignore a newly compiled version, because the version
828 -- numbers in the interface file will be out-of-sync with
829 -- our internal ones.
830 | linkableTime l' > linkableTime l -> up_to_date l' True
831 | linkableTime l' == linkableTime l -> up_to_date l False
833 -- on-disk linkable has been replaced by an older one!
834 -- again, disregard the previous one.
837 | linkableTime l < ms_hs_date summary = []
838 | otherwise = [(l,b)]
839 -- why '<' rather than '<=' above? If the filesystem stores
840 -- times to the nearset second, we may occasionally find that
841 -- the object & source have the same modification time,
842 -- especially if the source was automatically generated
843 -- and compiled. Using >= is slightly unsafe, but it matches
846 return (new_linkables' ++ new_linkables)
849 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
850 maybe_getFileLinkable mod obj_fn
851 = do obj_exist <- doesFileExist obj_fn
855 do let stub_fn = case splitFilename3 obj_fn of
856 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
857 stub_exist <- doesFileExist stub_fn
858 obj_time <- getModificationTime obj_fn
860 then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
861 else return (Just (LM obj_time mod [DotO obj_fn]))
864 -----------------------------------------------------------------------------
865 -- Do a pre-upsweep without use of "compile", to establish a
866 -- (downward-closed) set of stable modules for which we won't call compile.
869 -- * has a valid linkable (see getValidLinkables above)
870 -- * depends only on stable modules
871 -- * has an interface in the HIT (interactive mode only)
873 preUpsweep :: [Linkable] -- new valid linkables
874 -> [ModuleName] -- names of all mods encountered in downsweep
875 -> [ModuleName] -- accumulating stable modules
876 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
877 -> IO [ModuleName] -- stable modules
879 preUpsweep valid_lis all_home_mods stable [] = return stable
880 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
881 = do let scc = flattenSCC scc0
882 scc_allhomeimps :: [ModuleName]
884 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
885 all_imports_in_scc_or_stable
886 = all in_stable_or_scc scc_allhomeimps
888 = map modSummaryName scc
890 = m `elem` scc_names || m `elem` stable
892 -- now we check for valid linkables: each module in the SCC must
893 -- have a valid linkable (see getValidLinkables above).
894 has_valid_linkable new_summary
895 = isJust (findModuleLinkable_maybe valid_lis modname)
896 where modname = modSummaryName new_summary
898 scc_is_stable = all_imports_in_scc_or_stable
899 && all has_valid_linkable scc
902 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
903 else preUpsweep valid_lis all_home_mods stable sccs
906 -- Helper for preUpsweep. Assuming that new_summary's imports are all
907 -- stable (in the sense of preUpsweep), determine if new_summary is itself
908 -- stable, and, if so, in batch mode, return its linkable.
909 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
910 findInSummaries old_summaries mod_name
911 = [s | s <- old_summaries, modSummaryName s == mod_name]
913 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
914 findModInSummaries old_summaries mod
915 = case [s | s <- old_summaries, ms_mod s == mod] of
919 -- Return (names of) all those in modsDone who are part of a cycle
920 -- as defined by theGraph.
921 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
922 findPartiallyCompletedCycles modsDone theGraph
926 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
927 chew ((CyclicSCC vs):rest)
928 = let names_in_this_cycle = nub (map modSummaryName vs)
930 = nub ([done | done <- modsDone,
931 done `elem` names_in_this_cycle])
932 chewed_rest = chew rest
934 if notNull mods_in_this_cycle
935 && length mods_in_this_cycle < length names_in_this_cycle
936 then mods_in_this_cycle ++ chewed_rest
940 -- Add the given (LM-form) Linkables to the UI, overwriting previous
941 -- versions if they exist.
942 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
944 = filter (not_in lis) ui ++ lis
946 not_in :: [Linkable] -> Linkable -> Bool
948 = all (\l -> linkableModName l /= mod) lis
949 where mod = linkableModName li
952 data CmThreaded -- stuff threaded through individual module compilations
953 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
956 -- Compile multiple modules, stopping as soon as an error appears.
957 -- There better had not be any cyclic groups here -- we check for them.
958 upsweep_mods :: GhciMode
960 -> UnlinkedImage -- valid linkables
961 -> (ModuleName -> [ModuleName]) -- to construct downward closures
962 -> CmThreaded -- PCS & HST & HIT
963 -> IO () -- how to clean up unwanted tmp files
964 -> [SCC ModSummary] -- mods to do (the worklist)
965 -- ...... RETURNING ......
966 -> IO (Bool{-complete success?-},
968 [ModSummary], -- mods which succeeded
969 [Linkable]) -- new linkables
971 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
973 = return (True, threaded, [], [])
975 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
977 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
978 unwords (map (moduleNameUserString.modSummaryName) ms))
979 return (False, threaded, [], [])
981 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
982 ((AcyclicSCC mod):mods)
983 = do --case threaded of
984 -- CmThreaded pcsz hstz hitz
985 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
987 (threaded1, maybe_linkable)
988 <- upsweep_mod ghci_mode dflags oldUI threaded mod
989 (reachable_from (modSummaryName mod))
991 -- remove unwanted tmp files between compilations
994 case maybe_linkable of
996 -> -- No errors; do the rest
997 do (restOK, threaded2, modOKs, linkables)
998 <- upsweep_mods ghci_mode dflags oldUI reachable_from
999 threaded1 cleanup mods
1000 return (restOK, threaded2, mod:modOKs, linkable:linkables)
1001 Nothing -- we got a compilation error; give up now
1002 -> return (False, threaded1, [], [])
1005 -- Compile a single module. Always produce a Linkable for it if
1006 -- successful. If no compilation happened, return the old Linkable.
1007 upsweep_mod :: GhciMode
1013 -> IO (CmThreaded, Maybe Linkable)
1015 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1017 let mod_name = modSummaryName summary1
1019 let (CmThreaded pcs1 hst1 hit1) = threaded1
1020 let old_iface = lookupUFM hit1 mod_name
1022 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1024 source_unchanged = isJust maybe_old_linkable
1026 reachable_only = filter (/= (modSummaryName summary1))
1029 -- in interactive mode, all home modules below us *must* have an
1030 -- interface in the HIT. We never demand-load home interfaces in
1031 -- interactive mode.
1032 (hst1_strictDC, hit1_strictDC, [])
1033 = ASSERT(ghci_mode == Batch ||
1034 all (`elemUFM` hit1) reachable_only)
1035 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1038 = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1041 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1044 compresult <- compile ghci_mode summary1 source_unchanged
1045 have_object old_iface hst1_strictDC hit1_strictDC pcs1
1049 -- Compilation "succeeded", and may or may not have returned a new
1050 -- linkable (depending on whether compilation was actually performed
1052 CompOK pcs2 new_details new_iface maybe_new_linkable
1053 -> do let hst2 = addToUFM hst1 mod_name new_details
1054 hit2 = addToUFM hit1 mod_name new_iface
1055 threaded2 = CmThreaded pcs2 hst2 hit2
1057 return (threaded2, if isJust maybe_new_linkable
1058 then maybe_new_linkable
1059 else Just old_linkable)
1061 -- Compilation failed. compile may still have updated
1064 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1065 return (threaded2, Nothing)
1067 -- Filter modules in the top level envs (HST, HIT, UI).
1068 retainInTopLevelEnvs :: [ModuleName]
1069 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1070 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1071 retainInTopLevelEnvs keep_these (hst, hit, ui)
1072 = (retainInUFM hst keep_these,
1073 retainInUFM hit keep_these,
1074 filterModuleLinkables (`elem` keep_these) ui
1077 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1078 retainInUFM ufm keys_to_keep
1079 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1080 maybeLookupUFM ufm u
1081 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1083 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1084 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1085 downwards_closure_of_module summaries root
1086 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1087 toEdge summ = (modSummaryName summ,
1088 filter (`elem` all_mods) (ms_allimps summ))
1090 all_mods = map modSummaryName summaries
1092 res = simple_transitive_closure (map toEdge summaries) [root]
1094 -- trace (showSDoc (text "DC of mod" <+> ppr root
1095 -- <+> text "=" <+> ppr res)) $
1098 -- Calculate transitive closures from a set of roots given an adjacency list
1099 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1100 simple_transitive_closure graph set
1101 = let set2 = nub (concatMap dsts set ++ set)
1102 dsts node = fromMaybe [] (lookup node graph)
1104 if length set == length set2
1106 else simple_transitive_closure graph set2
1109 -- Calculate SCCs of the module graph, with or without taking into
1110 -- account source imports.
1111 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1112 topological_sort include_source_imports summaries
1114 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1116 = (summ, modSummaryName summ,
1117 (if include_source_imports
1118 then ms_srcimps summ else []) ++ ms_imps summ)
1120 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1121 mash_edge (summ, m, m_imports)
1122 = case lookup m key_map of
1123 Nothing -> panic "reverse_topological_sort"
1124 Just mk -> (summ, mk,
1125 -- ignore imports not from the home package
1126 catMaybes (map (flip lookup key_map) m_imports))
1128 edges = map toEdge summaries
1129 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1130 scc_input = map mash_edge edges
1131 sccs = stronglyConnComp scc_input
1136 -----------------------------------------------------------------------------
1137 -- Downsweep (dependency analysis)
1139 -- Chase downwards from the specified root set, returning summaries
1140 -- for all home modules encountered. Only follow source-import
1143 -- We pass in the previous collection of summaries, which is used as a
1144 -- cache to avoid recalculating a module summary if the source is
1147 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1148 downsweep roots old_summaries
1149 = do rootSummaries <- mapM getRootSummary roots
1150 checkDuplicates rootSummaries
1152 <- loop (concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1153 (ms_imps m)) rootSummaries))
1154 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1155 let mod = ms_mod s, isHomeModule mod
1157 return all_summaries
1159 getRootSummary :: FilePath -> IO ModSummary
1161 | haskellish_src_file file
1162 = do exists <- doesFileExist file
1163 if exists then summariseFile file else do
1164 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1166 = do exists <- doesFileExist hs_file
1167 if exists then summariseFile hs_file else do
1168 exists <- doesFileExist lhs_file
1169 if exists then summariseFile lhs_file else do
1170 let mod_name = mkModuleName file
1171 maybe_summary <- getSummary (file, mod_name)
1172 case maybe_summary of
1173 Nothing -> packageModErr mod_name
1176 hs_file = file ++ ".hs"
1177 lhs_file = file ++ ".lhs"
1179 -- In a root module, the filename is allowed to diverge from the module
1180 -- name, so we have to check that there aren't multiple root files
1181 -- defining the same module (otherwise the duplicates will be silently
1182 -- ignored, leading to confusing behaviour).
1183 checkDuplicates :: [ModSummary] -> IO ()
1184 checkDuplicates summaries = mapM_ check summaries
1189 many -> multiRootsErr modl many
1190 where modl = ms_mod summ
1192 [ fromJust (ml_hs_file (ms_location summ'))
1193 | summ' <- summaries, ms_mod summ' == modl ]
1195 getSummary :: (FilePath,ModuleName) -> IO (Maybe ModSummary)
1196 getSummary (currentMod,nm)
1197 = do found <- findModule nm
1199 Just (mod, location) -> do
1200 let old_summary = findModInSummaries old_summaries mod
1201 summarise mod location old_summary
1204 throwDyn (CmdLineError
1205 ("can't find module `"
1206 ++ showSDoc (ppr nm) ++ "' (while processing "
1207 ++ show currentMod ++ ")"))
1209 -- loop invariant: env doesn't contain package modules
1210 loop :: [(FilePath,ModuleName)] -> ModuleEnv ModSummary -> IO [ModSummary]
1211 loop [] env = return (moduleEnvElts env)
1213 = do -- imports for modules we don't already have
1214 let needed_imps = nub (filter (not . (`elemUFM` env).snd) imps)
1217 needed_summaries <- mapM getSummary needed_imps
1219 -- get just the "home" modules
1220 let new_home_summaries = [ s | Just s <- needed_summaries ]
1222 -- loop, checking the new imports
1223 let new_imps = concat (map (\ m -> zip (repeat (fromMaybe "<unknown>" (ml_hs_file (ms_location m))))
1224 (ms_imps m)) new_home_summaries)
1225 loop new_imps (extendModuleEnvList env
1226 [ (ms_mod s, s) | s <- new_home_summaries ])
1228 -----------------------------------------------------------------------------
1229 -- Summarising modules
1231 -- We have two types of summarisation:
1233 -- * Summarise a file. This is used for the root module(s) passed to
1234 -- cmLoadModules. The file is read, and used to determine the root
1235 -- module name. The module name may differ from the filename.
1237 -- * Summarise a module. We are given a module name, and must provide
1238 -- a summary. The finder is used to locate the file in which the module
1241 summariseFile :: FilePath -> IO ModSummary
1243 = do hspp_fn <- preprocess file
1244 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1246 let (path, basename, _ext) = splitFilename3 file
1247 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1248 the_imps = filter (/= gHC_PRIM_Name) imps
1251 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1254 <- case ml_hs_file location of
1255 Nothing -> noHsFileErr mod_name
1256 Just src_fn -> getModificationTime src_fn
1258 return (ModSummary mod
1259 location{ml_hspp_file=Just hspp_fn}
1260 srcimps the_imps src_timestamp)
1262 -- Summarise a module, and pick up source and timestamp.
1263 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1264 -> IO (Maybe ModSummary)
1265 summarise mod location old_summary
1266 | not (isHomeModule mod) = return Nothing
1268 = do let hs_fn = expectJust "summarise" (ml_hs_file location)
1270 case ml_hs_file location of {
1271 Nothing -> noHsFileErr mod;
1274 src_timestamp <- getModificationTime src_fn
1276 -- return the cached summary if the source didn't change
1277 case old_summary of {
1278 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1281 hspp_fn <- preprocess hs_fn
1282 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1284 -- GHC.Prim doesn't exist physically, so don't go looking for it.
1285 the_imps = filter (/= gHC_PRIM_Name) imps
1287 when (mod_name /= moduleName mod) $
1288 throwDyn (ProgramError
1289 (showSDoc (text hs_fn
1290 <> text ": file name does not match module name"
1291 <+> quotes (ppr (moduleName mod)))))
1293 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1294 srcimps the_imps src_timestamp))
1300 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1303 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1304 quotes (ppr mod) <+>
1305 text "is a package module")))
1307 multiRootsErr mod files
1308 = throwDyn (ProgramError (showSDoc (
1309 text "module" <+> quotes (ppr mod) <+>
1310 text "is defined in multiple files:" <+>
1311 sep (map text files))))