1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
4 -----------------------------------------------------------------------------
6 -- Makefile Dependency Generation
8 -- (c) The University of Glasgow 2005
10 -----------------------------------------------------------------------------
12 module DriverMkDepend (
16 #include "HsVersions.h"
19 import GHC ( ModSummary(..), GhcMonad )
23 import HscTypes ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath, getSession )
24 import SysTools ( newTempName )
25 import qualified SysTools
27 import Digraph ( SCC(..) )
28 import Finder ( findImportedModule, FindResult(..) )
36 import ErrUtils ( debugTraceMsg, putMsg )
37 import MonadUtils ( liftIO )
39 import System.Directory
40 import System.FilePath
42 import System.IO.Error ( isEOFError )
43 import Control.Monad ( when )
44 import Data.Maybe ( isJust )
46 -----------------------------------------------------------------
50 -----------------------------------------------------------------
52 doMkDependHS :: GhcMonad m => [FilePath] -> m ()
53 doMkDependHS srcs = do
55 dflags <- GHC.getSessionDynFlags
56 files <- liftIO $ beginMkDependHS dflags
58 -- Do the downsweep to find all the modules
59 targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
60 GHC.setTargets targets
61 let excl_mods = depExcludeMods dflags
62 mod_summaries <- GHC.depanal excl_mods True {- Allow dup roots -}
64 -- Sort into dependency order
65 -- There should be no cycles
66 let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
68 -- Print out the dependencies if wanted
69 liftIO $ debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
71 -- Prcess them one by one, dumping results into makefile
72 -- and complaining about cycles
74 mapM (liftIO . processDeps dflags hsc_env excl_mods (mkd_tmp_hdl files)) sorted
76 -- If -ddump-mod-cycles, show cycles in the module graph
77 liftIO $ dumpModCycles dflags mod_summaries
80 liftIO $ endMkDependHS dflags files
82 -- Unconditional exiting is a bad idea. If an error occurs we'll get an
83 --exception; if that is not caught it's fine, but at least we have a
84 --chance to find out exactly what went wrong. Uncomment the following
85 --line if you disagree.
87 --`GHC.ghcCatch` \_ -> io $ exitWith (ExitFailure 1)
89 -----------------------------------------------------------------
92 -- Create a temporary file,
94 -- slurp through it, etc
96 -----------------------------------------------------------------
99 = MkDep { mkd_make_file :: FilePath, -- Name of the makefile
100 mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile
101 mkd_tmp_file :: FilePath, -- Name of the temporary file
102 mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
104 beginMkDependHS :: DynFlags -> IO MkDepFiles
105 beginMkDependHS dflags = do
106 -- open a new temp file in which to stuff the dependency info
108 tmp_file <- newTempName dflags "dep"
109 tmp_hdl <- openFile tmp_file WriteMode
112 let makefile = depMakefile dflags
113 exists <- doesFileExist makefile
118 makefile_hdl <- openFile makefile ReadMode
120 -- slurp through until we get the magic start string,
121 -- copying the contents into dep_makefile
123 l <- hGetLine makefile_hdl
124 if (l == depStartMarker)
126 else do hPutStrLn tmp_hdl l; slurp
128 -- slurp through until we get the magic end marker,
129 -- throwing away the contents
131 l <- hGetLine makefile_hdl
132 if (l == depEndMarker)
137 (\e -> if isEOFError e then return () else ioError e)
139 (\e -> if isEOFError e then return () else ioError e)
141 return (Just makefile_hdl)
144 -- write the magic marker into the tmp file
145 hPutStrLn tmp_hdl depStartMarker
147 return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
148 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
151 -----------------------------------------------------------------
155 -----------------------------------------------------------------
157 processDeps :: DynFlags
160 -> Handle -- Write dependencies to here
163 -- Write suitable dependencies to handle
167 -- If the dependency is on something other than a .hi file:
168 -- this.o this.p_o ... : dep
170 -- this.o ... : dep.hi
171 -- this.p_o ... : dep.p_hi
173 -- (where .o is $osuf, and the other suffixes come from
174 -- the cmdline -s options).
176 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
178 processDeps _ _ _ _ (CyclicSCC nodes)
179 = -- There shouldn't be any cycles; report them
180 ghcError (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
182 processDeps dflags hsc_env excl_mods hdl (AcyclicSCC node)
183 = do { let extra_suffixes = depSuffixes dflags
184 include_pkg_deps = depIncludePkgDeps dflags
185 src_file = msHsFilePath node
186 obj_file = msObjFilePath node
187 obj_files = insertSuffixes obj_file extra_suffixes
189 do_imp is_boot imp_mod
190 = do { mb_hi <- findDependency hsc_env src_file imp_mod
191 is_boot include_pkg_deps
193 Nothing -> return () ;
195 { let hi_files = insertSuffixes hi_file extra_suffixes
196 write_dep (obj,hi) = writeDependency hdl [obj] hi
198 -- Add one dependency for each suffix;
201 ; mapM_ write_dep (obj_files `zip` hi_files) }}}
204 -- Emit std dependency of the object(s) on the source file
205 -- Something like A.o : A.hs
206 ; writeDependency hdl obj_files src_file
208 -- Emit a dependency for each import
211 ; mapM_ (do_imp True)
212 (filter (`notElem` excl_mods) (map unLoc (ms_srcimps node)))
215 ; mapM_ (do_imp False)
216 (filter (`notElem` excl_mods) (map unLoc (ms_imps node)))
218 ; when (dopt Opt_ImplicitPrelude (ms_hspp_opts node)) $
219 do_imp False pRELUDE_NAME
223 findDependency :: HscEnv
224 -> FilePath -- Importing module: used only for error msg
225 -> ModuleName -- Imported module
226 -> IsBootInterface -- Source import
227 -> Bool -- Record dependency on package modules
228 -> IO (Maybe FilePath) -- Interface file file
229 findDependency hsc_env _ imp is_boot include_pkg_deps
230 = do { -- Find the module; this will be fast because
231 -- we've done it once during downsweep
232 r <- findImportedModule hsc_env imp Nothing
235 -- Home package: just depend on the .hi or hi-boot file
236 | isJust (ml_hs_file loc) || include_pkg_deps
237 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
239 -- Not in this package: we don't need a dependency
243 _ -> panic "findDependency"
246 -----------------------------
247 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
248 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
250 writeDependency hdl targets dep
251 = hPutStrLn hdl (unwords (map forOutput targets) ++ " : " ++ forOutput dep)
252 where forOutput = escapeSpaces . reslash Forwards . normalise
254 -----------------------------
256 :: FilePath -- Original filename; e.g. "foo.o"
257 -> [String] -- Extra suffices e.g. ["x","y"]
258 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
259 -- Note that that the extra bit gets inserted *before* the old suffix
260 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
262 -- NOTE: we used to have this comment
263 -- In order to construct hi files with alternate suffixes, we
264 -- now have to find the "basename" of the hi file. This is
265 -- difficult because we can't just split the hi filename
266 -- at the last dot - the hisuf might have dots in it. So we
267 -- check whether the hi filename ends in hisuf, and if it does,
268 -- we strip off hisuf, otherwise we strip everything after the
270 -- But I'm not sure we care about hisufs with dots in them.
271 -- Lots of other things will break first!
273 insertSuffixes file_name extras
274 = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ]
276 (basename, suffix) = case splitExtension file_name of
277 -- Drop the "." from the extension
278 (b, s) -> (b, drop 1 s)
281 -----------------------------------------------------------------
284 -- Complete the makefile, close the tmp file etc
286 -----------------------------------------------------------------
288 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
291 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
292 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
294 -- write the magic marker into the tmp file
295 hPutStrLn tmp_hdl depEndMarker
301 -- slurp the rest of the original makefile and copy it into the output
308 (\e -> if isEOFError e then return () else ioError e)
312 hClose tmp_hdl -- make sure it's flushed
314 -- Create a backup of the original makefile
315 when (isJust makefile_hdl)
316 (SysTools.copy dflags ("Backing up " ++ makefile)
317 makefile (makefile++".bak"))
319 -- Copy the new makefile in place
320 SysTools.copy dflags "Installing new makefile" tmp_file makefile
323 -----------------------------------------------------------------
325 -----------------------------------------------------------------
327 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
328 dumpModCycles dflags mod_summaries
329 | not (dopt Opt_D_dump_mod_cycles dflags)
333 = putMsg dflags (ptext (sLit "No module cycles"))
336 = putMsg dflags (hang (ptext (sLit "Module cycles found:")) 2 pp_cycles)
339 cycles :: [[ModSummary]]
340 cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
342 pp_cycles = vcat [ (ptext (sLit "---------- Cycle") <+> int n <+> ptext (sLit "----------"))
343 $$ pprCycle c $$ text ""
344 | (n,c) <- [1..] `zip` cycles ]
346 pprCycle :: [ModSummary] -> SDoc
347 -- Print a cycle, but show only the imports within the cycle
348 pprCycle summaries = pp_group (CyclicSCC summaries)
350 cycle_mods :: [ModuleName] -- The modules in this cycle
351 cycle_mods = map (moduleName . ms_mod) summaries
353 pp_group (AcyclicSCC ms) = pp_ms ms
354 pp_group (CyclicSCC mss)
355 = ASSERT( not (null boot_only) )
356 -- The boot-only list must be non-empty, else there would
357 -- be an infinite chain of non-boot imoprts, and we've
358 -- already checked for that in processModDeps
359 pp_ms loop_breaker $$ vcat (map pp_group groups)
361 (boot_only, others) = partition is_boot_only mss
362 is_boot_only ms = not (any in_group (ms_imps ms))
363 in_group (L _ m) = m `elem` group_mods
364 group_mods = map (moduleName . ms_mod) mss
366 loop_breaker = head boot_only
367 all_others = tail boot_only ++ others
368 groups = GHC.topSortModuleGraph True all_others Nothing
370 pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
371 <+> (pp_imps empty (ms_imps summary) $$
372 pp_imps (ptext (sLit "{-# SOURCE #-}")) (ms_srcimps summary))
374 mod_str = moduleNameString (moduleName (ms_mod summary))
376 pp_imps :: SDoc -> [Located ModuleName] -> SDoc
379 = case [m | L _ m <- lms, m `elem` cycle_mods] of
381 ms -> what <+> ptext (sLit "imports") <+>
384 -----------------------------------------------------------------
388 -----------------------------------------------------------------
390 depStartMarker, depEndMarker :: String
391 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
392 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"