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, [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"
66 import DriverState ( v_Output_file )
71 import HscMain ( initPersistentCompilerState, hscThing,
74 import HscMain ( initPersistentCompilerState )
77 import Name ( Name, NamedThing(..), nameRdrName, nameModule,
78 isHomePackageName, isGlobalName )
80 import Rename ( mkGlobalContext )
81 import RdrName ( emptyRdrEnv )
85 import Unique ( Uniquable )
86 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
87 import ErrUtils ( showPass )
88 import SysTools ( cleanTempFilesExcept )
92 import CmdLineOpts ( DynFlags(..), getDynFlags )
97 import RdrName ( lookupRdrEnv )
98 import Id ( idType, idName )
99 import Type ( tidyType )
100 import VarEnv ( emptyTidyEnv )
101 import BasicTypes ( Fixity, defaultFixity )
102 import Interpreter ( HValue )
103 import HscMain ( hscStmt )
104 import GlaExts ( unsafeCoerce# )
107 import Exception ( Exception, try )
111 import Exception ( throwDyn )
114 import Directory ( getModificationTime, doesFileExist )
123 -- Persistent state for the entire system
126 hst :: HomeSymbolTable, -- home symbol table
127 hit :: HomeIfaceTable, -- home interface table
128 ui :: UnlinkedImage, -- the unlinked images
129 mg :: ModuleGraph, -- the module graph
130 gmode :: GhciMode, -- NEVER CHANGES
131 ic :: InteractiveContext, -- command-line binding info
133 pcs :: PersistentCompilerState, -- compile's persistent state
134 pls :: PersistentLinkerState -- link's persistent state
137 emptyCmState :: GhciMode -> IO CmState
139 = do pcs <- initPersistentCompilerState
141 return (CmState { hst = emptySymbolTable,
142 hit = emptyIfaceTable,
146 ic = emptyInteractiveContext,
150 emptyInteractiveContext
151 = InteractiveContext { ic_toplev_scope = [],
153 ic_rn_gbl_env = emptyRdrEnv,
154 ic_print_unqual = alwaysQualify,
155 ic_rn_local_env = emptyRdrEnv,
156 ic_type_env = emptyTypeEnv }
159 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
160 emptyUI :: UnlinkedImage
163 type ModuleGraph = [ModSummary] -- the module graph, topologically sorted
164 emptyMG :: ModuleGraph
167 -----------------------------------------------------------------------------
168 -- Produce an initial CmState.
170 cmInit :: GhciMode -> IO CmState
171 cmInit mode = emptyCmState mode
173 -----------------------------------------------------------------------------
174 -- Grab information from the CmState
176 cmGetModuleGraph = mg
179 cmGetBindings cmstate = nameEnvElts (ic_type_env (ic cmstate))
180 cmGetPrintUnqual cmstate = ic_print_unqual (ic cmstate)
182 -----------------------------------------------------------------------------
183 -- Setting the context doesn't throw away any bindings; the bindings
184 -- we've built up in the InteractiveContext simply move to the new
185 -- module. They always shadow anything in scope in the current context.
188 :: CmState -> DynFlags
189 -> [String] -- take the top-level scopes of these modules
190 -> [String] -- and the just the exports from these
192 cmSetContext cmstate dflags toplevs exports = do
193 let CmState{ hit=hit, hst=hst, pcs=pcs, ic=old_ic } = cmstate
195 toplev_mods <- mapM (getTopLevModule hit) (map mkModuleName toplevs)
196 export_mods <- mapM (moduleNameToModule hit) (map mkModuleName exports)
198 (new_pcs, print_unqual, maybe_env)
199 <- mkGlobalContext dflags hit hst pcs toplev_mods export_mods
202 Nothing -> return cmstate
203 Just env -> return cmstate{ pcs = new_pcs,
204 ic = old_ic{ ic_toplev_scope = toplev_mods,
205 ic_exports = export_mods,
207 ic_print_unqual = print_unqual } }
209 getTopLevModule hit mn =
210 case lookupModuleEnvByName hit mn of
212 | Just _ <- mi_globals iface -> return (mi_module iface)
213 _other -> throwDyn (CmdLineError (
214 "cannot enter the top-level scope of a compiled module (module `" ++
215 moduleNameUserString mn ++ "')"))
217 moduleNameToModule :: HomeIfaceTable -> ModuleName -> IO Module
218 moduleNameToModule hit mn = do
219 case lookupModuleEnvByName hit mn of
220 Just iface -> return (mi_module iface)
221 _not_a_home_module -> do
222 maybe_stuff <- findModule mn
224 Nothing -> throwDyn (CmdLineError ("can't find module `"
225 ++ moduleNameUserString mn ++ "'"))
226 Just (m,_) -> return m
228 cmGetContext :: CmState -> IO ([String],[String])
229 cmGetContext CmState{ic=ic} =
230 return (map moduleUserString (ic_toplev_scope ic),
231 map moduleUserString (ic_exports ic))
233 cmModuleIsInterpreted :: CmState -> String -> IO Bool
234 cmModuleIsInterpreted cmstate str
235 = case lookupModuleEnvByName (hit cmstate) (mkModuleName str) of
236 Just iface -> return (not (isNothing (mi_globals iface)))
237 _not_a_home_module -> return False
239 -----------------------------------------------------------------------------
240 -- cmInfoThing: convert a String to a TyThing
242 -- A string may refer to more than one TyThing (eg. a constructor,
243 -- and type constructor), so we return a list of all the possible TyThings.
246 cmInfoThing :: CmState -> DynFlags -> String -> IO (CmState, [(TyThing,Fixity)])
247 cmInfoThing cmstate dflags id
248 = do (new_pcs, things) <- hscThing dflags hst hit pcs icontext id
249 let pairs = map (\x -> (x, getFixity new_pcs (getName x))) things
250 return (cmstate{ pcs=new_pcs }, pairs)
252 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
254 getFixity :: PersistentCompilerState -> Name -> Fixity
257 Just iface <- lookupModuleEnv iface_table (nameModule name),
258 Just fixity <- lookupNameEnv (mi_fixities iface) name
262 where iface_table | isHomePackageName name = hit
263 | otherwise = pcs_PIT pcs
266 -- ---------------------------------------------------------------------------
267 -- cmBrowseModule: get all the TyThings defined in a module
270 cmBrowseModule :: CmState -> DynFlags -> String -> Bool
271 -> IO (CmState, [TyThing])
272 cmBrowseModule cmstate dflags str exports_only = do
273 let mn = mkModuleName str
274 mod <- moduleNameToModule hit mn
275 (pcs1, maybe_ty_things)
276 <- hscModuleContents dflags hst hit pcs mod exports_only
277 case maybe_ty_things of
278 Nothing -> return (cmstate{pcs=pcs1}, [])
279 Just ty_things -> return (cmstate{pcs=pcs1}, ty_things)
281 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
284 -----------------------------------------------------------------------------
285 -- cmRunStmt: Run a statement/expr.
289 = CmRunOk [Name] -- names bound by this evaluation
291 | CmRunException Exception -- statement raised an exception
293 cmRunStmt :: CmState -> DynFlags -> String -> IO (CmState, CmRunResult)
294 cmRunStmt cmstate@CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext }
297 let InteractiveContext {
298 ic_rn_local_env = rn_env,
299 ic_type_env = type_env } = icontext
301 (new_pcs, maybe_stuff)
302 <- hscStmt dflags hst hit pcs icontext expr False{-stmt-}
305 Nothing -> return (cmstate{ pcs=new_pcs }, CmRunFailed)
306 Just (ids, _, bcos) -> do
308 -- update the interactive context
310 names = map idName ids
312 -- these names have just been shadowed
313 shadowed = [ n | r <- map nameRdrName names,
314 Just n <- [lookupRdrEnv rn_env r] ]
316 new_rn_env = extendLocalRdrEnv rn_env names
318 -- remove any shadowed bindings from the type_env
319 filtered_type_env = delListFromNameEnv type_env shadowed
321 new_type_env = extendNameEnvList filtered_type_env
322 [ (getName id, AnId id) | id <- ids]
324 new_ic = icontext { ic_rn_local_env = new_rn_env,
325 ic_type_env = new_type_env }
328 hval <- linkExpr pls bcos
331 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
332 either_hvals <- sandboxIO thing_to_run
335 -> do hPutStrLn stderr ("unknown failure, code " ++ show err)
336 return ( cmstate{ pcs=new_pcs, ic=new_ic }, CmRunFailed )
341 return ( cmstate{ pcs=new_pcs, ic=new_ic },
344 -- Get the newly bound things, and bind them.
345 -- Don't forget to delete any shadowed bindings from the
346 -- closure_env, lest we end up with a space leak.
347 pls <- delListFromClosureEnv pls shadowed
348 new_pls <- addListToClosureEnv pls (zip names hvals)
350 return (cmstate{ pcs=new_pcs, pls=new_pls, ic=new_ic },
354 -- We run the statement in a "sandbox" to protect the rest of the
355 -- system from anything the expression might do. For now, this
356 -- consists of just wrapping it in an exception handler, but see below
357 -- for another version.
359 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
361 r <- Exception.try thing
365 -- This version of sandboxIO runs the expression in a completely new
366 -- RTS main thread. It is disabled for now because ^C exceptions
367 -- won't be delivered to the new thread, instead they'll be delivered
368 -- to the (blocked) GHCi main thread.
370 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
372 st_thing <- newStablePtr (Exception.try thing)
373 alloca $ \ p_st_result -> do
374 stat <- rts_evalStableIO st_thing p_st_result
375 freeStablePtr st_thing
377 then do st_result <- peek p_st_result
378 result <- deRefStablePtr st_result
379 freeStablePtr st_result
380 return (Right result)
382 return (Left (fromIntegral stat))
384 foreign import "rts_evalStableIO" {- safe -}
385 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
386 -- more informative than the C type!
390 -----------------------------------------------------------------------------
391 -- cmTypeOfExpr: returns a string representing the type of an expression
394 cmTypeOfExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe String)
395 cmTypeOfExpr cmstate dflags expr
396 = do (new_pcs, maybe_stuff)
397 <- hscStmt dflags hst hit pcs ic expr True{-just an expr-}
399 let new_cmstate = cmstate{pcs = new_pcs}
402 Nothing -> return (new_cmstate, Nothing)
403 Just (_, ty, _) -> return (new_cmstate, Just str)
405 str = showSDocForUser unqual (ppr tidy_ty)
406 unqual = ic_print_unqual ic
407 tidy_ty = tidyType emptyTidyEnv ty
409 CmState{ hst=hst, hit=hit, pcs=pcs, ic=ic } = cmstate
412 -----------------------------------------------------------------------------
413 -- cmTypeOfName: returns a string representing the type of a name.
416 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
417 cmTypeOfName CmState{ hit=hit, pcs=pcs, ic=ic } name
418 = case lookupNameEnv (ic_type_env ic) name of
419 Nothing -> return Nothing
420 Just (AnId id) -> return (Just str)
422 unqual = ic_print_unqual ic
423 ty = tidyType emptyTidyEnv (idType id)
424 str = showSDocForUser unqual (ppr ty)
426 _ -> panic "cmTypeOfName"
429 -----------------------------------------------------------------------------
430 -- cmCompileExpr: compile an expression and deliver an HValue
433 cmCompileExpr :: CmState -> DynFlags -> String -> IO (CmState, Maybe HValue)
434 cmCompileExpr cmstate dflags expr
436 let InteractiveContext {
437 ic_rn_local_env = rn_env,
438 ic_type_env = type_env } = icontext
440 (new_pcs, maybe_stuff)
441 <- hscStmt dflags hst hit pcs icontext
442 ("let __cmCompileExpr = "++expr) False{-stmt-}
445 Nothing -> return (cmstate{ pcs=new_pcs }, Nothing)
446 Just (ids, _, bcos) -> do
449 hval <- linkExpr pls bcos
452 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
453 hvals <- thing_to_run
456 ([id],[hv]) -> return (cmstate{ pcs=new_pcs }, Just hv)
457 _ -> panic "cmCompileExpr"
460 CmState{ hst=hst, hit=hit, pcs=pcs, pls=pls, ic=icontext } = cmstate
463 -----------------------------------------------------------------------------
464 -- Unload the compilation manager's state: everything it knows about the
465 -- current collection of modules in the Home package.
467 cmUnload :: CmState -> DynFlags -> IO CmState
468 cmUnload state@CmState{ gmode=mode, pls=pls, pcs=pcs } dflags
469 = do -- Throw away the old home dir cache
472 -- Unload everything the linker knows about
473 new_pls <- CmLink.unload mode dflags [] pls
475 -- Start with a fresh CmState, but keep the PersistentCompilerState
476 new_state <- cmInit mode
477 return new_state{ pcs=pcs, pls=new_pls }
480 -----------------------------------------------------------------------------
481 -- Trace dependency graph
483 -- This is a seperate pass so that the caller can back off and keep
484 -- the current state if the downsweep fails.
486 cmDepAnal :: CmState -> DynFlags -> [FilePath] -> IO ModuleGraph
487 cmDepAnal cmstate dflags rootnames
488 = do showPass dflags "Chasing dependencies"
489 when (verbosity dflags >= 1 && gmode cmstate == Batch) $
490 hPutStrLn stderr (showSDoc (hcat [
491 text progName, text ": chasing modules from: ",
492 hcat (punctuate comma (map text rootnames))]))
493 downsweep rootnames (mg cmstate)
495 -----------------------------------------------------------------------------
496 -- The real business of the compilation manager: given a system state and
497 -- a module name, try and bring the module up to date, probably changing
498 -- the system state at the same time.
500 cmLoadModules :: CmState
503 -> IO (CmState, -- new state
504 Bool, -- was successful
505 [String]) -- list of modules loaded
507 cmLoadModules cmstate1 dflags mg2unsorted
508 = do -- version 1's are the original, before downsweep
509 let pls1 = pls cmstate1
510 let pcs1 = pcs cmstate1
511 let hst1 = hst cmstate1
512 let hit1 = hit cmstate1
513 -- similarly, ui1 is the (complete) set of linkables from
514 -- the previous pass, if any.
515 let ui1 = ui cmstate1
517 let ghci_mode = gmode cmstate1 -- this never changes
519 -- Do the downsweep to reestablish the module graph
520 let verb = verbosity dflags
522 -- Find out if we have a Main module
524 = any ((=="Main").moduleNameUserString.modSummaryName)
527 let mg2unsorted_names = map modSummaryName mg2unsorted
529 -- reachable_from follows source as well as normal imports
530 let reachable_from :: ModuleName -> [ModuleName]
531 reachable_from = downwards_closure_of_module mg2unsorted
533 -- should be cycle free; ignores 'import source's
534 let mg2 = topological_sort False mg2unsorted
535 -- ... whereas this takes them into account. Used for
536 -- backing out partially complete cycles following a failed
537 -- upsweep, and for removing from hst/hit all the modules
538 -- not in strict downwards closure, during calls to compile.
539 let mg2_with_srcimps = topological_sort True mg2unsorted
541 -- Sort out which linkables we wish to keep in the unlinked image.
542 -- See getValidLinkables below for details.
543 (valid_old_linkables, new_linkables)
544 <- getValidLinkables ui1 mg2unsorted_names mg2_with_srcimps
546 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
548 -- uniq of ModuleName is the same as Module, fortunately...
549 let hit2 = delListFromUFM hit1 (map linkableModName new_linkables)
551 -- When (verb >= 2) $
552 -- putStrLn (showSDoc (text "Valid linkables:"
553 -- <+> ppr valid_linkables))
555 -- Figure out a stable set of modules which can be retained
556 -- the top level envs, to avoid upsweeping them. Goes to a
557 -- bit of trouble to avoid upsweeping module cycles.
559 -- Construct a set S of stable modules like this:
560 -- Travel upwards, over the sccified graph. For each scc
561 -- of modules ms, add ms to S only if:
562 -- 1. All home imports of ms are either in ms or S
563 -- 2. A valid old linkable exists for each module in ms
565 stable_mods <- preUpsweep valid_old_linkables
566 mg2unsorted_names [] mg2_with_srcimps
569 = concatMap (findInSummaries mg2unsorted) stable_mods
572 = filter (\m -> linkableModName m `elem` stable_mods)
576 putStrLn (showSDoc (text "Stable modules:"
577 <+> sep (map (text.moduleNameUserString) stable_mods)))
579 -- unload any modules which are going to be re-linked this
581 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
583 -- we can now glom together our linkable sets
584 let valid_linkables = valid_old_linkables ++ new_linkables
586 -- We could at this point detect cycles which aren't broken by
587 -- a source-import, and complain immediately, but it seems better
588 -- to let upsweep_mods do this, so at least some useful work gets
589 -- done before the upsweep is abandoned.
591 = filter (\scc -> any (`notElem` stable_mods)
592 (map modSummaryName (flattenSCC scc)))
595 --hPutStrLn stderr "after tsort:\n"
596 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
598 -- Because we don't take into account source imports when doing
599 -- the topological sort, there shouldn't be any cycles in mg2.
600 -- If there is, we complain and give up -- the user needs to
601 -- break the cycle using a boot file.
603 -- Now do the upsweep, calling compile for each module in
604 -- turn. Final result is version 3 of everything.
606 let threaded2 = CmThreaded pcs1 hst1 hit2
608 -- clean up between compilations
609 let cleanup = cleanTempFilesExcept verb
610 (ppFilesFromSummaries (flattenSCCs upsweep_these))
612 (upsweep_complete_success, threaded3, modsUpswept, newLis)
613 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
614 threaded2 cleanup upsweep_these
616 let ui3 = add_to_ui valid_linkables newLis
617 let (CmThreaded pcs3 hst3 hit3) = threaded3
619 -- At this point, modsUpswept and newLis should have the same
620 -- length, so there is one new (or old) linkable for each
621 -- mod which was processed (passed to compile).
623 -- Make modsDone be the summaries for each home module now
624 -- available; this should equal the domains of hst3 and hit3.
625 -- (NOT STRICTLY TRUE if an interactive session was started
626 -- with some object on disk ???)
627 -- Get in in a roughly top .. bottom order (hence reverse).
629 let modsDone = reverse modsUpswept ++ stable_summaries
631 -- Try and do linking in some form, depending on whether the
632 -- upsweep was completely or only partially successful.
634 if upsweep_complete_success
637 -- Easy; just relink it all.
638 do when (verb >= 2) $
639 hPutStrLn stderr "Upsweep completely successful."
641 -- clean up after ourselves
642 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
644 -- issue a warning for the confusing case where the user said '-o foo'
645 -- but we're not going to do any linking.
646 ofile <- readIORef v_Output_file
647 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
649 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
651 -- link everything together
652 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
654 cmLoadFinish True linkresult
655 hst3 hit3 ui3 modsDone ghci_mode pcs3
658 -- Tricky. We need to back out the effects of compiling any
659 -- half-done cycles, both so as to clean up the top level envs
660 -- and to avoid telling the interactive linker to link them.
661 do when (verb >= 2) $
662 hPutStrLn stderr "Upsweep partially successful."
665 = map modSummaryName modsDone
666 let mods_to_zap_names
667 = findPartiallyCompletedCycles modsDone_names
670 = filter ((`notElem` mods_to_zap_names).modSummaryName)
673 let (hst4, hit4, ui4)
674 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
677 -- clean up after ourselves
678 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
680 -- link everything together
681 linkresult <- link ghci_mode dflags False ui4 pls2
683 cmLoadFinish False linkresult
684 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
687 -- Finish up after a cmLoad.
689 -- If the link failed, unload everything and return.
690 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
691 dflags <- getDynFlags
692 new_pls <- CmLink.unload ghci_mode dflags [] pls
693 new_state <- cmInit ghci_mode
694 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
696 -- Empty the interactive context and set the module context to the topmost
697 -- newly loaded module, or the Prelude if none were loaded.
698 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
699 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
700 gmode=ghci_mode, pcs=pcs, pls=pls,
701 ic = emptyInteractiveContext }
702 mods_loaded = map (moduleNameUserString.modSummaryName) mods
704 return (new_cmstate, ok, mods_loaded)
706 -- used to fish out the preprocess output files for the purposes
708 ppFilesFromSummaries summaries
709 = [ fn | Just fn <- map toPpFile summaries ]
712 | hspp /= ml_hs_file loc = hspp
713 | otherwise = Nothing
715 loc = ms_location sum
716 hspp = ml_hspp_file loc
719 -----------------------------------------------------------------------------
722 -- For each module (or SCC of modules), we take:
724 -- - an on-disk linkable, if this is the first time around and one
727 -- - the old linkable, otherwise (and if one is available).
729 -- and we throw away the linkable if it is older than the source
730 -- file. We ignore the on-disk linkables unless all of the dependents
731 -- of this SCC also have on-disk linkables.
733 -- If a module has a valid linkable, then it may be STABLE (see below),
734 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
737 -- ToDo: this pass could be merged with the preUpsweep.
740 :: [Linkable] -- old linkables
741 -> [ModuleName] -- all home modules
742 -> [SCC ModSummary] -- all modules in the program, dependency order
743 -> IO ( [Linkable], -- still-valid linkables
744 [Linkable] -- new linkables we just found
747 getValidLinkables old_linkables all_home_mods module_graph = do
748 ls <- foldM (getValidLinkablesSCC old_linkables all_home_mods)
750 return (partition_it ls [] [])
752 partition_it [] valid new = (valid,new)
753 partition_it ((l,b):ls) valid new
754 | b = partition_it ls valid (l:new)
755 | otherwise = partition_it ls (l:valid) new
758 getValidLinkablesSCC old_linkables all_home_mods new_linkables scc0
760 scc = flattenSCC scc0
761 scc_names = map modSummaryName scc
762 home_module m = m `elem` all_home_mods && m `notElem` scc_names
763 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
764 -- NB. ms_imps, not ms_allimps above. We don't want to
765 -- force a module's SOURCE imports to be already compiled for
766 -- its object linkable to be valid.
769 case findModuleLinkable_maybe (map fst new_linkables) m of
771 Just l -> isObjectLinkable l
773 objects_allowed = all has_object scc_allhomeimps
777 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
779 -- since an scc can contain only all objects or no objects at all,
780 -- we have to check whether we got all objects or not, and re-do
781 -- the linkable check if not.
784 && not (all isObjectLinkable (map fst new_linkables'))
785 then foldM (getValidLinkable old_linkables False) [] scc
786 else return new_linkables'
788 return (new_linkables ++ new_linkables')
791 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
792 -> IO [(Linkable,Bool)]
793 -- True <=> linkable is new
794 getValidLinkable old_linkables objects_allowed new_linkables summary
795 = do let mod_name = modSummaryName summary
798 <- if (not objects_allowed)
801 else case ml_obj_file (ms_location summary) of
802 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
803 Nothing -> return Nothing
805 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
808 case (old_linkable, maybe_disk_linkable) of
809 (Nothing, Nothing) -> []
811 -- new object linkable just appeared
812 (Nothing, Just l) -> up_to_date l True
815 | isObjectLinkable l -> []
816 -- object linkable disappeared! In case we need to
817 -- relink the module, disregard the old linkable and
818 -- just interpret the module from now on.
819 | otherwise -> up_to_date l False
820 -- old byte code linkable
823 | not (isObjectLinkable l) -> up_to_date l False
824 -- if the previous linkable was interpreted, then we
825 -- ignore a newly compiled version, because the version
826 -- numbers in the interface file will be out-of-sync with
827 -- our internal ones.
828 | linkableTime l' > linkableTime l -> up_to_date l' True
829 | linkableTime l' == linkableTime l -> up_to_date l False
831 -- on-disk linkable has been replaced by an older one!
832 -- again, disregard the previous one.
835 | linkableTime l < ms_hs_date summary = []
836 | otherwise = [(l,b)]
837 -- why '<' rather than '<=' above? If the filesystem stores
838 -- times to the nearset second, we may occasionally find that
839 -- the object & source have the same modification time,
840 -- especially if the source was automatically generated
841 -- and compiled. Using >= is slightly unsafe, but it matches
844 return (new_linkables' ++ new_linkables)
847 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
848 maybe_getFileLinkable mod obj_fn
849 = do obj_exist <- doesFileExist obj_fn
853 do let stub_fn = case splitFilename3 obj_fn of
854 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
855 stub_exist <- doesFileExist stub_fn
856 obj_time <- getModificationTime obj_fn
858 then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
859 else return (Just (LM obj_time mod [DotO obj_fn]))
862 -----------------------------------------------------------------------------
863 -- Do a pre-upsweep without use of "compile", to establish a
864 -- (downward-closed) set of stable modules for which we won't call compile.
867 -- * has a valid linkable (see getValidLinkables above)
868 -- * depends only on stable modules
869 -- * has an interface in the HIT (interactive mode only)
871 preUpsweep :: [Linkable] -- new valid linkables
872 -> [ModuleName] -- names of all mods encountered in downsweep
873 -> [ModuleName] -- accumulating stable modules
874 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
875 -> IO [ModuleName] -- stable modules
877 preUpsweep valid_lis all_home_mods stable [] = return stable
878 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
879 = do let scc = flattenSCC scc0
880 scc_allhomeimps :: [ModuleName]
882 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
883 all_imports_in_scc_or_stable
884 = all in_stable_or_scc scc_allhomeimps
886 = map modSummaryName scc
888 = m `elem` scc_names || m `elem` stable
890 -- now we check for valid linkables: each module in the SCC must
891 -- have a valid linkable (see getValidLinkables above).
892 has_valid_linkable new_summary
893 = isJust (findModuleLinkable_maybe valid_lis modname)
894 where modname = modSummaryName new_summary
896 scc_is_stable = all_imports_in_scc_or_stable
897 && all has_valid_linkable scc
900 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
901 else preUpsweep valid_lis all_home_mods stable sccs
904 -- Helper for preUpsweep. Assuming that new_summary's imports are all
905 -- stable (in the sense of preUpsweep), determine if new_summary is itself
906 -- stable, and, if so, in batch mode, return its linkable.
907 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
908 findInSummaries old_summaries mod_name
909 = [s | s <- old_summaries, modSummaryName s == mod_name]
911 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
912 findModInSummaries old_summaries mod
913 = case [s | s <- old_summaries, ms_mod s == mod] of
917 -- Return (names of) all those in modsDone who are part of a cycle
918 -- as defined by theGraph.
919 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
920 findPartiallyCompletedCycles modsDone theGraph
924 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
925 chew ((CyclicSCC vs):rest)
926 = let names_in_this_cycle = nub (map modSummaryName vs)
928 = nub ([done | done <- modsDone,
929 done `elem` names_in_this_cycle])
930 chewed_rest = chew rest
932 if not (null mods_in_this_cycle)
933 && length mods_in_this_cycle < length names_in_this_cycle
934 then mods_in_this_cycle ++ chewed_rest
938 -- Add the given (LM-form) Linkables to the UI, overwriting previous
939 -- versions if they exist.
940 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
942 = filter (not_in lis) ui ++ lis
944 not_in :: [Linkable] -> Linkable -> Bool
946 = all (\l -> linkableModName l /= mod) lis
947 where mod = linkableModName li
950 data CmThreaded -- stuff threaded through individual module compilations
951 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
954 -- Compile multiple modules, stopping as soon as an error appears.
955 -- There better had not be any cyclic groups here -- we check for them.
956 upsweep_mods :: GhciMode
958 -> UnlinkedImage -- valid linkables
959 -> (ModuleName -> [ModuleName]) -- to construct downward closures
960 -> CmThreaded -- PCS & HST & HIT
961 -> IO () -- how to clean up unwanted tmp files
962 -> [SCC ModSummary] -- mods to do (the worklist)
963 -- ...... RETURNING ......
964 -> IO (Bool{-complete success?-},
966 [ModSummary], -- mods which succeeded
967 [Linkable]) -- new linkables
969 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
971 = return (True, threaded, [], [])
973 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
975 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
976 unwords (map (moduleNameUserString.modSummaryName) ms))
977 return (False, threaded, [], [])
979 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
980 ((AcyclicSCC mod):mods)
981 = do --case threaded of
982 -- CmThreaded pcsz hstz hitz
983 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
985 (threaded1, maybe_linkable)
986 <- upsweep_mod ghci_mode dflags oldUI threaded mod
987 (reachable_from (modSummaryName mod))
989 -- remove unwanted tmp files between compilations
992 case maybe_linkable of
994 -> -- No errors; do the rest
995 do (restOK, threaded2, modOKs, linkables)
996 <- upsweep_mods ghci_mode dflags oldUI reachable_from
997 threaded1 cleanup mods
998 return (restOK, threaded2, mod:modOKs, linkable:linkables)
999 Nothing -- we got a compilation error; give up now
1000 -> return (False, threaded1, [], [])
1003 -- Compile a single module. Always produce a Linkable for it if
1004 -- successful. If no compilation happened, return the old Linkable.
1005 upsweep_mod :: GhciMode
1011 -> IO (CmThreaded, Maybe Linkable)
1013 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1015 let mod_name = modSummaryName summary1
1017 let (CmThreaded pcs1 hst1 hit1) = threaded1
1018 let old_iface = lookupUFM hit1 mod_name
1020 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1022 source_unchanged = isJust maybe_old_linkable
1024 reachable_only = filter (/= (modSummaryName summary1))
1027 -- in interactive mode, all home modules below us *must* have an
1028 -- interface in the HIT. We never demand-load home interfaces in
1029 -- interactive mode.
1030 (hst1_strictDC, hit1_strictDC, [])
1031 = ASSERT(ghci_mode == Batch ||
1032 all (`elemUFM` hit1) reachable_only)
1033 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1036 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
1039 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1042 compresult <- compile ghci_mode summary1 source_unchanged
1043 have_object old_iface hst1_strictDC hit1_strictDC pcs1
1047 -- Compilation "succeeded", and may or may not have returned a new
1048 -- linkable (depending on whether compilation was actually performed
1050 CompOK pcs2 new_details new_iface maybe_new_linkable
1051 -> do let hst2 = addToUFM hst1 mod_name new_details
1052 hit2 = addToUFM hit1 mod_name new_iface
1053 threaded2 = CmThreaded pcs2 hst2 hit2
1055 return (threaded2, if isJust maybe_new_linkable
1056 then maybe_new_linkable
1057 else Just old_linkable)
1059 -- Compilation failed. compile may still have updated
1062 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1063 return (threaded2, Nothing)
1065 -- Filter modules in the top level envs (HST, HIT, UI).
1066 retainInTopLevelEnvs :: [ModuleName]
1067 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1068 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1069 retainInTopLevelEnvs keep_these (hst, hit, ui)
1070 = (retainInUFM hst keep_these,
1071 retainInUFM hit keep_these,
1072 filterModuleLinkables (`elem` keep_these) ui
1075 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1076 retainInUFM ufm keys_to_keep
1077 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1078 maybeLookupUFM ufm u
1079 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1081 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1082 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1083 downwards_closure_of_module summaries root
1084 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1085 toEdge summ = (modSummaryName summ,
1086 filter (`elem` all_mods) (ms_allimps summ))
1088 all_mods = map modSummaryName summaries
1090 res = simple_transitive_closure (map toEdge summaries) [root]
1092 -- trace (showSDoc (text "DC of mod" <+> ppr root
1093 -- <+> text "=" <+> ppr res)) $
1096 -- Calculate transitive closures from a set of roots given an adjacency list
1097 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1098 simple_transitive_closure graph set
1099 = let set2 = nub (concatMap dsts set ++ set)
1100 dsts node = fromMaybe [] (lookup node graph)
1102 if length set == length set2
1104 else simple_transitive_closure graph set2
1107 -- Calculate SCCs of the module graph, with or without taking into
1108 -- account source imports.
1109 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1110 topological_sort include_source_imports summaries
1112 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1114 = (summ, modSummaryName summ,
1115 (if include_source_imports
1116 then ms_srcimps summ else []) ++ ms_imps summ)
1118 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1119 mash_edge (summ, m, m_imports)
1120 = case lookup m key_map of
1121 Nothing -> panic "reverse_topological_sort"
1122 Just mk -> (summ, mk,
1123 -- ignore imports not from the home package
1124 catMaybes (map (flip lookup key_map) m_imports))
1126 edges = map toEdge summaries
1127 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1128 scc_input = map mash_edge edges
1129 sccs = stronglyConnComp scc_input
1134 -----------------------------------------------------------------------------
1135 -- Downsweep (dependency analysis)
1137 -- Chase downwards from the specified root set, returning summaries
1138 -- for all home modules encountered. Only follow source-import
1141 -- We pass in the previous collection of summaries, which is used as a
1142 -- cache to avoid recalculating a module summary if the source is
1145 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1146 downsweep roots old_summaries
1147 = do rootSummaries <- mapM getRootSummary roots
1149 <- loop (concat (map ms_imps rootSummaries))
1150 (mkModuleEnv [ (mod, s) | s <- rootSummaries,
1151 let mod = ms_mod s, isHomeModule mod
1153 return all_summaries
1155 getRootSummary :: FilePath -> IO ModSummary
1157 | haskellish_src_file file
1158 = do exists <- doesFileExist file
1159 if exists then summariseFile file else do
1160 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1162 = do exists <- doesFileExist hs_file
1163 if exists then summariseFile hs_file else do
1164 exists <- doesFileExist lhs_file
1165 if exists then summariseFile lhs_file else do
1166 let mod_name = mkModuleName file
1167 maybe_summary <- getSummary mod_name
1168 case maybe_summary of
1169 Nothing -> packageModErr mod_name
1172 hs_file = file ++ ".hs"
1173 lhs_file = file ++ ".lhs"
1175 getSummary :: ModuleName -> IO (Maybe ModSummary)
1177 = do found <- findModule nm
1179 Just (mod, location) -> do
1180 let old_summary = findModInSummaries old_summaries mod
1181 summarise mod location old_summary
1183 Nothing -> throwDyn (CmdLineError
1184 ("can't find module `"
1185 ++ showSDoc (ppr nm) ++ "'"))
1187 -- loop invariant: env doesn't contain package modules
1188 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1189 loop [] env = return (moduleEnvElts env)
1191 = do -- imports for modules we don't already have
1192 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1195 needed_summaries <- mapM getSummary needed_imps
1197 -- get just the "home" modules
1198 let new_home_summaries = [ s | Just s <- needed_summaries ]
1200 -- loop, checking the new imports
1201 let new_imps = concat (map ms_imps new_home_summaries)
1202 loop new_imps (extendModuleEnvList env
1203 [ (ms_mod s, s) | s <- new_home_summaries ])
1205 -----------------------------------------------------------------------------
1206 -- Summarising modules
1208 -- We have two types of summarisation:
1210 -- * Summarise a file. This is used for the root module(s) passed to
1211 -- cmLoadModules. The file is read, and used to determine the root
1212 -- module name. The module name may differ from the filename.
1214 -- * Summarise a module. We are given a module name, and must provide
1215 -- a summary. The finder is used to locate the file in which the module
1218 summariseFile :: FilePath -> IO ModSummary
1220 = do hspp_fn <- preprocess file
1221 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1223 let (path, basename, _ext) = splitFilename3 file
1226 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1229 <- case ml_hs_file location of
1230 Nothing -> noHsFileErr mod_name
1231 Just src_fn -> getModificationTime src_fn
1233 return (ModSummary mod
1234 location{ml_hspp_file=Just hspp_fn}
1235 srcimps imps src_timestamp)
1237 -- Summarise a module, and pick up source and timestamp.
1238 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1239 -> IO (Maybe ModSummary)
1240 summarise mod location old_summary
1241 | not (isHomeModule mod) = return Nothing
1243 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1245 case ml_hs_file location of {
1246 Nothing -> noHsFileErr mod;
1249 src_timestamp <- getModificationTime src_fn
1251 -- return the cached summary if the source didn't change
1252 case old_summary of {
1253 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1256 hspp_fn <- preprocess hs_fn
1257 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1259 when (mod_name /= moduleName mod) $
1260 throwDyn (ProgramError
1261 (showSDoc (text hs_fn
1262 <> text ": file name does not match module name"
1263 <+> quotes (ppr (moduleName mod)))))
1265 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1266 srcimps imps src_timestamp))
1272 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1275 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1276 quotes (ppr mod) <+>
1277 text "is a package module")))