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, -- :: GhcMode -> 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 DriverPhases ( HscSource(..), hscSourceString, isHaskellSrcFilename )
62 import Finder ( findModule, findLinkable, addHomeModuleToFinder,
63 flushFinderCache, mkHomeModLocation, FindResult(..), cantFindError )
64 import HscTypes ( ModSummary(..), HomeModInfo(..), ModIface(..),
65 msHsFilePath, HscEnv(..), isBootSummary,
66 InteractiveContext(..), emptyInteractiveContext,
67 HomePackageTable, emptyHomePackageTable,
68 IsBootInterface, Linkable(..), isObjectLinkable )
69 import Module ( Module, mkModule, delModuleEnv, delModuleEnvList,
70 mkModuleEnv, lookupModuleEnv, moduleEnvElts,
71 extendModuleEnv, filterModuleEnv, moduleUserString,
72 addBootSuffixLocn, ModLocation(..) )
73 import GetImports ( getImports )
74 import Digraph ( SCC(..), stronglyConnComp, flattenSCC, flattenSCCs )
75 import ErrUtils ( showPass )
76 import SysTools ( cleanTempFilesExcept )
77 import BasicTypes ( SuccessFlag(..), succeeded )
78 import StringBuffer ( hGetStringBuffer )
82 import DynFlags ( DynFlags(..), DynFlag(..), GhcMode(..), dopt )
83 import Maybes ( expectJust, orElse, mapCatMaybes )
87 import Finder ( findPackageModule )
88 import HscMain ( hscGetInfo, GetInfoResult, hscStmt, hscTcExpr, hscKcType )
89 import HscTypes ( TyThing(..), icPrintUnqual, showModMsg )
90 import TcRnDriver ( mkExportEnv, getModuleContents )
91 import IfaceSyn ( IfaceDecl )
92 import RdrName ( GlobalRdrEnv, plusGlobalRdrEnv )
96 import Type ( tidyType, dropForAlls )
97 import VarEnv ( emptyTidyEnv )
98 import Linker ( HValue, unload, extendLinkEnv )
99 import GHC.Exts ( unsafeCoerce# )
101 import Control.Exception as Exception ( Exception, try )
102 import DynFlags ( DynFlag(..), dopt_unset, dopt )
105 import EXCEPTION ( throwDyn )
108 import Directory ( getModificationTime, doesFileExist )
116 %************************************************************************
118 The module dependency graph
119 ModSummary, ModGraph, NodeKey, NodeMap
121 %************************************************************************
123 The nodes of the module graph are
124 EITHER a regular Haskell source module
125 OR a hi-boot source module
127 A ModuleGraph contains all the nodes from the home package (only).
128 There will be a node for each source module, plus a node for each hi-boot
132 type ModuleGraph = [ModSummary] -- The module graph,
133 -- NOT NECESSARILY IN TOPOLOGICAL ORDER
135 emptyMG :: ModuleGraph
139 ms_allimps :: ModSummary -> [Module]
140 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
143 type NodeKey = (Module, HscSource) -- The nodes of the graph are
144 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
146 msKey :: ModSummary -> NodeKey
147 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
149 emptyNodeMap :: NodeMap a
150 emptyNodeMap = emptyFM
152 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
153 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
155 nodeMapElts :: NodeMap a -> [a]
160 %************************************************************************
162 The compilation manager state
164 %************************************************************************
168 -- Persistent state for the entire system
171 cm_hsc :: HscEnv, -- Includes the home-package table
172 cm_mg :: ModuleGraph, -- The module graph
173 cm_ic :: InteractiveContext -- Command-line binding info
177 cmGetModuleGraph cmstate = cm_mg cmstate
178 cmGetBindings cmstate = nameEnvElts (ic_type_env (cm_ic cmstate))
179 cmGetPrintUnqual cmstate = icPrintUnqual (cm_ic cmstate)
180 cmHPT cmstate = hsc_HPT (cm_hsc cmstate)
183 cmInit :: DynFlags -> IO CmState
185 = do { hsc_env <- newHscEnv dflags
186 ; return (CmState { cm_hsc = hsc_env,
188 cm_ic = emptyInteractiveContext })}
190 discardCMInfo :: CmState -> CmState
191 -- Forget the compilation manager's state, including the home package table
192 -- but retain the persistent info in HscEnv
193 discardCMInfo cm_state
194 = cm_state { cm_mg = emptyMG, cm_ic = emptyInteractiveContext,
195 cm_hsc = (cm_hsc cm_state) { hsc_HPT = emptyHomePackageTable } }
197 -------------------------------------------------------------------
198 -- The unlinked image
200 -- The compilation manager keeps a list of compiled, but as-yet unlinked
201 -- binaries (byte code or object code). Even when it links bytecode
202 -- it keeps the unlinked version so it can re-link it later without
205 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
207 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
208 findModuleLinkable_maybe lis mod
209 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
212 many -> pprPanic "findModuleLinkable" (ppr mod)
214 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
215 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
219 %************************************************************************
223 %************************************************************************
227 -----------------------------------------------------------------------------
228 -- Setting the context doesn't throw away any bindings; the bindings
229 -- we've built up in the InteractiveContext simply move to the new
230 -- module. They always shadow anything in scope in the current context.
234 -> [String] -- take the top-level scopes of these modules
235 -> [String] -- and the just the exports from these
237 cmSetContext cmstate toplevs exports = do
238 let old_ic = cm_ic cmstate
239 hsc_env = cm_hsc cmstate
240 hpt = hsc_HPT hsc_env
242 let export_mods = map mkModule exports
243 mapM_ (checkModuleExists (hsc_dflags hsc_env) hpt) export_mods
244 export_env <- mkExportEnv hsc_env export_mods
245 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
247 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
248 return cmstate{ cm_ic = old_ic { ic_toplev_scope = toplevs,
249 ic_exports = exports,
250 ic_rn_gbl_env = all_env } }
252 checkModuleExists :: DynFlags -> HomePackageTable -> Module -> IO ()
253 checkModuleExists dflags hpt mod =
254 case lookupModuleEnv hpt mod of
255 Just mod_info -> return ()
256 _not_a_home_module -> do
257 res <- findPackageModule dflags mod True
259 Found _ _ -> return ()
260 err -> let msg = cantFindError dflags mod err in
261 throwDyn (CmdLineError (showSDoc msg))
263 mkTopLevEnv :: HomePackageTable -> String -> IO GlobalRdrEnv
265 = case lookupModuleEnv hpt (mkModule mod) of
266 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++ mod))
267 Just details -> case mi_globals (hm_iface details) of
268 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not interpreted " ++ mod))
269 Just env -> return env
271 cmGetContext :: CmState -> IO ([String],[String])
272 cmGetContext CmState{cm_ic=ic} =
273 return (ic_toplev_scope ic, ic_exports ic)
275 cmModuleIsInterpreted :: CmState -> String -> IO Bool
276 cmModuleIsInterpreted cmstate str
277 = case lookupModuleEnv (cmHPT cmstate) (mkModule str) of
278 Just details -> return (isJust (mi_globals (hm_iface details)))
279 _not_a_home_module -> return False
281 -----------------------------------------------------------------------------
283 cmSetDFlags :: CmState -> DynFlags -> CmState
284 cmSetDFlags cm_state dflags
285 = cm_state { cm_hsc = (cm_hsc cm_state) { hsc_dflags = dflags } }
287 cmGetDFlags :: CmState -> DynFlags
288 cmGetDFlags cm_state = hsc_dflags (cm_hsc cm_state)
290 -----------------------------------------------------------------------------
291 -- cmInfoThing: convert a String to a TyThing
293 -- A string may refer to more than one TyThing (eg. a constructor,
294 -- and type constructor), so we return a list of all the possible TyThings.
296 cmGetInfo :: CmState -> String -> IO [GetInfoResult]
297 cmGetInfo cmstate id = hscGetInfo (cm_hsc cmstate) (cm_ic cmstate) id
299 -- ---------------------------------------------------------------------------
300 -- cmBrowseModule: get all the TyThings defined in a module
302 cmBrowseModule :: CmState -> String -> Bool -> IO [IfaceDecl]
303 cmBrowseModule cmstate str exports_only
304 = do { mb_decls <- getModuleContents (cm_hsc cmstate) (cm_ic cmstate)
305 (mkModule str) exports_only
307 Nothing -> return [] -- An error of some kind
312 -----------------------------------------------------------------------------
313 cmShowModule :: CmState -> ModSummary -> String
314 cmShowModule cmstate mod_summary
315 = case lookupModuleEnv hpt (ms_mod mod_summary) of
316 Nothing -> panic "missing linkable"
317 Just mod_info -> showModMsg obj_linkable mod_summary
319 obj_linkable = isObjectLinkable (hm_linkable mod_info)
321 hpt = hsc_HPT (cm_hsc cmstate)
323 -----------------------------------------------------------------------------
324 -- cmRunStmt: Run a statement/expr.
327 = CmRunOk [Name] -- names bound by this evaluation
329 | CmRunException Exception -- statement raised an exception
331 cmRunStmt :: CmState -> String -> IO (CmState, CmRunResult)
332 cmRunStmt cmstate@CmState{ cm_hsc=hsc_env, cm_ic=icontext } expr
334 -- Turn off -fwarn-unused-bindings when running a statement, to hide
335 -- warnings about the implicit bindings we introduce.
336 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
337 hsc_env' = hsc_env{ hsc_dflags = dflags' }
339 maybe_stuff <- hscStmt hsc_env' icontext expr
342 Nothing -> return (cmstate, CmRunFailed)
343 Just (new_ic, names, hval) -> do
345 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
346 either_hvals <- sandboxIO thing_to_run
350 -- on error, keep the *old* interactive context,
351 -- so that 'it' is not bound to something
352 -- that doesn't exist.
353 return ( cmstate, CmRunException e )
356 -- Get the newly bound things, and bind them.
357 -- Don't need to delete any shadowed bindings;
358 -- the new ones override the old ones.
359 extendLinkEnv (zip names hvals)
361 return (cmstate{ cm_ic=new_ic },
365 -- We run the statement in a "sandbox" to protect the rest of the
366 -- system from anything the expression might do. For now, this
367 -- consists of just wrapping it in an exception handler, but see below
368 -- for another version.
370 sandboxIO :: IO a -> IO (Either Exception a)
371 sandboxIO thing = Exception.try thing
374 -- This version of sandboxIO runs the expression in a completely new
375 -- RTS main thread. It is disabled for now because ^C exceptions
376 -- won't be delivered to the new thread, instead they'll be delivered
377 -- to the (blocked) GHCi main thread.
379 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
381 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
383 st_thing <- newStablePtr (Exception.try thing)
384 alloca $ \ p_st_result -> do
385 stat <- rts_evalStableIO st_thing p_st_result
386 freeStablePtr st_thing
388 then do st_result <- peek p_st_result
389 result <- deRefStablePtr st_result
390 freeStablePtr st_result
391 return (Right result)
393 return (Left (fromIntegral stat))
395 foreign import "rts_evalStableIO" {- safe -}
396 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
397 -- more informative than the C type!
400 -----------------------------------------------------------------------------
401 -- cmTypeOfExpr: returns a string representing the type of an expression
403 cmTypeOfExpr :: CmState -> String -> IO (Maybe String)
404 cmTypeOfExpr cmstate expr
405 = do maybe_stuff <- hscTcExpr (cm_hsc cmstate) (cm_ic cmstate) expr
408 Nothing -> return Nothing
409 Just ty -> return (Just (showSDocForUser unqual doc))
411 doc = text expr <+> dcolon <+> ppr final_ty
412 unqual = icPrintUnqual (cm_ic cmstate)
413 tidy_ty = tidyType emptyTidyEnv ty
414 dflags = hsc_dflags (cm_hsc cmstate)
415 -- if -fglasgow-exts is on we show the foralls, otherwise
418 | dopt Opt_GlasgowExts dflags = tidy_ty
419 | otherwise = dropForAlls tidy_ty
421 -----------------------------------------------------------------------------
422 -- cmKindOfType: returns a string representing the kind of a type
424 cmKindOfType :: CmState -> String -> IO (Maybe String)
425 cmKindOfType cmstate str
426 = do maybe_stuff <- hscKcType (cm_hsc cmstate) (cm_ic cmstate) str
428 Nothing -> return Nothing
429 Just kind -> return (Just res_str)
431 res_str = showSDocForUser unqual (text str <+> dcolon <+> ppr kind)
432 unqual = icPrintUnqual (cm_ic cmstate)
434 -----------------------------------------------------------------------------
435 -- cmTypeOfName: returns a string representing the type of a name.
437 cmTypeOfName :: CmState -> Name -> IO (Maybe String)
438 cmTypeOfName CmState{ cm_ic=ic } name
440 hPutStrLn stderr ("cmTypeOfName: " ++ showSDoc (ppr name))
441 case lookupNameEnv (ic_type_env ic) name of
442 Nothing -> return Nothing
443 Just (AnId id) -> return (Just str)
445 unqual = icPrintUnqual ic
446 ty = tidyType emptyTidyEnv (idType id)
447 str = showSDocForUser unqual (ppr ty)
449 _ -> panic "cmTypeOfName"
451 -----------------------------------------------------------------------------
452 -- cmCompileExpr: compile an expression and deliver an HValue
454 cmCompileExpr :: CmState -> String -> IO (Maybe HValue)
455 cmCompileExpr cmstate expr
458 <- hscStmt (cm_hsc cmstate) (cm_ic cmstate)
459 ("let __cmCompileExpr = "++expr)
462 Nothing -> return Nothing
463 Just (new_ic, names, hval) -> do
466 hvals <- (unsafeCoerce# hval) :: IO [HValue]
468 case (names,hvals) of
469 ([n],[hv]) -> return (Just hv)
470 _ -> panic "cmCompileExpr"
476 %************************************************************************
478 Loading and unloading
480 %************************************************************************
483 -----------------------------------------------------------------------------
484 -- Unload the compilation manager's state: everything it knows about the
485 -- current collection of modules in the Home package.
487 cmUnload :: CmState -> IO CmState
488 cmUnload state@CmState{ cm_hsc = hsc_env }
489 = do -- Throw away the old home dir cache
492 -- Unload everything the linker knows about
495 -- Start with a fresh CmState, but keep the PersistentCompilerState
496 return (discardCMInfo state)
498 cm_unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
499 = case ghcMode (hsc_dflags hsc_env) of
500 BatchCompile -> return ()
502 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
504 Interactive -> panic "cm_unload: no interpreter"
506 other -> panic "cm_unload: strange mode"
509 -----------------------------------------------------------------------------
510 -- Trace dependency graph
512 -- This is a seperate pass so that the caller can back off and keep
513 -- the current state if the downsweep fails. Typically the caller
514 -- might go cmDepAnal
517 -- He wants to do the dependency analysis before the unload, so that
518 -- if the former fails he can use the later
520 cmDepAnal :: CmState -> [FilePath] -> IO ModuleGraph
521 cmDepAnal cmstate rootnames
522 = do showPass dflags "Chasing dependencies"
523 when (verbosity dflags >= 1 && gmode == BatchCompile) $
524 hPutStrLn stderr (showSDoc (hcat [
525 text "Chasing modules from: ",
526 hcat (punctuate comma (map text rootnames))]))
527 cmDownsweep dflags rootnames (cm_mg cmstate) []
529 hsc_env = cm_hsc cmstate
530 dflags = hsc_dflags hsc_env
531 gmode = ghcMode (hsc_dflags hsc_env)
533 -----------------------------------------------------------------------------
534 -- The real business of the compilation manager: given a system state and
535 -- a module name, try and bring the module up to date, probably changing
536 -- the system state at the same time.
538 cmLoadModules :: CmState -- The HPT may not be as up to date
539 -> ModuleGraph -- Bang up to date; but may contain hi-boot no
540 -> IO (CmState, -- new state
541 SuccessFlag, -- was successful
542 [String]) -- list of modules loaded
544 cmLoadModules cmstate1 mg2unsorted
545 = do -- version 1's are the original, before downsweep
546 let hsc_env = cm_hsc cmstate1
547 let hpt1 = hsc_HPT hsc_env
548 let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
549 let dflags = hsc_dflags hsc_env -- this never changes
550 let verb = verbosity dflags
552 -- The "bad" boot modules are the ones for which we have
553 -- B.hs-boot in the module graph, but no B.hs
554 -- The downsweep should have ensured this does not happen
556 let all_home_mods = [ms_mod s | s <- mg2unsorted, not (isBootSummary s)]
557 bad_boot_mods = [s | s <- mg2unsorted, isBootSummary s,
558 not (ms_mod s `elem` all_home_mods)]
559 ASSERT( null bad_boot_mods ) return ()
561 -- Do the downsweep to reestablish the module graph
562 -- mg2 should be cycle free; but it includes hi-boot ModSummary nodes
563 let mg2 :: [SCC ModSummary]
564 mg2 = cmTopSort False mg2unsorted
566 -- mg2_with_srcimps drops the hi-boot nodes, returning a
567 -- graph with cycles. Among other things, it is used for
568 -- backing out partially complete cycles following a failed
569 -- upsweep, and for removing from hpt all the modules
570 -- not in strict downwards closure, during calls to compile.
571 let mg2_with_srcimps :: [SCC ModSummary]
572 mg2_with_srcimps = cmTopSort True mg2unsorted
574 -- Sort out which linkables we wish to keep in the unlinked image.
575 -- See getValidLinkables below for details.
576 (valid_old_linkables, new_linkables)
577 <- getValidLinkables ghci_mode (hptLinkables hpt1)
578 all_home_mods mg2_with_srcimps
580 -- putStrLn (showSDoc (vcat [ppr valid_old_linkables, ppr new_linkables]))
582 -- The new_linkables are .o files we found on the disk, presumably
583 -- as a result of a GHC run "on the side". So we'd better forget
584 -- everything we know abouut those modules!
585 let old_hpt = delModuleEnvList hpt1 (map linkableModule new_linkables)
587 -- When (verb >= 2) $
588 -- putStrLn (showSDoc (text "Valid linkables:"
589 -- <+> ppr valid_linkables))
591 -- Figure out a stable set of modules which can be retained
592 -- the top level envs, to avoid upsweeping them. Goes to a
593 -- bit of trouble to avoid upsweeping module cycles.
595 -- Construct a set S of stable modules like this:
596 -- Travel upwards, over the sccified graph. For each scc
597 -- of modules ms, add ms to S only if:
598 -- 1. All home imports of ms are either in ms or S
599 -- 2. A valid old linkable exists for each module in ms
601 -- mg2_with_srcimps has no hi-boot nodes,
602 -- and hence neither does stable_mods
603 stable_summaries <- preUpsweep valid_old_linkables
604 all_home_mods [] mg2_with_srcimps
605 let stable_mods = map ms_mod stable_summaries
606 stable_linkables = filter (\m -> linkableModule m `elem` stable_mods)
609 stable_hpt = filterModuleEnv is_stable_hm hpt1
610 is_stable_hm hm_info = mi_module (hm_iface hm_info) `elem` stable_mods
613 = filter (\scc -> any (`notElem` stable_mods)
614 (map ms_mod (flattenSCC scc)))
618 hPutStrLn stderr (showSDoc (text "Stable modules:"
619 <+> sep (map (text.moduleUserString) stable_mods)))
621 -- Unload any modules which are going to be re-linked this time around.
622 cm_unload hsc_env stable_linkables
624 -- We can now glom together our linkable sets
625 let valid_linkables = valid_old_linkables ++ new_linkables
627 -- We could at this point detect cycles which aren't broken by
628 -- a source-import, and complain immediately, but it seems better
629 -- to let upsweep_mods do this, so at least some useful work gets
630 -- done before the upsweep is abandoned.
631 --hPutStrLn stderr "after tsort:\n"
632 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
634 -- Because we don't take into account source imports when doing
635 -- the topological sort, there shouldn't be any cycles in mg2.
636 -- If there is, we complain and give up -- the user needs to
637 -- break the cycle using a boot file.
639 -- Now do the upsweep, calling compile for each module in
640 -- turn. Final result is version 3 of everything.
642 -- clean up between compilations
643 let cleanup = cleanTempFilesExcept dflags
644 (ppFilesFromSummaries (flattenSCCs mg2))
646 (upsweep_ok, hsc_env3, modsUpswept)
647 <- upsweep_mods (hsc_env { hsc_HPT = stable_hpt })
648 (old_hpt, valid_linkables)
649 cleanup upsweep_these
651 -- At this point, modsUpswept and newLis should have the same
652 -- length, so there is one new (or old) linkable for each
653 -- mod which was processed (passed to compile).
655 -- Make modsDone be the summaries for each home module now
656 -- available; this should equal the domain of hpt3.
657 -- (NOT STRICTLY TRUE if an interactive session was started
658 -- with some object on disk ???)
659 -- Get in in a roughly top .. bottom order (hence reverse).
661 let modsDone = reverse modsUpswept ++ stable_summaries
663 -- Try and do linking in some form, depending on whether the
664 -- upsweep was completely or only partially successful.
666 if succeeded upsweep_ok
669 -- Easy; just relink it all.
670 do when (verb >= 2) $
671 hPutStrLn stderr "Upsweep completely successful."
673 -- Clean up after ourselves
674 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
676 -- Issue a warning for the confusing case where the user
677 -- said '-o foo' but we're not going to do any linking.
678 -- We attempt linking if either (a) one of the modules is
679 -- called Main, or (b) the user said -no-hs-main, indicating
680 -- that main() is going to come from somewhere else.
682 let ofile = outputFile dflags
683 let no_hs_main = dopt Opt_NoHsMain dflags
684 let mb_main_mod = mainModIs dflags
686 main_mod = mb_main_mod `orElse` "Main"
688 = any ((==main_mod).moduleUserString.ms_mod)
690 do_linking = a_root_is_Main || no_hs_main
692 when (ghci_mode == BatchCompile && isJust ofile && not do_linking
694 hPutStrLn stderr ("Warning: output was redirected with -o, " ++
695 "but no output will be generated\n" ++
696 "because there is no " ++ main_mod ++ " module.")
698 -- link everything together
699 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env3)
701 let cmstate3 = cmstate1 { cm_mg = modsDone, cm_hsc = hsc_env3 }
702 cmLoadFinish Succeeded linkresult cmstate3
705 -- Tricky. We need to back out the effects of compiling any
706 -- half-done cycles, both so as to clean up the top level envs
707 -- and to avoid telling the interactive linker to link them.
708 do when (verb >= 2) $
709 hPutStrLn stderr "Upsweep partially successful."
712 = map ms_mod modsDone
713 let mods_to_zap_names
714 = findPartiallyCompletedCycles modsDone_names
717 = filter ((`notElem` mods_to_zap_names).ms_mod)
720 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
723 -- Clean up after ourselves
724 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
726 -- Link everything together
727 linkresult <- link ghci_mode dflags False hpt4
729 let cmstate3 = cmstate1 { cm_mg = mods_to_keep,
730 cm_hsc = hsc_env3 { hsc_HPT = hpt4 } }
731 cmLoadFinish Failed linkresult cmstate3
733 -- Finish up after a cmLoad.
735 -- If the link failed, unload everything and return.
736 cmLoadFinish ok Failed cmstate
737 = do cm_unload (cm_hsc cmstate) []
738 return (discardCMInfo cmstate, Failed, [])
740 -- Empty the interactive context and set the module context to the topmost
741 -- newly loaded module, or the Prelude if none were loaded.
742 cmLoadFinish ok Succeeded cmstate
743 = do let new_cmstate = cmstate { cm_ic = emptyInteractiveContext }
744 mods_loaded = map (moduleUserString.ms_mod)
747 return (new_cmstate, ok, mods_loaded)
749 -- used to fish out the preprocess output files for the purposes of
750 -- cleaning up. The preprocessed file *might* be the same as the
751 -- source file, but that doesn't do any harm.
752 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
754 -----------------------------------------------------------------------------
757 -- For each module (or SCC of modules), we take:
759 -- - an on-disk linkable, if this is the first time around and one
762 -- - the old linkable, otherwise (and if one is available).
764 -- and we throw away the linkable if it is older than the source file.
765 -- In interactive mode, we also ignore the on-disk linkables unless
766 -- all of the dependents of this SCC also have on-disk linkables (we
767 -- can't have dynamically loaded objects that depend on interpreted
770 -- If a module has a valid linkable, then it may be STABLE (see below),
771 -- and it is classified as SOURCE UNCHANGED for the purposes of calling
774 -- ToDo: this pass could be merged with the preUpsweep.
778 -> [Linkable] -- old linkables
779 -> [Module] -- all home modules
780 -> [SCC ModSummary] -- all modules in the program, dependency order
781 -> IO ( [Linkable], -- still-valid linkables
782 [Linkable] -- new linkables we just found on the disk
783 -- presumably generated by separate run of ghc
786 getValidLinkables mode old_linkables all_home_mods module_graph
787 = do { -- Process the SCCs in bottom-to-top order
788 -- (foldM works left-to-right)
789 ls <- foldM (getValidLinkablesSCC mode old_linkables all_home_mods)
791 ; return (partition_it ls [] []) }
793 partition_it [] valid new = (valid,new)
794 partition_it ((l,b):ls) valid new
795 | b = partition_it ls valid (l:new)
796 | otherwise = partition_it ls (l:valid) new
801 -> [Linkable] -- old linkables
802 -> [Module] -- all home modules
805 -> IO [(Linkable,Bool)]
807 getValidLinkablesSCC mode old_linkables all_home_mods new_linkables scc0
809 scc = flattenSCC scc0
810 scc_names = map ms_mod scc
811 home_module m = m `elem` all_home_mods && m `notElem` scc_names
812 scc_allhomeimps = nub (filter home_module (concatMap ms_imps scc))
813 -- NB. ms_imps, not ms_allimps above. We don't want to
814 -- force a module's SOURCE imports to be already compiled for
815 -- its object linkable to be valid.
817 -- The new_linkables is only the *valid* linkables below here
818 has_object m = case findModuleLinkable_maybe (map fst new_linkables) m of
820 Just l -> isObjectLinkable l
822 objects_allowed = mode == BatchCompile || all has_object scc_allhomeimps
826 <- foldM (getValidLinkable old_linkables objects_allowed) [] scc
828 -- since an scc can contain only all objects or no objects at all,
829 -- we have to check whether we got all objects or not, and re-do
830 -- the linkable check if not.
833 && not (all isObjectLinkable (map fst new_linkables'))
834 then foldM (getValidLinkable old_linkables False) [] scc
835 else return new_linkables'
837 return (new_linkables ++ new_linkables')
840 getValidLinkable :: [Linkable] -> Bool -> [(Linkable,Bool)] -> ModSummary
841 -> IO [(Linkable,Bool)]
842 -- True <=> linkable is new; i.e. freshly discovered on the disk
843 -- presumably generated 'on the side'
844 -- by a separate GHC run
845 getValidLinkable old_linkables objects_allowed new_linkables summary
846 -- 'objects_allowed' says whether we permit this module to
847 -- have a .o-file linkable. We only permit it if all the
848 -- modules it depends on also have .o files; a .o file can't
849 -- link to a bytecode module
850 = do let mod_name = ms_mod summary
853 <- if (not objects_allowed)
856 else findLinkable mod_name (ms_location summary)
858 let old_linkable = findModuleLinkable_maybe old_linkables mod_name
861 case (old_linkable, maybe_disk_linkable) of
862 (Nothing, Nothing) -> []
864 -- new object linkable just appeared
865 (Nothing, Just l) -> up_to_date l True
868 | isObjectLinkable l -> []
869 -- object linkable disappeared! In case we need to
870 -- relink the module, disregard the old linkable and
871 -- just interpret the module from now on.
872 | otherwise -> up_to_date l False
873 -- old byte code linkable
876 | not (isObjectLinkable l) -> up_to_date l False
877 -- if the previous linkable was interpreted, then we
878 -- ignore a newly compiled version, because the version
879 -- numbers in the interface file will be out-of-sync with
880 -- our internal ones.
881 | linkableTime l' > linkableTime l -> up_to_date l' True
882 | linkableTime l' == linkableTime l -> up_to_date l False
884 -- on-disk linkable has been replaced by an older one!
885 -- again, disregard the previous one.
888 | linkableTime l < ms_hs_date summary = []
889 | otherwise = [(l,b)]
890 -- why '<' rather than '<=' above? If the filesystem stores
891 -- times to the nearset second, we may occasionally find that
892 -- the object & source have the same modification time,
893 -- especially if the source was automatically generated
894 -- and compiled. Using >= is slightly unsafe, but it matches
897 return (new_linkables' ++ new_linkables)
900 hptLinkables :: HomePackageTable -> [Linkable]
901 -- Get all the linkables from the home package table, one for each module
902 -- Once the HPT is up to date, these are the ones we should link
903 hptLinkables hpt = map hm_linkable (moduleEnvElts hpt)
906 -----------------------------------------------------------------------------
907 -- Do a pre-upsweep without use of "compile", to establish a
908 -- (downward-closed) set of stable modules for which we won't call compile.
911 -- * has a valid linkable (see getValidLinkables above)
912 -- * depends only on stable modules
913 -- * has an interface in the HPT (interactive mode only)
915 preUpsweep :: [Linkable] -- new valid linkables
916 -> [Module] -- names of all mods encountered in downsweep
917 -> [ModSummary] -- accumulating stable modules
918 -> [SCC ModSummary] -- scc-ified mod graph, including src imps
919 -> IO [ModSummary] -- stable modules
921 preUpsweep valid_lis all_home_mods stable [] = return stable
922 preUpsweep valid_lis all_home_mods stable (scc0:sccs)
923 = do let scc = flattenSCC scc0
924 scc_allhomeimps :: [Module]
926 = nub (filter (`elem` all_home_mods) (concatMap ms_allimps scc))
927 all_imports_in_scc_or_stable
928 = all in_stable_or_scc scc_allhomeimps
929 scc_mods = map ms_mod scc
930 stable_names = scc_mods ++ map ms_mod stable
931 in_stable_or_scc m = m `elem` stable_names
933 -- now we check for valid linkables: each module in the SCC must
934 -- have a valid linkable (see getValidLinkables above).
935 has_valid_linkable scc_mod
936 = isJust (findModuleLinkable_maybe valid_lis scc_mod)
938 scc_is_stable = all_imports_in_scc_or_stable
939 && all has_valid_linkable scc_mods
942 then preUpsweep valid_lis all_home_mods (scc ++ stable) sccs
943 else preUpsweep valid_lis all_home_mods stable sccs
946 -- Return (names of) all those in modsDone who are part of a cycle
947 -- as defined by theGraph.
948 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
949 findPartiallyCompletedCycles modsDone theGraph
953 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
954 chew ((CyclicSCC vs):rest)
955 = let names_in_this_cycle = nub (map ms_mod vs)
957 = nub ([done | done <- modsDone,
958 done `elem` names_in_this_cycle])
959 chewed_rest = chew rest
961 if notNull mods_in_this_cycle
962 && length mods_in_this_cycle < length names_in_this_cycle
963 then mods_in_this_cycle ++ chewed_rest
967 -- Compile multiple modules, stopping as soon as an error appears.
968 -- There better had not be any cyclic groups here -- we check for them.
969 upsweep_mods :: HscEnv -- Includes initially-empty HPT
970 -> (HomePackageTable, [Linkable]) -- HPT and valid linkables from last time round
971 -> IO () -- How to clean up unwanted tmp files
972 -> [SCC ModSummary] -- Mods to do (the worklist)
974 HscEnv, -- With an updated HPT
975 [ModSummary]) -- Mods which succeeded
977 upsweep_mods hsc_env oldUI cleanup
979 = return (Succeeded, hsc_env, [])
981 upsweep_mods hsc_env oldUI cleanup
983 = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
984 return (Failed, hsc_env, [])
986 upsweep_mods hsc_env oldUI@(old_hpt, old_linkables) cleanup
987 (AcyclicSCC mod:mods)
988 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
989 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
990 -- (moduleEnvElts (hsc_HPT hsc_env)))
992 mb_mod_info <- upsweep_mod hsc_env oldUI mod
994 cleanup -- Remove unwanted tmp files between compilations
997 Nothing -> return (Failed, hsc_env, [])
999 { let this_mod = ms_mod mod
1001 -- Add new info to hsc_env
1002 hpt1 = extendModuleEnv (hsc_HPT hsc_env) this_mod mod_info
1003 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1005 -- Space-saving: delete the old HPT entry and linkable for mod
1006 -- BUT if mod is a hs-boot node, don't delete it
1007 -- For the linkable this is dead right: the linkable relates only
1008 -- to the main Haskell source file.
1009 -- For the interface, the HPT entry is probaby for the main Haskell
1010 -- source file. Deleting it would force
1011 oldUI1 | isBootSummary mod = oldUI
1013 = (delModuleEnv old_hpt this_mod,
1014 delModuleLinkable old_linkables this_mod)
1016 ; (restOK, hsc_env2, modOKs) <- upsweep_mods hsc_env1 oldUI1 cleanup mods
1017 ; return (restOK, hsc_env2, mod:modOKs) }
1020 -- Compile a single module. Always produce a Linkable for it if
1021 -- successful. If no compilation happened, return the old Linkable.
1022 upsweep_mod :: HscEnv
1023 -> (HomePackageTable, UnlinkedImage)
1025 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1027 upsweep_mod hsc_env (old_hpt, old_linkables) summary
1029 let this_mod = ms_mod summary
1031 -- The old interface is ok if it's in the old HPT
1032 -- a) we're compiling a source file, and the old HPT entry is for a source file
1033 -- b) we're compiling a hs-boot file
1034 -- Case (b) allows an hs-boot file to get the interface of its real source file
1035 -- on the second iteration of the compilation manager, but that does no harm.
1036 -- Otherwise the hs-boot file will always be recompiled
1038 = case lookupModuleEnv old_hpt this_mod of
1040 Just hm_info | isBootSummary summary -> Just iface
1041 | not (mi_boot iface) -> Just iface
1042 | otherwise -> Nothing
1044 iface = hm_iface hm_info
1046 maybe_old_linkable = findModuleLinkable_maybe old_linkables this_mod
1047 source_unchanged = isJust maybe_old_linkable
1049 old_linkable = expectJust "upsweep_mod:old_linkable" maybe_old_linkable
1052 | Just l <- maybe_old_linkable, isObjectLinkable l = True
1055 compresult <- compile hsc_env summary source_unchanged have_object mb_old_iface
1059 -- Compilation "succeeded", and may or may not have returned a new
1060 -- linkable (depending on whether compilation was actually performed
1062 CompOK new_details new_iface maybe_new_linkable
1064 new_linkable = maybe_new_linkable `orElse` old_linkable
1065 new_info = HomeModInfo { hm_iface = new_iface,
1066 hm_details = new_details,
1067 hm_linkable = new_linkable }
1068 return (Just new_info)
1070 -- Compilation failed. Compile may still have updated the PCS, tho.
1071 CompErrs -> return Nothing
1073 -- Filter modules in the HPT
1074 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1075 retainInTopLevelEnvs keep_these hpt
1076 = mkModuleEnv [ (mod, fromJust mb_mod_info)
1078 , let mb_mod_info = lookupModuleEnv hpt mod
1079 , isJust mb_mod_info ]
1081 -----------------------------------------------------------------------------
1082 cmTopSort :: Bool -- Drop hi-boot nodes? (see below)
1085 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1087 -- Drop hi-boot nodes (first boolean arg)?
1089 -- False: treat the hi-boot summaries as nodes of the graph,
1090 -- so the graph must be acyclic
1092 -- True: eliminate the hi-boot nodes, and instead pretend
1093 -- the a source-import of Foo is an import of Foo
1094 -- The resulting graph has no hi-boot nodes, but can by cyclic
1096 cmTopSort drop_hs_boot_nodes summaries
1097 = stronglyConnComp nodes
1099 -- Drop hs-boot nodes by using HsSrcFile as the key
1100 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1101 | otherwise = HsBootFile
1103 -- We use integers as the keys for the SCC algorithm
1104 nodes :: [(ModSummary, Int, [Int])]
1105 nodes = [(s, fromJust (lookup_key (ms_hsc_src s) (ms_mod s)),
1106 out_edge_keys hs_boot_key (ms_srcimps s) ++
1107 out_edge_keys HsSrcFile (ms_imps s) )
1109 , not (isBootSummary s && drop_hs_boot_nodes) ]
1110 -- Drop the hi-boot ones if told to do so
1112 key_map :: NodeMap Int
1113 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1116 lookup_key :: HscSource -> Module -> Maybe Int
1117 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1119 out_edge_keys :: HscSource -> [Module] -> [Int]
1120 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1121 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1122 -- the IsBootInterface parameter True; else False
1125 -----------------------------------------------------------------------------
1126 -- Downsweep (dependency analysis)
1128 -- Chase downwards from the specified root set, returning summaries
1129 -- for all home modules encountered. Only follow source-import
1132 -- We pass in the previous collection of summaries, which is used as a
1133 -- cache to avoid recalculating a module summary if the source is
1136 -- The returned list of [ModSummary] nodes has one node for each home-package
1137 -- module, plus one for any hs-boot files. The imports of these nodes
1138 -- are all there, including the imports of non-home-package modules.
1140 cmDownsweep :: DynFlags
1141 -> [FilePath] -- Roots
1142 -> [ModSummary] -- Old summaries
1143 -> [Module] -- Ignore dependencies on these; treat them as
1144 -- if they were package modules
1146 cmDownsweep dflags roots old_summaries excl_mods
1147 = do rootSummaries <- mapM getRootSummary roots
1148 checkDuplicates rootSummaries
1149 loop (concatMap msDeps rootSummaries)
1150 (mkNodeMap rootSummaries)
1152 old_summary_map :: NodeMap ModSummary
1153 old_summary_map = mkNodeMap old_summaries
1155 getRootSummary :: FilePath -> IO ModSummary
1157 | isHaskellSrcFilename file
1158 = do exists <- doesFileExist file
1159 if exists then summariseFile dflags file else do
1160 throwDyn (CmdLineError ("can't find file `" ++ file ++ "'"))
1162 = do exists <- doesFileExist hs_file
1163 if exists then summariseFile dflags hs_file else do
1164 exists <- doesFileExist lhs_file
1165 if exists then summariseFile dflags lhs_file else do
1166 let mod_name = mkModule file
1167 maybe_summary <- summarise dflags emptyNodeMap Nothing False
1169 case maybe_summary of
1170 Nothing -> packageModErr mod_name
1173 hs_file = file ++ ".hs"
1174 lhs_file = file ++ ".lhs"
1176 -- In a root module, the filename is allowed to diverge from the module
1177 -- name, so we have to check that there aren't multiple root files
1178 -- defining the same module (otherwise the duplicates will be silently
1179 -- ignored, leading to confusing behaviour).
1180 checkDuplicates :: [ModSummary] -> IO ()
1181 checkDuplicates summaries = mapM_ check summaries
1186 many -> multiRootsErr modl many
1187 where modl = ms_mod summ
1189 [ fromJust (ml_hs_file (ms_location summ'))
1190 | summ' <- summaries, ms_mod summ' == modl ]
1192 loop :: [(FilePath,Module,IsBootInterface)] -- Work list: process these modules
1193 -> NodeMap ModSummary -- Visited set
1194 -> IO [ModSummary] -- The result includes the worklist, except
1195 -- for those mentioned in the visited set
1196 loop [] done = return (nodeMapElts done)
1197 loop ((cur_path, wanted_mod, is_boot) : ss) done
1198 | key `elemFM` done = loop ss done
1199 | otherwise = do { mb_s <- summarise dflags old_summary_map
1200 (Just cur_path) is_boot
1201 wanted_mod excl_mods
1203 Nothing -> loop ss done
1204 Just s -> loop (msDeps s ++ ss)
1205 (addToFM done key s) }
1207 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1209 msDeps :: ModSummary -> [(FilePath, -- Importing module
1210 Module, -- Imported module
1211 IsBootInterface)] -- {-# SOURCE #-} import or not
1212 -- (msDeps s) returns the dependencies of the ModSummary s.
1213 -- A wrinkle is that for a {-# SOURCE #-} import we return
1214 -- *both* the hs-boot file
1215 -- *and* the source file
1216 -- as "dependencies". That ensures that the list of all relevant
1217 -- modules always contains B.hs if it contains B.hs-boot.
1218 -- Remember, this pass isn't doing the topological sort. It's
1219 -- just gathering the list of all relevant ModSummaries
1220 msDeps s = concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s]
1221 ++ [(f,m,False) | m <- ms_imps s]
1223 f = msHsFilePath s -- Keep the importing module for error reporting
1226 -----------------------------------------------------------------------------
1227 -- Summarising modules
1229 -- We have two types of summarisation:
1231 -- * Summarise a file. This is used for the root module(s) passed to
1232 -- cmLoadModules. The file is read, and used to determine the root
1233 -- module name. The module name may differ from the filename.
1235 -- * Summarise a module. We are given a module name, and must provide
1236 -- a summary. The finder is used to locate the file in which the module
1239 summariseFile :: DynFlags -> FilePath -> IO ModSummary
1240 -- Used for Haskell source only, I think
1241 -- We know the file name, and we know it exists,
1242 -- but we don't necessarily know the module name (might differ)
1243 summariseFile dflags file
1244 = do (dflags', hspp_fn) <- preprocess dflags file
1245 -- The dflags' contains the OPTIONS pragmas
1247 -- Read the file into a buffer. We're going to cache
1248 -- this buffer in the ModLocation (ml_hspp_buf) so that it
1249 -- doesn't have to be slurped again when hscMain parses the
1251 buf <- hGetStringBuffer hspp_fn
1252 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1254 -- Make a ModLocation for this file
1255 location <- mkHomeModLocation dflags mod file
1257 -- Tell the Finder cache where it is, so that subsequent calls
1258 -- to findModule will find it, even if it's not on any search path
1259 addHomeModuleToFinder mod location
1261 src_timestamp <- getModificationTime file
1262 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1263 ms_location = location,
1264 ms_hspp_file = Just hspp_fn,
1265 ms_hspp_buf = Just buf,
1266 ms_srcimps = srcimps, ms_imps = the_imps,
1267 ms_hs_date = src_timestamp })
1269 -- Summarise a module, and pick up source and timestamp.
1270 summarise :: DynFlags
1271 -> NodeMap ModSummary -- Map of old summaries
1272 -> Maybe FilePath -- Importing module (for error messages)
1273 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1274 -> Module -- Imported module to be summarised
1275 -> [Module] -- Modules to exclude
1276 -> IO (Maybe ModSummary) -- Its new summary
1278 summarise dflags old_summary_map cur_mod is_boot wanted_mod excl_mods
1279 | wanted_mod `elem` excl_mods
1282 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1283 = do { -- Find its new timestamp; all the
1284 -- ModSummaries in the old map have valid ml_hs_files
1285 let location = ms_location old_summary
1286 src_fn = fromJust (ml_hs_file location)
1288 ; src_timestamp <- getModificationTime src_fn
1290 -- return the cached summary if the source didn't change
1291 ; if ms_hs_date old_summary == src_timestamp
1292 then return (Just old_summary)
1293 else new_summary location
1297 = do { found <- findModule dflags wanted_mod True {-explicit-}
1300 | not (isHomePackage pkg) -> return Nothing -- Drop external-pkg
1301 | isJust (ml_hs_file location) -> new_summary location -- Home package
1302 err -> noModError dflags cur_mod wanted_mod err -- Not found
1305 hsc_src = if is_boot then HsBootFile else HsSrcFile
1307 new_summary location
1308 = do { -- Adjust location to point to the hs-boot source file,
1309 -- hi file, object file, when is_boot says so
1310 let location' | is_boot = addBootSuffixLocn location
1311 | otherwise = location
1312 src_fn = fromJust (ml_hs_file location')
1314 -- Check that it exists
1315 -- It might have been deleted since the Finder last found it
1316 ; exists <- doesFileExist src_fn
1317 ; if exists then return () else noHsFileErr cur_mod src_fn
1319 -- Preprocess the source file and get its imports
1320 -- The dflags' contains the OPTIONS pragmas
1321 ; (dflags', hspp_fn) <- preprocess dflags src_fn
1322 ; buf <- hGetStringBuffer hspp_fn
1323 ; (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1325 ; when (mod_name /= wanted_mod) $
1326 throwDyn (ProgramError
1327 (showSDoc (text src_fn
1328 <> text ": file name does not match module name"
1329 <+> quotes (ppr mod_name))))
1331 -- Find its timestamp, and return the summary
1332 ; src_timestamp <- getModificationTime src_fn
1333 ; return (Just ( ModSummary { ms_mod = wanted_mod,
1334 ms_hsc_src = hsc_src,
1335 ms_location = location',
1336 ms_hspp_file = Just hspp_fn,
1337 ms_hspp_buf = Just buf,
1338 ms_srcimps = srcimps,
1340 ms_hs_date = src_timestamp }))
1344 -----------------------------------------------------------------------------
1346 -----------------------------------------------------------------------------
1348 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1349 -- ToDo: we don't have a proper line number for this error
1350 noModError dflags cur_mod wanted_mod err
1351 = throwDyn $ ProgramError $ showSDoc $
1352 vcat [cantFindError dflags wanted_mod err,
1353 nest 2 (parens (pp_where cur_mod))]
1355 noHsFileErr cur_mod path
1356 = throwDyn $ CmdLineError $ showSDoc $
1357 vcat [text "Can't find" <+> text path,
1358 nest 2 (parens (pp_where cur_mod))]
1360 pp_where Nothing = text "one of the roots of the dependency analysis"
1361 pp_where (Just p) = text "imported from" <+> text p
1364 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1365 quotes (ppr mod) <+>
1366 text "is a package module")))
1368 multiRootsErr mod files
1369 = throwDyn (ProgramError (showSDoc (
1370 text "module" <+> quotes (ppr mod) <+>
1371 text "is defined in multiple files:" <+>
1372 sep (map text files))))
1374 cyclicModuleErr :: [ModSummary] -> SDoc
1376 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1377 2 (vcat (map show_one ms))
1379 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1380 nest 2 $ ptext SLIT("imports:") <+>
1381 (pp_imps HsBootFile (ms_srcimps ms)
1382 $$ pp_imps HsSrcFile (ms_imps ms))]
1383 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1384 pp_imps src mods = fsep (map (show_mod src) mods)