2 % (c) The University of Glasgow, 2002
4 % The Compilation Manager
8 ModSummary, -- Abstract
9 ModuleGraph, -- All the modules from the home package
13 cmInit, -- :: GhciMode -> IO CmState
15 cmDepAnal, -- :: CmState -> [FilePath] -> IO ModuleGraph
17 cmTopSort, -- :: Bool -> ModuleGraph -> [SCC ModSummary]
18 cyclicModuleErr, -- :: [ModSummary] -> String -- Used by DriverMkDepend
20 cmLoadModules, -- :: CmState -> ModuleGraph
21 -- -> IO (CmState, Bool, [String])
23 cmUnload, -- :: CmState -> IO CmState
27 cmModuleIsInterpreted, -- :: CmState -> String -> IO Bool
29 cmSetContext, -- :: CmState -> [String] -> [String] -> IO CmState
30 cmGetContext, -- :: CmState -> IO ([String],[String])
32 cmGetInfo, -- :: CmState -> String -> IO (CmState, [(TyThing,Fixity)])
34 cmBrowseModule, -- :: CmState -> IO [TyThing]
38 cmRunStmt, -- :: CmState -> String -> IO (CmState, CmRunResult)
40 cmTypeOfExpr, -- :: CmState -> String -> IO (CmState, Maybe String)
41 cmKindOfType, -- :: CmState -> String -> IO (CmState, Maybe String)
42 cmTypeOfName, -- :: CmState -> Name -> IO (Maybe String)
45 cmCompileExpr, -- :: CmState -> String -> IO (CmState, Maybe HValue)
46 cmGetModuleGraph, -- :: CmState -> ModuleGraph
50 cmGetBindings, -- :: CmState -> [TyThing]
51 cmGetPrintUnqual, -- :: CmState -> PrintUnqualified
56 #include "HsVersions.h"
58 import Packages ( isHomePackage )
59 import DriverPipeline ( CompResult(..), preprocess, compile, link )
60 import HscMain ( newHscEnv )
61 import DriverState ( v_Output_file, v_NoHsMain, v_MainModIs )
62 import DriverPhases ( HscSource(..), hscSourceString, isHaskellSrcFilename )
63 import Finder ( findModule, findLinkable, addHomeModuleToFinder,
64 flushFinderCache, mkHomeModLocation, FindResult(..), cantFindError )
65 import HscTypes ( ModSummary(..), HomeModInfo(..), ModIface(..), msHsFilePath,
66 HscEnv(..), GhciMode(..), isBootSummary,
67 InteractiveContext(..), emptyInteractiveContext,
68 HomePackageTable, emptyHomePackageTable, IsBootInterface,
69 Linkable(..), isObjectLinkable )
70 import Module ( Module, mkModule, delModuleEnv, delModuleEnvList, mkModuleEnv,
71 lookupModuleEnv, moduleEnvElts, extendModuleEnv, filterModuleEnv,
72 moduleUserString, addBootSuffixLocn,
74 import GetImports ( getImports )
75 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
76 import ErrUtils ( showPass )
77 import SysTools ( cleanTempFilesExcept )
78 import BasicTypes ( SuccessFlag(..), succeeded )
79 import StringBuffer ( hGetStringBuffer )
83 import CmdLineOpts ( DynFlags(..) )
84 import Maybes ( expectJust, orElse, mapCatMaybes )
87 import DATA_IOREF ( readIORef )
90 import Finder ( findPackageModule )
91 import HscMain ( hscGetInfo, GetInfoResult, hscStmt, hscTcExpr, hscKcType )
92 import HscTypes ( TyThing(..), icPrintUnqual, showModMsg )
93 import TcRnDriver ( mkExportEnv, getModuleContents )
94 import IfaceSyn ( IfaceDecl )
95 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
99 import Type ( tidyType, dropForAlls )
100 import VarEnv ( emptyTidyEnv )
101 import Linker ( HValue, unload, extendLinkEnv )
102 import GHC.Exts ( unsafeCoerce# )
104 import Control.Exception as Exception ( Exception, try )
105 import CmdLineOpts ( DynFlag(..), dopt_unset, dopt )
108 import EXCEPTION ( throwDyn )
111 import Directory ( getModificationTime, doesFileExist )
119 %************************************************************************
121 The module dependency graph
122 ModSummary, ModGraph, NodeKey, NodeMap
124 %************************************************************************
126 The nodes of the module graph are
127 EITHER a regular Haskell source module
128 OR a hi-boot source module
130 A ModuleGraph contains all the nodes from the home package (only).
131 There will be a node for each source module, plus a node for each hi-boot
135 type ModuleGraph = [ModSummary] -- The module graph,
136 -- NOT NECESSARILY IN TOPOLOGICAL ORDER
138 emptyMG :: ModuleGraph
142 ms_allimps :: ModSummary -> [Module]
143 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
146 type NodeKey = (Module, HscSource) -- The nodes of the graph are
147 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
149 msKey :: ModSummary -> NodeKey
150 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
152 emptyNodeMap :: NodeMap a
153 emptyNodeMap = emptyFM
155 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
156 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
158 nodeMapElts :: NodeMap a -> [a]
163 %************************************************************************
165 The compilation manager state
167 %************************************************************************
171 -- Persistent state for the entire system
174 cm_hsc :: HscEnv, -- Includes the home-package table
175 cm_mg :: ModuleGraph, -- The module graph
176 cm_ic :: InteractiveContext -- Command-line binding info
180 cmGetModuleGraph cmstate = cm_mg cmstate
181 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
182 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
183 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
186 cmInit :: GhciMode -> DynFlags -> IO CmState
187 cmInit ghci_mode dflags
188 = do { hsc_env <- newHscEnv ghci_mode dflags
189 ; return (CmState { cm_hsc = hsc_env,
191 cm_ic = emptyInteractiveContext })}
193 discardCMInfo :: CmState -> CmState
194 -- Forget the compilation manager's state, including the home package table
195 -- but retain the persistent info in HscEnv
196 discardCMInfo cm_state
197 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
198 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
200 -------------------------------------------------------------------
201 -- The unlinked image
203 -- The compilation manager keeps a list of compiled, but as-yet unlinked
204 -- binaries (byte code or object code). Even when it links bytecode
205 -- it keeps the unlinked version so it can re-link it later without
208 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
210 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
211 findModuleLinkable_maybe lis mod
212 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
215 many -> pprPanic "findModuleLinkable" (ppr mod)
217 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
218 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
222 %************************************************************************
226 %************************************************************************
230 -----------------------------------------------------------------------------
231 -- Setting the context doesn't throw away any bindings; the bindings
232 -- we've built up in the InteractiveContext simply move to the new
233 -- module. They always shadow anything in scope in the current context.
237 -> [String] -- take the top-level scopes of these modules
238 -> [String] -- and the just the exports from these
240 cmSetContext cmstate toplevs exports = do
241 let old_ic = cm_ic cmstate
242 hsc_env = cm_hsc cmstate
243 hpt = hsc_HPT hsc_env
245 let export_mods = map mkModule exports
246 mapM_ (checkModuleExists (hsc_dflags hsc_env) hpt) export_mods
247 export_env <- mkExportEnv hsc_env export_mods
248 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
250 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
251 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
252 ic_exports = exports,
253 ic_rn_gbl_env = all_env } }
255 checkModuleExists :: DynFlags -> HomePackageTable -> Module -> IO ()
256 checkModuleExists dflags hpt mod =
257 case lookupModuleEnv hpt mod of
258 Just mod_info -> return ()
259 _not_a_home_module -> do
260 res <- findPackageModule dflags mod True
262 Found _ _ -> return ()
263 err -> let msg = cantFindError dflags mod err in
264 throwDyn (CmdLineError (showSDoc msg))
266 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
268 = case lookupModuleEnv hpt (mkModule mod) of
269 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
270 Just details -> case mi_globals (hm_iface details) of
271 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
272 Just env -> return env
274 cmGetContext :: CmState -> IO ([String],[String])
275 cmGetContext CmState{cm_ic=ic} =
276 return (ic_toplev_scope ic, ic_exports ic)
278 cmModuleIsInterpreted :: CmState -> String -> IO Bool
279 cmModuleIsInterpreted cmstate str
280 = case lookupModuleEnv (cmHPT cmstate) (mkModule str) of
281 Just details -> return (isJust (mi_globals (hm_iface details)))
282 _not_a_home_module -> return False
284 -----------------------------------------------------------------------------
286 cmSetDFlags :: CmState -> DynFlags -> CmState
287 cmSetDFlags cm_state dflags
288 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
290 cmGetDFlags :: CmState -> DynFlags
291 cmGetDFlags cm_state = hsc_dflags (cm_hsc cm_state)
293 -----------------------------------------------------------------------------
294 -- cmInfoThing: convert a String to a TyThing
296 -- A string may refer to more than one TyThing (eg. a constructor,
297 -- and type constructor), so we return a list of all the possible TyThings.
299 cmGetInfo :: CmState -> String -> IO [GetInfoResult]
300 cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
302 -- ---------------------------------------------------------------------------
303 -- cmBrowseModule: get all the TyThings defined in a module
305 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
306 cmBrowseModule cmstate str exports_only
307 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
308 (mkModule str) exports_only
310 Nothing -> return [] -- An error of some kind
315 -----------------------------------------------------------------------------
316 cmShowModule :: CmState -> ModSummary -> String
317 cmShowModule cmstate mod_summary
318 = case lookupModuleEnv hpt (ms_mod mod_summary) of
319 Nothing -> panic "missing linkable"
320 Just mod_info -> showModMsg obj_linkable mod_summary
322 obj_linkable = isObjectLinkable (hm_linkable mod_info)
324 hpt = hsc_HPT (cm_hsc cmstate)
326 -----------------------------------------------------------------------------
327 -- cmRunStmt: Run a statement/expr.
330 = CmRunOk [Name] -- names bound by this evaluation
332 | CmRunException Exception -- statement raised an exception
334 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
335 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
337 -- Turn off -fwarn-unused-bindings when running a statement, to hide
338 -- warnings about the implicit bindings we introduce.
339 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
340 hsc_env' = hsc_env{ hsc_dflags = dflags' }
342 maybe_stuff <- hscStmt hsc_env' icontext expr
345 Nothing -> return (cmstate, CmRunFailed)
346 Just (new_ic, names, hval) -> do
348 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
349 either_hvals <- sandboxIO thing_to_run
353 -- on error, keep the *old* interactive context,
354 -- so that 'it' is not bound to something
355 -- that doesn't exist.
356 return ( cmstate, CmRunException e )
359 -- Get the newly bound things, and bind them.
360 -- Don't need to delete any shadowed bindings;
361 -- the new ones override the old ones.
362 extendLinkEnv (zip names hvals)
364 return (cmstate{ cm_ic=new_ic },
368 -- We run the statement in a "sandbox" to protect the rest of the
369 -- system from anything the expression might do. For now, this
370 -- consists of just wrapping it in an exception handler, but see below
371 -- for another version.
373 sandboxIO :: IO a -> IO (Either Exception a)
374 sandboxIO thing = Exception.try thing
377 -- This version of sandboxIO runs the expression in a completely new
378 -- RTS main thread. It is disabled for now because ^C exceptions
379 -- won't be delivered to the new thread, instead they'll be delivered
380 -- to the (blocked) GHCi main thread.
382 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
384 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
386 st_thing <- newStablePtr (Exception.try thing)
387 alloca $ \ p_st_result -> do
388 stat <- rts_evalStableIO st_thing p_st_result
389 freeStablePtr st_thing
391 then do st_result <- peek p_st_result
392 result <- deRefStablePtr st_result
393 freeStablePtr st_result
394 return (Right result)
396 return (Left (fromIntegral stat))
398 foreign import "rts_evalStableIO" {- safe -}
399 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
400 -- more informative than the C type!
403 -----------------------------------------------------------------------------
404 -- cmTypeOfExpr: returns a string representing the type of an expression
406 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
407 cmTypeOfExpr cmstate expr
408 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
411 Nothing -> return Nothing
412 Just ty -> return (Just (showSDocForUser unqual doc))
414 doc = text expr <+> dcolon <+> ppr final_ty
415 unqual = icPrintUnqual (cm_ic cmstate)
416 tidy_ty = tidyType emptyTidyEnv ty
417 dflags = hsc_dflags (cm_hsc cmstate)
418 -- if -fglasgow-exts is on we show the foralls, otherwise
421 | dopt Opt_GlasgowExts dflags = tidy_ty
422 | otherwise = dropForAlls tidy_ty
424 -----------------------------------------------------------------------------
425 -- cmKindOfType: returns a string representing the kind of a type
427 cmKindOfType :: CmState -> String -> IO (Maybe String)
428 cmKindOfType cmstate str
429 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
431 Nothing -> return Nothing
432 Just kind -> return (Just res_str)
434 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
435 unqual = icPrintUnqual (cm_ic cmstate)
437 -----------------------------------------------------------------------------
438 -- cmTypeOfName: returns a string representing the type of a name.
440 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
441 cmTypeOfName CmState{ cm_ic=ic } name
443 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
444 case lookupNameEnv (ic_type_env ic) name of
445 Nothing -> return Nothing
446 Just (AnId id) -> return (Just str)
448 unqual = icPrintUnqual ic
449 ty = tidyType emptyTidyEnv (idType id)
450 str = showSDocForUser unqual (ppr ty)
452 _ -> panic "cmTypeOfName"
454 -----------------------------------------------------------------------------
455 -- cmCompileExpr: compile an expression and deliver an HValue
457 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
458 cmCompileExpr cmstate expr
461 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
462 ("let __cmCompileExpr = "++expr)
465 Nothing -> return Nothing
466 Just (new_ic, names, hval) -> do
469 hvals <- (unsafeCoerce# hval) :: IO [HValue]
471 case (names,hvals) of
472 ([n],[hv]) -> return (Just hv)
473 _ -> panic "cmCompileExpr"
479 %************************************************************************
481 Loading and unloading
483 %************************************************************************
486 -----------------------------------------------------------------------------
487 -- Unload the compilation manager's state: everything it knows about the
488 -- current collection of modules in the Home package.
490 cmUnload :: CmState -> IO CmState
491 cmUnload state@CmState{ cm_hsc = hsc_env }
492 = do -- Throw away the old home dir cache
495 -- Unload everything the linker knows about
498 -- Start with a fresh CmState, but keep the PersistentCompilerState
499 return (discardCMInfo state)
501 cm_unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
502 = case hsc_mode hsc_env of
505 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
507 Interactive -> panic "cm_unload: no interpreter"
509 other -> panic "cm_unload: strange mode"
512 -----------------------------------------------------------------------------
513 -- Trace dependency graph
515 -- This is a seperate pass so that the caller can back off and keep
516 -- the current state if the downsweep fails. Typically the caller
517 -- might go cmDepAnal
520 -- He wants to do the dependency analysis before the unload, so that
521 -- if the former fails he can use the later
523 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
524 cmDepAnal cmstate rootnames
525 = do showPass dflags "Chasing dependencies"
526 when (verbosity dflags >= 1 && gmode == Batch) $
527 hPutStrLn stderr (showSDoc (hcat [
528 text "Chasing modules from: ",
529 hcat (punctuate comma (map text rootnames))]))
530 cmDownsweep dflags rootnames (cm_mg cmstate) []
532 hsc_env = cm_hsc cmstate
533 dflags = hsc_dflags hsc_env
534 gmode = hsc_mode hsc_env
536 -----------------------------------------------------------------------------
537 -- The real business of the compilation manager: given a system state and
538 -- a module name, try and bring the module up to date, probably changing
539 -- the system state at the same time.
541 cmLoadModules :: CmState -- The HPT may not be as up to date
542 -> ModuleGraph -- Bang up to date; but may contain hi-boot no
543 -> IO (CmState, -- new state
544 SuccessFlag, -- was successful
545 [String]) -- list of modules loaded
547 cmLoadModules cmstate1 mg2unsorted
548 = do -- version 1's are the original, before downsweep
549 let hsc_env = cm_hsc cmstate1
550 let hpt1 = hsc_HPT hsc_env
551 let ghci_mode = hsc_mode hsc_env -- this never changes
552 let dflags = hsc_dflags hsc_env -- this never changes
553 let verb = verbosity dflags
555 -- The "bad" boot modules are the ones for which we have
556 -- B.hs-boot in the module graph, but no B.hs
557 let all_home_mods = [ms_mod s | s <- mg2unsorted, not (isBootSummary s)]
558 bad_boot_mods = [s | s <- mg2unsorted, isBootSummary s,
559 not (ms_mod s `elem` all_home_mods)]
561 if not (null bad_boot_mods)
562 then do { mapM reportBadBootMod bad_boot_mods
563 ; return (cmstate1, Failed, []) }
566 -- Do the downsweep to reestablish the module graph
567 -- mg2 should be cycle free; but it includes hi-boot ModSummary nodes
568 let mg2 :: [SCC ModSummary]
569 mg2 = cmTopSort False mg2unsorted
571 -- mg2_with_srcimps drops the hi-boot nodes, returning a
572 -- graph with cycles. Among other things, it is used for
573 -- backing out partially complete cycles following a failed
574 -- upsweep, and for removing from hpt all the modules
575 -- not in strict downwards closure, during calls to compile.
576 let mg2_with_srcimps :: [SCC ModSummary]
577 mg2_with_srcimps = cmTopSort True mg2unsorted
579 -- Sort out which linkables we wish to keep in the unlinked image.
580 -- See getValidLinkables below for details.
581 (valid_old_linkables, new_linkables)
582 <- getValidLinkables ghci_mode (hptLinkables hpt1)
583 all_home_mods mg2_with_srcimps
585 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
587 -- The new_linkables are .o files we found on the disk, presumably
588 -- as a result of a GHC run "on the side". So we'd better forget
589 -- everything we know abouut those modules!
590 let old_hpt = delModuleEnvList hpt1 (map linkableModule new_linkables)
592 -- When (verb >= 2) $
593 -- putStrLn (showSDoc (text "Valid linkables:"
594 -- <+> ppr valid_linkables))
596 -- Figure out a stable set of modules which can be retained
597 -- the top level envs, to avoid upsweeping them. Goes to a
598 -- bit of trouble to avoid upsweeping module cycles.
600 -- Construct a set S of stable modules like this:
601 -- Travel upwards, over the sccified graph. For each scc
602 -- of modules ms, add ms to S only if:
603 -- 1. All home imports of ms are either in ms or S
604 -- 2. A valid old linkable exists for each module in ms
606 -- mg2_with_srcimps has no hi-boot nodes,
607 -- and hence neither does stable_mods
608 stable_summaries <- preUpsweep valid_old_linkables
609 all_home_mods [] mg2_with_srcimps
610 let stable_mods = map ms_mod stable_summaries
611 stable_linkables = filter (\m -> linkableModule m `elem` stable_mods)
614 stable_hpt = filterModuleEnv is_stable_hm hpt1
615 is_stable_hm hm_info = mi_module (hm_iface hm_info) `elem` stable_mods
618 = filter (\scc -> any (`notElem` stable_mods)
619 (map ms_mod (flattenSCC scc)))
623 hPutStrLn stderr (showSDoc (text "Stable modules:"
624 <+> sep (map (text.moduleUserString) stable_mods)))
626 -- Unload any modules which are going to be re-linked this time around.
627 cm_unload hsc_env stable_linkables
629 -- We can now glom together our linkable sets
630 let valid_linkables = valid_old_linkables ++ new_linkables
632 -- We could at this point detect cycles which aren't broken by
633 -- a source-import, and complain immediately, but it seems better
634 -- to let upsweep_mods do this, so at least some useful work gets
635 -- done before the upsweep is abandoned.
636 --hPutStrLn stderr "after tsort:\n"
637 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
639 -- Because we don't take into account source imports when doing
640 -- the topological sort, there shouldn't be any cycles in mg2.
641 -- If there is, we complain and give up -- the user needs to
642 -- break the cycle using a boot file.
644 -- Now do the upsweep, calling compile for each module in
645 -- turn. Final result is version 3 of everything.
647 -- clean up between compilations
648 let cleanup = cleanTempFilesExcept dflags
649 (ppFilesFromSummaries (flattenSCCs mg2))
651 (upsweep_ok, hsc_env3, modsUpswept)
652 <- upsweep_mods (hsc_env { hsc_HPT = stable_hpt })
653 (old_hpt, valid_linkables)
654 cleanup upsweep_these
656 -- At this point, modsUpswept and newLis should have the same
657 -- length, so there is one new (or old) linkable for each
658 -- mod which was processed (passed to compile).
660 -- Make modsDone be the summaries for each home module now
661 -- available; this should equal the domain of hpt3.
662 -- (NOT STRICTLY TRUE if an interactive session was started
663 -- with some object on disk ???)
664 -- Get in in a roughly top .. bottom order (hence reverse).
666 let modsDone = reverse modsUpswept ++ stable_summaries
668 -- Try and do linking in some form, depending on whether the
669 -- upsweep was completely or only partially successful.
671 if succeeded upsweep_ok
674 -- Easy; just relink it all.
675 do when (verb >= 2) $
676 hPutStrLn stderr "Upsweep completely successful."
678 -- Clean up after ourselves
679 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
682 -- Issue a warning for the confusing case where the user
683 -- said '-o foo' but we're not going to do any linking.
684 -- We attempt linking if either (a) one of the modules is
685 -- called Main, or (b) the user said -no-hs-main, indicating
686 -- that main() is going to come from somewhere else.
688 ofile <- readIORef v_Output_file
689 no_hs_main <- readIORef v_NoHsMain
690 mb_main_mod <- readIORef v_MainModIs
692 main_mod = mb_main_mod `orElse` "Main"
694 = any ((==main_mod).moduleUserString.ms_mod)
696 do_linking = a_root_is_Main || no_hs_main
698 when (ghci_mode == Batch && isJust ofile && not do_linking
700 hPutStrLn stderr ("Warning: output was redirected with -o, " ++
701 "but no output will be generated\n" ++
702 "because there is no " ++ main_mod ++ " module.")
704 -- link everything together
705 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
707 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
708 cmLoadFinish Succeeded linkresult cmstate3
711 -- Tricky. We need to back out the effects of compiling any
712 -- half-done cycles, both so as to clean up the top level envs
713 -- and to avoid telling the interactive linker to link them.
714 do when (verb >= 2) $
715 hPutStrLn stderr "Upsweep partially successful."
718 = map ms_mod modsDone
719 let mods_to_zap_names
720 = findPartiallyCompletedCycles modsDone_names
723 = filter ((`notElem` mods_to_zap_names).ms_mod)
726 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
729 -- Clean up after ourselves
730 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
732 -- Link everything together
733 linkresult <- link ghci_mode dflags False hpt4
735 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
736 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
737 cmLoadFinish Failed linkresult cmstate3
739 reportBadBootMod :: ModSummary -> IO ()
741 = hPutStrLn stderr $ showSDoc $
742 ptext SLIT("Module") <+> quotes (ppr (ms_mod s)) <+>
743 ptext SLIT("is {-# SOURCE #-} imported, but nowhere imported ordinarily")
745 -- Finish up after a cmLoad.
747 -- If the link failed, unload everything and return.
748 cmLoadFinish ok Failed cmstate
749 = do cm_unload (cm_hsc cmstate) []
750 return (discardCMInfo cmstate, Failed, [])
752 -- Empty the interactive context and set the module context to the topmost
753 -- newly loaded module, or the Prelude if none were loaded.
754 cmLoadFinish ok Succeeded cmstate
755 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
756 mods_loaded = map (moduleUserString.ms_mod)
759 return (new_cmstate, ok, mods_loaded)
761 -- used to fish out the preprocess output files for the purposes of
762 -- cleaning up. The preprocessed file *might* be the same as the
763 -- source file, but that doesn't do any harm.
764 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
766 -----------------------------------------------------------------------------
769 -- For each module (or SCC of modules), we take:
771 -- - an on-disk linkable, if this is the first time around and one
774 -- - the old linkable, otherwise (and if one is available).
776 -- and we throw away the linkable if it is older than the source file.
777 -- In interactive mode, we also ignore the on-disk linkables unless
778 -- all of the dependents of this SCC also have on-disk linkables (we
779 -- can't have dynamically loaded objects that depend on interpreted
782 -- If a module has a valid linkable, then it may be STABLE (see below),
783 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
786 -- ToDo: this pass could be merged with the preUpsweep.
790 -> [Linkable] -- old linkables
791 -> [Module] -- all home modules
792 -> [SCC ModSummary] -- all modules in the program, dependency order
793 -> IO ( [Linkable], -- still-valid linkables
794 [Linkable] -- new linkables we just found on the disk
795 -- presumably generated by separate run of ghc
798 getValidLinkables mode old_linkables all_home_mods module_graph
799 = do { -- Process the SCCs in bottom-to-top order
800 -- (foldM works left-to-right)
801 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
803 ; return (partition_it ls [] []) }
805 partition_it [] valid new = (valid,new)
806 partition_it ((l,b):ls) valid new
807 | b = partition_it ls valid (l:new)
808 | otherwise = partition_it ls (l:valid) new
813 -> [Linkable] -- old linkables
814 -> [Module] -- all home modules
817 -> IO [(Linkable,Bool)]
819 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
821 scc = flattenSCC scc0
822 scc_names = map ms_mod scc
823 home_module m = m `elem` all_home_mods && m `notElem` scc_names
824 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
825 -- NB. ms_imps, not ms_allimps above. We don't want to
826 -- force a module's SOURCE imports to be already compiled for
827 -- its object linkable to be valid.
829 -- The new_linkables is only the *valid* linkables below here
830 has_object m = case findModuleLinkable_maybe (map fst new_linkables) m of
832 Just l -> isObjectLinkable l
834 objects_allowed = mode == Batch || all has_object scc_allhomeimps
838 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
840 -- since an scc can contain only all objects or no objects at all,
841 -- we have to check whether we got all objects or not, and re-do
842 -- the linkable check if not.
845 && not (all isObjectLinkable (map fst new_linkables'))
846 then foldM (getValidLinkable old_linkables False) [] scc
847 else return new_linkables'
849 return (new_linkables ++ new_linkables')
852 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
853 -> IO [(Linkable,Bool)]
854 -- True <=> linkable is new; i.e. freshly discovered on the disk
855 -- presumably generated 'on the side'
856 -- by a separate GHC run
857 getValidLinkable old_linkables objects_allowed new_linkables summary
858 -- 'objects_allowed' says whether we permit this module to
859 -- have a .o-file linkable. We only permit it if all the
860 -- modules it depends on also have .o files; a .o file can't
861 -- link to a bytecode module
862 = do let mod_name = ms_mod summary
865 <- if (not objects_allowed)
868 else findLinkable mod_name (ms_location summary)
870 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
873 case (old_linkable, maybe_disk_linkable) of
874 (Nothing, Nothing) -> []
876 -- new object linkable just appeared
877 (Nothing, Just l) -> up_to_date l True
880 | isObjectLinkable l -> []
881 -- object linkable disappeared! In case we need to
882 -- relink the module, disregard the old linkable and
883 -- just interpret the module from now on.
884 | otherwise -> up_to_date l False
885 -- old byte code linkable
888 | not (isObjectLinkable l) -> up_to_date l False
889 -- if the previous linkable was interpreted, then we
890 -- ignore a newly compiled version, because the version
891 -- numbers in the interface file will be out-of-sync with
892 -- our internal ones.
893 | linkableTime l' > linkableTime l -> up_to_date l' True
894 | linkableTime l' == linkableTime l -> up_to_date l False
896 -- on-disk linkable has been replaced by an older one!
897 -- again, disregard the previous one.
900 | linkableTime l < ms_hs_date summary = []
901 | otherwise = [(l,b)]
902 -- why '<' rather than '<=' above? If the filesystem stores
903 -- times to the nearset second, we may occasionally find that
904 -- the object & source have the same modification time,
905 -- especially if the source was automatically generated
906 -- and compiled. Using >= is slightly unsafe, but it matches
909 return (new_linkables' ++ new_linkables)
912 hptLinkables :: HomePackageTable -> [Linkable]
913 -- Get all the linkables from the home package table, one for each module
914 -- Once the HPT is up to date, these are the ones we should link
915 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
918 -----------------------------------------------------------------------------
919 -- Do a pre-upsweep without use of "compile", to establish a
920 -- (downward-closed) set of stable modules for which we won't call compile.
923 -- * has a valid linkable (see getValidLinkables above)
924 -- * depends only on stable modules
925 -- * has an interface in the HPT (interactive mode only)
927 preUpsweep :: [Linkable] -- new valid linkables
928 -> [Module] -- names of all mods encountered in downsweep
929 -> [ModSummary] -- accumulating stable modules
930 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
931 -> IO [ModSummary] -- stable modules
933 preUpsweep valid_lis all_home_mods stable [] = return stable
934 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
935 = do let scc = flattenSCC scc0
936 scc_allhomeimps :: [Module]
938 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
939 all_imports_in_scc_or_stable
940 = all in_stable_or_scc scc_allhomeimps
941 scc_mods = map ms_mod scc
942 stable_names = scc_mods ++ map ms_mod stable
943 in_stable_or_scc m = m `elem` stable_names
945 -- now we check for valid linkables: each module in the SCC must
946 -- have a valid linkable (see getValidLinkables above).
947 has_valid_linkable scc_mod
948 = isJust (findModuleLinkable_maybe valid_lis scc_mod)
950 scc_is_stable = all_imports_in_scc_or_stable
951 && all has_valid_linkable scc_mods
954 then preUpsweep valid_lis all_home_mods (scc ++ stable) sccs
955 else preUpsweep valid_lis all_home_mods stable sccs
958 -- Return (names of) all those in modsDone who are part of a cycle
959 -- as defined by theGraph.
960 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
961 findPartiallyCompletedCycles modsDone theGraph
965 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
966 chew ((CyclicSCC vs):rest)
967 = let names_in_this_cycle = nub (map ms_mod vs)
969 = nub ([done | done <- modsDone,
970 done `elem` names_in_this_cycle])
971 chewed_rest = chew rest
973 if notNull mods_in_this_cycle
974 && length mods_in_this_cycle < length names_in_this_cycle
975 then mods_in_this_cycle ++ chewed_rest
979 -- Compile multiple modules, stopping as soon as an error appears.
980 -- There better had not be any cyclic groups here -- we check for them.
981 upsweep_mods :: HscEnv -- Includes initially-empty HPT
982 -> (HomePackageTable, [Linkable]) -- HPT and valid linkables from last time round
983 -> IO () -- How to clean up unwanted tmp files
984 -> [SCC ModSummary] -- Mods to do (the worklist)
986 HscEnv, -- With an updated HPT
987 [ModSummary]) -- Mods which succeeded
989 upsweep_mods hsc_env oldUI cleanup
991 = return (Succeeded, hsc_env, [])
993 upsweep_mods hsc_env oldUI cleanup
995 = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
996 return (Failed, hsc_env, [])
998 upsweep_mods hsc_env oldUI@(old_hpt, old_linkables) cleanup
999 (AcyclicSCC mod:mods)
1000 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1001 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1002 -- (moduleEnvElts (hsc_HPT hsc_env)))
1004 mb_mod_info <- upsweep_mod hsc_env oldUI mod
1006 cleanup -- Remove unwanted tmp files between compilations
1009 Nothing -> return (Failed, hsc_env, [])
1011 { let this_mod = ms_mod mod
1013 -- Add new info to hsc_env
1014 hpt1 = extendModuleEnv (hsc_HPT hsc_env) this_mod mod_info
1015 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1017 -- Space-saving: delete the old HPT entry and linkable for mod
1018 -- BUT if mod is a hs-boot node, don't delete it
1019 -- For the linkable this is dead right: the linkable relates only
1020 -- to the main Haskell source file.
1021 -- For the interface, the HPT entry is probaby for the main Haskell
1022 -- source file. Deleting it would force
1023 oldUI1 | isBootSummary mod = oldUI
1025 = (delModuleEnv old_hpt this_mod,
1026 delModuleLinkable old_linkables this_mod)
1028 ; (restOK, hsc_env2, modOKs) <- upsweep_mods hsc_env1 oldUI1 cleanup mods
1029 ; return (restOK, hsc_env2, mod:modOKs) }
1032 -- Compile a single module. Always produce a Linkable for it if
1033 -- successful. If no compilation happened, return the old Linkable.
1034 upsweep_mod :: HscEnv
1035 -> (HomePackageTable, UnlinkedImage)
1037 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1039 upsweep_mod hsc_env (old_hpt, old_linkables) summary
1041 let this_mod = ms_mod summary
1043 -- The old interface is ok if it's in the old HPT
1044 -- a) we're compiling a source file, and the old HPT entry is for a source file
1045 -- b) we're compiling a hs-boot file
1046 -- Case (b) allows an hs-boot file to get the interface of its real source file
1047 -- on the second iteration of the compilation manager, but that does no harm.
1048 -- Otherwise the hs-boot file will always be recompiled
1050 = case lookupModuleEnv old_hpt this_mod of
1052 Just hm_info | isBootSummary summary -> Just iface
1053 | not (mi_boot iface) -> Just iface
1054 | otherwise -> Nothing
1056 iface = hm_iface hm_info
1058 maybe_old_linkable = findModuleLinkable_maybe old_linkables this_mod
1059 source_unchanged = isJust maybe_old_linkable
1061 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1064 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1067 compresult <- compile hsc_env summary source_unchanged have_object mb_old_iface
1071 -- Compilation "succeeded", and may or may not have returned a new
1072 -- linkable (depending on whether compilation was actually performed
1074 CompOK new_details new_iface maybe_new_linkable
1076 new_linkable = maybe_new_linkable `orElse` old_linkable
1077 new_info = HomeModInfo { hm_iface = new_iface,
1078 hm_details = new_details,
1079 hm_linkable = new_linkable }
1080 return (Just new_info)
1082 -- Compilation failed. Compile may still have updated the PCS, tho.
1083 CompErrs -> return Nothing
1085 -- Filter modules in the HPT
1086 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1087 retainInTopLevelEnvs keep_these hpt
1088 = mkModuleEnv [ (mod, fromJust mb_mod_info)
1090 , let mb_mod_info = lookupModuleEnv hpt mod
1091 , isJust mb_mod_info ]
1093 -----------------------------------------------------------------------------
1094 cmTopSort :: Bool -- Drop hi-boot nodes? (see below)
1097 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1099 -- Drop hi-boot nodes (first boolean arg)?
1101 -- False: treat the hi-boot summaries as nodes of the graph,
1102 -- so the graph must be acyclic
1104 -- True: eliminate the hi-boot nodes, and instead pretend
1105 -- the a source-import of Foo is an import of Foo
1106 -- The resulting graph has no hi-boot nodes, but can by cyclic
1108 cmTopSort drop_hs_boot_nodes summaries
1109 = stronglyConnComp nodes
1111 -- Drop hs-boot nodes by using HsSrcFile as the key
1112 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1113 | otherwise = HsBootFile
1115 -- We use integers as the keys for the SCC algorithm
1116 nodes :: [(ModSummary, Int, [Int])]
1117 nodes = [(s, fromJust (lookup_key (ms_hsc_src s) (ms_mod s)),
1118 out_edge_keys hs_boot_key (ms_srcimps s) ++
1119 out_edge_keys HsSrcFile (ms_imps s) )
1121 , not (isBootSummary s && drop_hs_boot_nodes) ]
1122 -- Drop the hi-boot ones if told to do so
1124 key_map :: NodeMap Int
1125 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1128 lookup_key :: HscSource -> Module -> Maybe Int
1129 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1131 out_edge_keys :: HscSource -> [Module] -> [Int]
1132 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1133 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1134 -- the IsBootInterface parameter True; else False
1137 -----------------------------------------------------------------------------
1138 -- Downsweep (dependency analysis)
1140 -- Chase downwards from the specified root set, returning summaries
1141 -- for all home modules encountered. Only follow source-import
1144 -- We pass in the previous collection of summaries, which is used as a
1145 -- cache to avoid recalculating a module summary if the source is
1148 -- The returned list of [ModSummary] nodes has one node for each home-package
1149 -- module, plus one for any hs-boot files. The imports of these nodes
1150 -- are all there, including the imports of non-home-package modules.
1152 cmDownsweep :: DynFlags
1153 -> [FilePath] -- Roots
1154 -> [ModSummary] -- Old summaries
1155 -> [Module] -- Ignore dependencies on these; treat them as
1156 -- if they were package modules
1158 cmDownsweep dflags roots old_summaries excl_mods
1159 = do rootSummaries <- mapM getRootSummary roots
1160 checkDuplicates rootSummaries
1161 loop (concatMap msImports rootSummaries)
1162 (mkNodeMap rootSummaries)
1164 old_summary_map :: NodeMap ModSummary
1165 old_summary_map = mkNodeMap old_summaries
1167 getRootSummary :: FilePath -> IO ModSummary
1169 | isHaskellSrcFilename file
1170 = do exists <- doesFileExist file
1171 if exists then summariseFile dflags file else do
1172 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1174 = do exists <- doesFileExist hs_file
1175 if exists then summariseFile dflags hs_file else do
1176 exists <- doesFileExist lhs_file
1177 if exists then summariseFile dflags lhs_file else do
1178 let mod_name = mkModule file
1179 maybe_summary <- summarise dflags emptyNodeMap Nothing False
1181 case maybe_summary of
1182 Nothing -> packageModErr mod_name
1185 hs_file = file ++ ".hs"
1186 lhs_file = file ++ ".lhs"
1188 -- In a root module, the filename is allowed to diverge from the module
1189 -- name, so we have to check that there aren't multiple root files
1190 -- defining the same module (otherwise the duplicates will be silently
1191 -- ignored, leading to confusing behaviour).
1192 checkDuplicates :: [ModSummary] -> IO ()
1193 checkDuplicates summaries = mapM_ check summaries
1198 many -> multiRootsErr modl many
1199 where modl = ms_mod summ
1201 [ fromJust (ml_hs_file (ms_location summ'))
1202 | summ' <- summaries, ms_mod summ' == modl ]
1204 loop :: [(FilePath,Module,IsBootInterface)] -- Work list: process these modules
1205 -> NodeMap ModSummary -- Visited set
1206 -> IO [ModSummary] -- The result includes the worklist, except
1207 -- for those mentioned in the visited set
1208 loop [] done = return (nodeMapElts done)
1209 loop ((cur_path, wanted_mod, is_boot) : ss) done
1210 | key `elemFM` done = loop ss done
1211 | otherwise = do { mb_s <- summarise dflags old_summary_map
1212 (Just cur_path) is_boot
1213 wanted_mod excl_mods
1215 Nothing -> loop ss done
1216 Just s -> loop (msImports s ++ ss)
1217 (addToFM done key s) }
1219 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1221 msImports :: ModSummary -> [(FilePath, -- Importing module
1222 Module, -- Imported module
1223 IsBootInterface)] -- {-# SOURCE #-} import or not
1224 msImports s = [(f, m,True) | m <- ms_srcimps s]
1225 ++ [(f, m,False) | m <- ms_imps s]
1227 f = msHsFilePath s -- Keep the importing module for error reporting
1230 -----------------------------------------------------------------------------
1231 -- Summarising modules
1233 -- We have two types of summarisation:
1235 -- * Summarise a file. This is used for the root module(s) passed to
1236 -- cmLoadModules. The file is read, and used to determine the root
1237 -- module name. The module name may differ from the filename.
1239 -- * Summarise a module. We are given a module name, and must provide
1240 -- a summary. The finder is used to locate the file in which the module
1243 summariseFile :: DynFlags -> FilePath -> IO ModSummary
1244 -- Used for Haskell source only, I think
1245 -- We know the file name, and we know it exists,
1246 -- but we don't necessarily know the module name (might differ)
1247 summariseFile dflags file
1248 = do (dflags', hspp_fn) <- preprocess dflags file
1249 -- The dflags' contains the OPTIONS pragmas
1251 -- Read the file into a buffer. We're going to cache
1252 -- this buffer in the ModLocation (ml_hspp_buf) so that it
1253 -- doesn't have to be slurped again when hscMain parses the
1255 buf <- hGetStringBuffer hspp_fn
1256 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1258 -- Make a ModLocation for this file
1259 location <- mkHomeModLocation mod file
1261 -- Tell the Finder cache where it is, so that subsequent calls
1262 -- to findModule will find it, even if it's not on any search path
1263 addHomeModuleToFinder mod location
1265 src_timestamp <- getModificationTime file
1266 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1267 ms_location = location,
1268 ms_hspp_file = Just hspp_fn,
1269 ms_hspp_buf = Just buf,
1270 ms_srcimps = srcimps, ms_imps = the_imps,
1271 ms_hs_date = src_timestamp })
1273 -- Summarise a module, and pick up source and timestamp.
1274 summarise :: DynFlags
1275 -> NodeMap ModSummary -- Map of old summaries
1276 -> Maybe FilePath -- Importing module (for error messages)
1277 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1278 -> Module -- Imported module to be summarised
1279 -> [Module] -- Modules to exclude
1280 -> IO (Maybe ModSummary) -- Its new summary
1282 summarise dflags old_summary_map cur_mod is_boot wanted_mod excl_mods
1283 | wanted_mod `elem` excl_mods
1286 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1287 = do { -- Find its new timestamp; all the
1288 -- ModSummaries in the old map have valid ml_hs_files
1289 let location = ms_location old_summary
1290 src_fn = fromJust (ml_hs_file location)
1292 ; src_timestamp <- getModificationTime src_fn
1294 -- return the cached summary if the source didn't change
1295 ; if ms_hs_date old_summary == src_timestamp
1296 then return (Just old_summary)
1297 else new_summary location
1301 = do { found <- findModule dflags wanted_mod True {-explicit-}
1304 | not (isHomePackage pkg) -> return Nothing -- Drop external-pkg
1305 | isJust (ml_hs_file location) -> new_summary location -- Home package
1306 err -> noModError dflags cur_mod wanted_mod err -- Not found
1309 hsc_src = if is_boot then HsBootFile else HsSrcFile
1311 new_summary location
1312 = do { -- Adjust location to point to the hs-boot source file,
1313 -- hi file, object file, when is_boot says so
1314 let location' | is_boot = addBootSuffixLocn location
1315 | otherwise = location
1316 src_fn = fromJust (ml_hs_file location')
1318 -- Check that it exists
1319 -- It might have been deleted since the Finder last found it
1320 ; exists <- doesFileExist src_fn
1321 ; if exists then return () else noHsFileErr cur_mod src_fn
1323 -- Preprocess the source file and get its imports
1324 -- The dflags' contains the OPTIONS pragmas
1325 ; (dflags', hspp_fn) <- preprocess dflags src_fn
1326 ; buf <- hGetStringBuffer hspp_fn
1327 ; (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1329 ; when (mod_name /= wanted_mod) $
1330 throwDyn (ProgramError
1331 (showSDoc (text src_fn
1332 <> text ": file name does not match module name"
1333 <+> quotes (ppr mod_name))))
1335 -- Find its timestamp, and return the summary
1336 ; src_timestamp <- getModificationTime src_fn
1337 ; return (Just ( ModSummary { ms_mod = wanted_mod,
1338 ms_hsc_src = hsc_src,
1339 ms_location = location',
1340 ms_hspp_file = Just hspp_fn,
1341 ms_hspp_buf = Just buf,
1342 ms_srcimps = srcimps,
1344 ms_hs_date = src_timestamp }))
1348 -----------------------------------------------------------------------------
1350 -----------------------------------------------------------------------------
1352 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1353 -- ToDo: we don't have a proper line number for this error
1354 noModError dflags cur_mod wanted_mod err
1355 = throwDyn $ ProgramError $ showSDoc $
1356 vcat [cantFindError dflags wanted_mod err,
1357 nest 2 (parens (pp_where cur_mod))]
1359 noHsFileErr cur_mod path
1360 = throwDyn $ CmdLineError $ showSDoc $
1361 vcat [text "Can't find" <+> text path,
1362 nest 2 (parens (pp_where cur_mod))]
1364 pp_where Nothing = text "one of the roots of the dependency analysis"
1365 pp_where (Just p) = text "imported from" <+> text p
1368 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1369 quotes (ppr mod) <+>
1370 text "is a package module")))
1372 multiRootsErr mod files
1373 = throwDyn (ProgramError (showSDoc (
1374 text "module" <+> quotes (ppr mod) <+>
1375 text "is defined in multiple files:" <+>
1376 sep (map text files))))
1378 cyclicModuleErr :: [ModSummary] -> SDoc
1380 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1381 2 (vcat (map show_one ms))
1383 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1384 nest 2 $ ptext SLIT("imports:") <+>
1385 (pp_imps HsBootFile (ms_srcimps ms)
1386 $$ pp_imps HsSrcFile (ms_imps ms))]
1387 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1388 pp_imps src mods = fsep (map (show_mod src) mods)