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, isExternalName )
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
256 | isExternalName name,
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 ghci_mode ui1
545 mg2unsorted_names mg2_with_srcimps
547 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
549 -- uniq of ModuleName is the same as Module, fortunately...
550 let hit2 = delListFromUFM hit1 (map linkableModName new_linkables)
552 -- When (verb >= 2) $
553 -- putStrLn (showSDoc (text "Valid linkables:"
554 -- <+> ppr valid_linkables))
556 -- Figure out a stable set of modules which can be retained
557 -- the top level envs, to avoid upsweeping them. Goes to a
558 -- bit of trouble to avoid upsweeping module cycles.
560 -- Construct a set S of stable modules like this:
561 -- Travel upwards, over the sccified graph. For each scc
562 -- of modules ms, add ms to S only if:
563 -- 1. All home imports of ms are either in ms or S
564 -- 2. A valid old linkable exists for each module in ms
566 stable_mods <- preUpsweep valid_old_linkables
567 mg2unsorted_names [] mg2_with_srcimps
570 = concatMap (findInSummaries mg2unsorted) stable_mods
573 = filter (\m -> linkableModName m `elem` stable_mods)
577 putStrLn (showSDoc (text "Stable modules:"
578 <+> sep (map (text.moduleNameUserString) stable_mods)))
580 -- unload any modules which are going to be re-linked this
582 pls2 <- CmLink.unload ghci_mode dflags stable_linkables pls1
584 -- we can now glom together our linkable sets
585 let valid_linkables = valid_old_linkables ++ new_linkables
587 -- We could at this point detect cycles which aren't broken by
588 -- a source-import, and complain immediately, but it seems better
589 -- to let upsweep_mods do this, so at least some useful work gets
590 -- done before the upsweep is abandoned.
592 = filter (\scc -> any (`notElem` stable_mods)
593 (map modSummaryName (flattenSCC scc)))
596 --hPutStrLn stderr "after tsort:\n"
597 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
599 -- Because we don't take into account source imports when doing
600 -- the topological sort, there shouldn't be any cycles in mg2.
601 -- If there is, we complain and give up -- the user needs to
602 -- break the cycle using a boot file.
604 -- Now do the upsweep, calling compile for each module in
605 -- turn. Final result is version 3 of everything.
607 let threaded2 = CmThreaded pcs1 hst1 hit2
609 -- clean up between compilations
610 let cleanup = cleanTempFilesExcept verb
611 (ppFilesFromSummaries (flattenSCCs upsweep_these))
613 (upsweep_complete_success, threaded3, modsUpswept, newLis)
614 <- upsweep_mods ghci_mode dflags valid_linkables reachable_from
615 threaded2 cleanup upsweep_these
617 let ui3 = add_to_ui valid_linkables newLis
618 let (CmThreaded pcs3 hst3 hit3) = threaded3
620 -- At this point, modsUpswept and newLis should have the same
621 -- length, so there is one new (or old) linkable for each
622 -- mod which was processed (passed to compile).
624 -- Make modsDone be the summaries for each home module now
625 -- available; this should equal the domains of hst3 and hit3.
626 -- (NOT STRICTLY TRUE if an interactive session was started
627 -- with some object on disk ???)
628 -- Get in in a roughly top .. bottom order (hence reverse).
630 let modsDone = reverse modsUpswept ++ stable_summaries
632 -- Try and do linking in some form, depending on whether the
633 -- upsweep was completely or only partially successful.
635 if upsweep_complete_success
638 -- Easy; just relink it all.
639 do when (verb >= 2) $
640 hPutStrLn stderr "Upsweep completely successful."
642 -- clean up after ourselves
643 cleanTempFilesExcept verb (ppFilesFromSummaries modsDone)
645 -- issue a warning for the confusing case where the user said '-o foo'
646 -- but we're not going to do any linking.
647 ofile <- readIORef v_Output_file
648 when (ghci_mode == Batch && isJust ofile && not a_root_is_Main
650 hPutStrLn stderr "Warning: output was redirected with -o, but no output will be generated\nbecause there is no Main module."
652 -- link everything together
653 linkresult <- link ghci_mode dflags a_root_is_Main ui3 pls2
655 cmLoadFinish True linkresult
656 hst3 hit3 ui3 modsDone ghci_mode pcs3
659 -- Tricky. We need to back out the effects of compiling any
660 -- half-done cycles, both so as to clean up the top level envs
661 -- and to avoid telling the interactive linker to link them.
662 do when (verb >= 2) $
663 hPutStrLn stderr "Upsweep partially successful."
666 = map modSummaryName modsDone
667 let mods_to_zap_names
668 = findPartiallyCompletedCycles modsDone_names
671 = filter ((`notElem` mods_to_zap_names).modSummaryName)
674 let (hst4, hit4, ui4)
675 = retainInTopLevelEnvs (map modSummaryName mods_to_keep)
678 -- clean up after ourselves
679 cleanTempFilesExcept verb (ppFilesFromSummaries mods_to_keep)
681 -- link everything together
682 linkresult <- link ghci_mode dflags False ui4 pls2
684 cmLoadFinish False linkresult
685 hst4 hit4 ui4 mods_to_keep ghci_mode pcs3
688 -- Finish up after a cmLoad.
690 -- If the link failed, unload everything and return.
691 cmLoadFinish ok (LinkFailed pls) hst hit ui mods ghci_mode pcs = do
692 dflags <- getDynFlags
693 new_pls <- CmLink.unload ghci_mode dflags [] pls
694 new_state <- cmInit ghci_mode
695 return (new_state{ pcs=pcs, pls=new_pls }, False, [])
697 -- Empty the interactive context and set the module context to the topmost
698 -- newly loaded module, or the Prelude if none were loaded.
699 cmLoadFinish ok (LinkOK pls) hst hit ui mods ghci_mode pcs
700 = do let new_cmstate = CmState{ hst=hst, hit=hit, ui=ui, mg=mods,
701 gmode=ghci_mode, pcs=pcs, pls=pls,
702 ic = emptyInteractiveContext }
703 mods_loaded = map (moduleNameUserString.modSummaryName) mods
705 return (new_cmstate, ok, mods_loaded)
707 -- used to fish out the preprocess output files for the purposes
709 ppFilesFromSummaries summaries
710 = [ fn | Just fn <- map toPpFile summaries ]
713 | hspp /= ml_hs_file loc = hspp
714 | otherwise = Nothing
716 loc = ms_location sum
717 hspp = ml_hspp_file loc
720 -----------------------------------------------------------------------------
723 -- For each module (or SCC of modules), we take:
725 -- - an on-disk linkable, if this is the first time around and one
728 -- - the old linkable, otherwise (and if one is available).
730 -- and we throw away the linkable if it is older than the source file.
731 -- In interactive mode, we also ignore the on-disk linkables unless
732 -- all of the dependents of this SCC also have on-disk linkables (we
733 -- can't have dynamically loaded objects that depend on interpreted
736 -- If a module has a valid linkable, then it may be STABLE (see below),
737 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
740 -- ToDo: this pass could be merged with the preUpsweep.
744 -> [Linkable] -- old linkables
745 -> [ModuleName] -- all home modules
746 -> [SCC ModSummary] -- all modules in the program, dependency order
747 -> IO ( [Linkable], -- still-valid linkables
748 [Linkable] -- new linkables we just found
751 getValidLinkables mode old_linkables all_home_mods module_graph = do
752 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
754 return (partition_it ls [] [])
756 partition_it [] valid new = (valid,new)
757 partition_it ((l,b):ls) valid new
758 | b = partition_it ls valid (l:new)
759 | otherwise = partition_it ls (l:valid) new
762 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
764 scc = flattenSCC scc0
765 scc_names = map modSummaryName scc
766 home_module m = m `elem` all_home_mods && m `notElem` scc_names
767 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
768 -- NB. ms_imps, not ms_allimps above. We don't want to
769 -- force a module's SOURCE imports to be already compiled for
770 -- its object linkable to be valid.
773 case findModuleLinkable_maybe (map fst new_linkables) m of
775 Just l -> isObjectLinkable l
777 objects_allowed = mode == Batch || all has_object scc_allhomeimps
781 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
783 -- since an scc can contain only all objects or no objects at all,
784 -- we have to check whether we got all objects or not, and re-do
785 -- the linkable check if not.
788 && not (all isObjectLinkable (map fst new_linkables'))
789 then foldM (getValidLinkable old_linkables False) [] scc
790 else return new_linkables'
792 return (new_linkables ++ new_linkables')
795 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
796 -> IO [(Linkable,Bool)]
797 -- True <=> linkable is new
798 getValidLinkable old_linkables objects_allowed new_linkables summary
799 = do let mod_name = modSummaryName summary
802 <- if (not objects_allowed)
805 else case ml_obj_file (ms_location summary) of
806 Just obj_fn -> maybe_getFileLinkable mod_name obj_fn
807 Nothing -> return Nothing
809 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
812 case (old_linkable, maybe_disk_linkable) of
813 (Nothing, Nothing) -> []
815 -- new object linkable just appeared
816 (Nothing, Just l) -> up_to_date l True
819 | isObjectLinkable l -> []
820 -- object linkable disappeared! In case we need to
821 -- relink the module, disregard the old linkable and
822 -- just interpret the module from now on.
823 | otherwise -> up_to_date l False
824 -- old byte code linkable
827 | not (isObjectLinkable l) -> up_to_date l False
828 -- if the previous linkable was interpreted, then we
829 -- ignore a newly compiled version, because the version
830 -- numbers in the interface file will be out-of-sync with
831 -- our internal ones.
832 | linkableTime l' > linkableTime l -> up_to_date l' True
833 | linkableTime l' == linkableTime l -> up_to_date l False
835 -- on-disk linkable has been replaced by an older one!
836 -- again, disregard the previous one.
839 | linkableTime l < ms_hs_date summary = []
840 | otherwise = [(l,b)]
841 -- why '<' rather than '<=' above? If the filesystem stores
842 -- times to the nearset second, we may occasionally find that
843 -- the object & source have the same modification time,
844 -- especially if the source was automatically generated
845 -- and compiled. Using >= is slightly unsafe, but it matches
848 return (new_linkables' ++ new_linkables)
851 maybe_getFileLinkable :: ModuleName -> FilePath -> IO (Maybe Linkable)
852 maybe_getFileLinkable mod obj_fn
853 = do obj_exist <- doesFileExist obj_fn
857 do let stub_fn = case splitFilename3 obj_fn of
858 (dir, base, ext) -> dir ++ "/" ++ base ++ ".stub_o"
859 stub_exist <- doesFileExist stub_fn
860 obj_time <- getModificationTime obj_fn
862 then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
863 else return (Just (LM obj_time mod [DotO obj_fn]))
866 -----------------------------------------------------------------------------
867 -- Do a pre-upsweep without use of "compile", to establish a
868 -- (downward-closed) set of stable modules for which we won't call compile.
871 -- * has a valid linkable (see getValidLinkables above)
872 -- * depends only on stable modules
873 -- * has an interface in the HIT (interactive mode only)
875 preUpsweep :: [Linkable] -- new valid linkables
876 -> [ModuleName] -- names of all mods encountered in downsweep
877 -> [ModuleName] -- accumulating stable modules
878 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
879 -> IO [ModuleName] -- stable modules
881 preUpsweep valid_lis all_home_mods stable [] = return stable
882 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
883 = do let scc = flattenSCC scc0
884 scc_allhomeimps :: [ModuleName]
886 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
887 all_imports_in_scc_or_stable
888 = all in_stable_or_scc scc_allhomeimps
890 = map modSummaryName scc
892 = m `elem` scc_names || m `elem` stable
894 -- now we check for valid linkables: each module in the SCC must
895 -- have a valid linkable (see getValidLinkables above).
896 has_valid_linkable new_summary
897 = isJust (findModuleLinkable_maybe valid_lis modname)
898 where modname = modSummaryName new_summary
900 scc_is_stable = all_imports_in_scc_or_stable
901 && all has_valid_linkable scc
904 then preUpsweep valid_lis all_home_mods (scc_names++stable) sccs
905 else preUpsweep valid_lis all_home_mods stable sccs
908 -- Helper for preUpsweep. Assuming that new_summary's imports are all
909 -- stable (in the sense of preUpsweep), determine if new_summary is itself
910 -- stable, and, if so, in batch mode, return its linkable.
911 findInSummaries :: [ModSummary] -> ModuleName -> [ModSummary]
912 findInSummaries old_summaries mod_name
913 = [s | s <- old_summaries, modSummaryName s == mod_name]
915 findModInSummaries :: [ModSummary] -> Module -> Maybe ModSummary
916 findModInSummaries old_summaries mod
917 = case [s | s <- old_summaries, ms_mod s == mod] of
921 -- Return (names of) all those in modsDone who are part of a cycle
922 -- as defined by theGraph.
923 findPartiallyCompletedCycles :: [ModuleName] -> [SCC ModSummary] -> [ModuleName]
924 findPartiallyCompletedCycles modsDone theGraph
928 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
929 chew ((CyclicSCC vs):rest)
930 = let names_in_this_cycle = nub (map modSummaryName vs)
932 = nub ([done | done <- modsDone,
933 done `elem` names_in_this_cycle])
934 chewed_rest = chew rest
936 if notNull mods_in_this_cycle
937 && length mods_in_this_cycle < length names_in_this_cycle
938 then mods_in_this_cycle ++ chewed_rest
942 -- Add the given (LM-form) Linkables to the UI, overwriting previous
943 -- versions if they exist.
944 add_to_ui :: UnlinkedImage -> [Linkable] -> UnlinkedImage
946 = filter (not_in lis) ui ++ lis
948 not_in :: [Linkable] -> Linkable -> Bool
950 = all (\l -> linkableModName l /= mod) lis
951 where mod = linkableModName li
954 data CmThreaded -- stuff threaded through individual module compilations
955 = CmThreaded PersistentCompilerState HomeSymbolTable HomeIfaceTable
958 -- Compile multiple modules, stopping as soon as an error appears.
959 -- There better had not be any cyclic groups here -- we check for them.
960 upsweep_mods :: GhciMode
962 -> UnlinkedImage -- valid linkables
963 -> (ModuleName -> [ModuleName]) -- to construct downward closures
964 -> CmThreaded -- PCS & HST & HIT
965 -> IO () -- how to clean up unwanted tmp files
966 -> [SCC ModSummary] -- mods to do (the worklist)
967 -- ...... RETURNING ......
968 -> IO (Bool{-complete success?-},
970 [ModSummary], -- mods which succeeded
971 [Linkable]) -- new linkables
973 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
975 = return (True, threaded, [], [])
977 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
979 = do hPutStrLn stderr ("Module imports form a cycle for modules:\n\t" ++
980 unwords (map (moduleNameUserString.modSummaryName) ms))
981 return (False, threaded, [], [])
983 upsweep_mods ghci_mode dflags oldUI reachable_from threaded cleanup
984 ((AcyclicSCC mod):mods)
985 = do --case threaded of
986 -- CmThreaded pcsz hstz hitz
987 -- -> putStrLn ("UPSWEEP_MOD: hit = " ++ show (map (moduleNameUserString.moduleName.mi_module) (eltsUFM hitz)))
989 (threaded1, maybe_linkable)
990 <- upsweep_mod ghci_mode dflags oldUI threaded mod
991 (reachable_from (modSummaryName mod))
993 -- remove unwanted tmp files between compilations
996 case maybe_linkable of
998 -> -- No errors; do the rest
999 do (restOK, threaded2, modOKs, linkables)
1000 <- upsweep_mods ghci_mode dflags oldUI reachable_from
1001 threaded1 cleanup mods
1002 return (restOK, threaded2, mod:modOKs, linkable:linkables)
1003 Nothing -- we got a compilation error; give up now
1004 -> return (False, threaded1, [], [])
1007 -- Compile a single module. Always produce a Linkable for it if
1008 -- successful. If no compilation happened, return the old Linkable.
1009 upsweep_mod :: GhciMode
1015 -> IO (CmThreaded, Maybe Linkable)
1017 upsweep_mod ghci_mode dflags oldUI threaded1 summary1 reachable_inc_me
1019 let mod_name = modSummaryName summary1
1021 let (CmThreaded pcs1 hst1 hit1) = threaded1
1022 let old_iface = lookupUFM hit1 mod_name
1024 let maybe_old_linkable = findModuleLinkable_maybe oldUI mod_name
1026 source_unchanged = isJust maybe_old_linkable
1028 reachable_only = filter (/= (modSummaryName summary1))
1031 -- in interactive mode, all home modules below us *must* have an
1032 -- interface in the HIT. We never demand-load home interfaces in
1033 -- interactive mode.
1034 (hst1_strictDC, hit1_strictDC, [])
1035 = ASSERT(ghci_mode == Batch ||
1036 all (`elemUFM` hit1) reachable_only)
1037 retainInTopLevelEnvs reachable_only (hst1,hit1,[])
1040 = unJust "upsweep_mod:old_linkable" maybe_old_linkable
1043 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1046 compresult <- compile ghci_mode summary1 source_unchanged
1047 have_object old_iface hst1_strictDC hit1_strictDC pcs1
1051 -- Compilation "succeeded", and may or may not have returned a new
1052 -- linkable (depending on whether compilation was actually performed
1054 CompOK pcs2 new_details new_iface maybe_new_linkable
1055 -> do let hst2 = addToUFM hst1 mod_name new_details
1056 hit2 = addToUFM hit1 mod_name new_iface
1057 threaded2 = CmThreaded pcs2 hst2 hit2
1059 return (threaded2, if isJust maybe_new_linkable
1060 then maybe_new_linkable
1061 else Just old_linkable)
1063 -- Compilation failed. compile may still have updated
1066 -> do let threaded2 = CmThreaded pcs2 hst1 hit1
1067 return (threaded2, Nothing)
1069 -- Filter modules in the top level envs (HST, HIT, UI).
1070 retainInTopLevelEnvs :: [ModuleName]
1071 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1072 -> (HomeSymbolTable, HomeIfaceTable, UnlinkedImage)
1073 retainInTopLevelEnvs keep_these (hst, hit, ui)
1074 = (retainInUFM hst keep_these,
1075 retainInUFM hit keep_these,
1076 filterModuleLinkables (`elem` keep_these) ui
1079 retainInUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
1080 retainInUFM ufm keys_to_keep
1081 = listToUFM (concatMap (maybeLookupUFM ufm) keys_to_keep)
1082 maybeLookupUFM ufm u
1083 = case lookupUFM ufm u of Nothing -> []; Just val -> [(u, val)]
1085 -- Needed to clean up HIT and HST so that we don't get duplicates in inst env
1086 downwards_closure_of_module :: [ModSummary] -> ModuleName -> [ModuleName]
1087 downwards_closure_of_module summaries root
1088 = let toEdge :: ModSummary -> (ModuleName,[ModuleName])
1089 toEdge summ = (modSummaryName summ,
1090 filter (`elem` all_mods) (ms_allimps summ))
1092 all_mods = map modSummaryName summaries
1094 res = simple_transitive_closure (map toEdge summaries) [root]
1096 -- trace (showSDoc (text "DC of mod" <+> ppr root
1097 -- <+> text "=" <+> ppr res)) $
1100 -- Calculate transitive closures from a set of roots given an adjacency list
1101 simple_transitive_closure :: Eq a => [(a,[a])] -> [a] -> [a]
1102 simple_transitive_closure graph set
1103 = let set2 = nub (concatMap dsts set ++ set)
1104 dsts node = fromMaybe [] (lookup node graph)
1106 if length set == length set2
1108 else simple_transitive_closure graph set2
1111 -- Calculate SCCs of the module graph, with or without taking into
1112 -- account source imports.
1113 topological_sort :: Bool -> [ModSummary] -> [SCC ModSummary]
1114 topological_sort include_source_imports summaries
1116 toEdge :: ModSummary -> (ModSummary,ModuleName,[ModuleName])
1118 = (summ, modSummaryName summ,
1119 (if include_source_imports
1120 then ms_srcimps summ else []) ++ ms_imps summ)
1122 mash_edge :: (ModSummary,ModuleName,[ModuleName]) -> (ModSummary,Int,[Int])
1123 mash_edge (summ, m, m_imports)
1124 = case lookup m key_map of
1125 Nothing -> panic "reverse_topological_sort"
1126 Just mk -> (summ, mk,
1127 -- ignore imports not from the home package
1128 catMaybes (map (flip lookup key_map) m_imports))
1130 edges = map toEdge summaries
1131 key_map = zip [nm | (s,nm,imps) <- edges] [1 ..] :: [(ModuleName,Int)]
1132 scc_input = map mash_edge edges
1133 sccs = stronglyConnComp scc_input
1138 -----------------------------------------------------------------------------
1139 -- Downsweep (dependency analysis)
1141 -- Chase downwards from the specified root set, returning summaries
1142 -- for all home modules encountered. Only follow source-import
1145 -- We pass in the previous collection of summaries, which is used as a
1146 -- cache to avoid recalculating a module summary if the source is
1149 downsweep :: [FilePath] -> [ModSummary] -> IO [ModSummary]
1150 downsweep roots old_summaries
1151 = do rootSummaries <- mapM getRootSummary roots
1153 <- loop (concat (map ms_imps 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 mod_name
1172 case maybe_summary of
1173 Nothing -> packageModErr mod_name
1176 hs_file = file ++ ".hs"
1177 lhs_file = file ++ ".lhs"
1179 getSummary :: ModuleName -> IO (Maybe ModSummary)
1181 = do found <- findModule nm
1183 Just (mod, location) -> do
1184 let old_summary = findModInSummaries old_summaries mod
1185 summarise mod location old_summary
1187 Nothing -> throwDyn (CmdLineError
1188 ("can't find module `"
1189 ++ showSDoc (ppr nm) ++ "'"))
1191 -- loop invariant: env doesn't contain package modules
1192 loop :: [ModuleName] -> ModuleEnv ModSummary -> IO [ModSummary]
1193 loop [] env = return (moduleEnvElts env)
1195 = do -- imports for modules we don't already have
1196 let needed_imps = nub (filter (not . (`elemUFM` env)) imps)
1199 needed_summaries <- mapM getSummary needed_imps
1201 -- get just the "home" modules
1202 let new_home_summaries = [ s | Just s <- needed_summaries ]
1204 -- loop, checking the new imports
1205 let new_imps = concat (map ms_imps new_home_summaries)
1206 loop new_imps (extendModuleEnvList env
1207 [ (ms_mod s, s) | s <- new_home_summaries ])
1209 -----------------------------------------------------------------------------
1210 -- Summarising modules
1212 -- We have two types of summarisation:
1214 -- * Summarise a file. This is used for the root module(s) passed to
1215 -- cmLoadModules. The file is read, and used to determine the root
1216 -- module name. The module name may differ from the filename.
1218 -- * Summarise a module. We are given a module name, and must provide
1219 -- a summary. The finder is used to locate the file in which the module
1222 summariseFile :: FilePath -> IO ModSummary
1224 = do hspp_fn <- preprocess file
1225 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1227 let (path, basename, _ext) = splitFilename3 file
1230 <- mkHomeModuleLocn mod_name (path ++ '/':basename) file
1233 <- case ml_hs_file location of
1234 Nothing -> noHsFileErr mod_name
1235 Just src_fn -> getModificationTime src_fn
1237 return (ModSummary mod
1238 location{ml_hspp_file=Just hspp_fn}
1239 srcimps imps src_timestamp)
1241 -- Summarise a module, and pick up source and timestamp.
1242 summarise :: Module -> ModuleLocation -> Maybe ModSummary
1243 -> IO (Maybe ModSummary)
1244 summarise mod location old_summary
1245 | not (isHomeModule mod) = return Nothing
1247 = do let hs_fn = unJust "summarise" (ml_hs_file location)
1249 case ml_hs_file location of {
1250 Nothing -> noHsFileErr mod;
1253 src_timestamp <- getModificationTime src_fn
1255 -- return the cached summary if the source didn't change
1256 case old_summary of {
1257 Just s | ms_hs_date s == src_timestamp -> return (Just s);
1260 hspp_fn <- preprocess hs_fn
1261 (srcimps,imps,mod_name) <- getImportsFromFile hspp_fn
1263 when (mod_name /= moduleName mod) $
1264 throwDyn (ProgramError
1265 (showSDoc (text hs_fn
1266 <> text ": file name does not match module name"
1267 <+> quotes (ppr (moduleName mod)))))
1269 return (Just (ModSummary mod location{ml_hspp_file=Just hspp_fn}
1270 srcimps imps src_timestamp))
1276 = throwDyn (CmdLineError (showSDoc (text "no source file for module" <+> quotes (ppr mod))))
1279 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1280 quotes (ppr mod) <+>
1281 text "is a package module")))