1 -----------------------------------------------------------------------------
3 -- Makefile Dependency Generation
5 -- (c) The University of Glasgow 2005
7 -----------------------------------------------------------------------------
9 module DriverMkDepend (
13 #include "HsVersions.h"
16 import GHC ( Session, ModSummary(..) )
18 import Util ( escapeSpaces, splitFilename, joinFileExt )
19 import HscTypes ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath )
20 import SysTools ( newTempName )
21 import qualified SysTools
23 import Digraph ( SCC(..) )
24 import Finder ( findImportedModule, FindResult(..) )
25 import Util ( global, consIORef )
32 import ErrUtils ( debugTraceMsg, putMsg )
34 import Data.IORef ( IORef, readIORef, writeIORef )
35 import Control.Exception
36 import System.Exit ( ExitCode(..), exitWith )
37 import System.Directory
39 import SYSTEM_IO_ERROR ( isEOFError )
40 import Control.Monad ( when )
41 import Data.Maybe ( isJust )
43 -----------------------------------------------------------------
47 -----------------------------------------------------------------
49 doMkDependHS :: Session -> [FilePath] -> IO ()
50 doMkDependHS session srcs
51 = do { -- Initialisation
52 dflags <- GHC.getSessionDynFlags session
53 ; files <- beginMkDependHS dflags
55 -- Do the downsweep to find all the modules
56 ; targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
57 ; GHC.setTargets session targets
58 ; excl_mods <- readIORef v_Dep_exclude_mods
59 ; r <- GHC.depanal session excl_mods True {- Allow dup roots -}
61 Nothing -> exitWith (ExitFailure 1)
62 Just mod_summaries -> do {
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 ; debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
71 -- Prcess them one by one, dumping results into makefile
72 -- and complaining about cycles
73 ; mapM (processDeps session excl_mods (mkd_tmp_hdl files)) sorted
75 -- If -ddump-mod-cycles, show cycles in the module graph
76 ; dumpModCycles dflags mod_summaries
79 ; endMkDependHS dflags files }}
81 -----------------------------------------------------------------
84 -- Create a temporary file,
86 -- slurp through it, etc
88 -----------------------------------------------------------------
91 = MkDep { mkd_make_file :: FilePath, -- Name of the makefile
92 mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile
93 mkd_tmp_file :: FilePath, -- Name of the temporary file
94 mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
96 beginMkDependHS :: DynFlags -> IO MkDepFiles
98 beginMkDependHS dflags = do
99 -- slurp in the mkdependHS-style options
100 let flags = getOpts dflags opt_dep
101 _ <- processArgs dep_opts flags
103 -- open a new temp file in which to stuff the dependency info
105 tmp_file <- newTempName dflags "dep"
106 tmp_hdl <- openFile tmp_file WriteMode
109 makefile <- readIORef v_Dep_makefile
110 exists <- doesFileExist makefile
115 makefile_hdl <- openFile makefile ReadMode
117 -- slurp through until we get the magic start string,
118 -- copying the contents into dep_makefile
120 l <- hGetLine makefile_hdl
121 if (l == depStartMarker)
123 else do hPutStrLn tmp_hdl l; slurp
125 -- slurp through until we get the magic end marker,
126 -- throwing away the contents
128 l <- hGetLine makefile_hdl
129 if (l == depEndMarker)
133 catchJust ioErrors slurp
134 (\e -> if isEOFError e then return () else ioError e)
135 catchJust ioErrors chuck
136 (\e -> if isEOFError e then return () else ioError e)
138 return (Just makefile_hdl)
141 -- write the magic marker into the tmp file
142 hPutStrLn tmp_hdl depStartMarker
144 return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
145 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
148 -----------------------------------------------------------------
152 -----------------------------------------------------------------
154 processDeps :: Session
156 -> Handle -- Write dependencies to here
159 -- Write suitable dependencies to handle
163 -- If the dependency is on something other than a .hi file:
164 -- this.o this.p_o ... : dep
166 -- this.o ... : dep.hi
167 -- this.p_o ... : dep.p_hi
169 -- (where .o is $osuf, and the other suffixes come from
170 -- the cmdline -s options).
172 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
174 processDeps session excl_mods hdl (CyclicSCC nodes)
175 = -- There shouldn't be any cycles; report them
176 throwDyn (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
178 processDeps session excl_mods hdl (AcyclicSCC node)
179 = do { extra_suffixes <- readIORef v_Dep_suffixes
180 ; hsc_env <- GHC.sessionHscEnv session
181 ; include_pkg_deps <- readIORef v_Dep_include_pkg_deps
182 ; let src_file = msHsFilePath node
183 obj_file = msObjFilePath node
184 obj_files = insertSuffixes obj_file extra_suffixes
186 do_imp is_boot imp_mod
187 = do { mb_hi <- findDependency hsc_env src_file imp_mod
188 is_boot include_pkg_deps
190 Nothing -> return () ;
192 { let hi_files = insertSuffixes hi_file extra_suffixes
193 write_dep (obj,hi) = writeDependency hdl [obj] hi
195 -- Add one dependency for each suffix;
198 ; mapM_ write_dep (obj_files `zip` hi_files) }}}
201 -- Emit std dependency of the object(s) on the source file
202 -- Something like A.o : A.hs
203 ; writeDependency hdl obj_files src_file
205 -- Emit a dependency for each import
208 ; mapM_ (do_imp True)
209 (filter (`notElem` excl_mods) (map unLoc (ms_srcimps node)))
212 ; mapM_ (do_imp False)
213 (filter (`notElem` excl_mods) (map unLoc (ms_imps node)))
217 findDependency :: HscEnv
218 -> FilePath -- Importing module: used only for error msg
219 -> ModuleName -- Imported module
220 -> IsBootInterface -- Source import
221 -> Bool -- Record dependency on package modules
222 -> IO (Maybe FilePath) -- Interface file file
223 findDependency hsc_env src imp is_boot include_pkg_deps
224 = do { -- Find the module; this will be fast because
225 -- we've done it once during downsweep
226 r <- findImportedModule hsc_env imp Nothing
229 -- Home package: just depend on the .hi or hi-boot file
230 | isJust (ml_hs_file loc)
231 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
233 -- Not in this package: we don't need a dependency
237 _ -> panic "findDependency"
240 -----------------------------
241 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
242 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
244 writeDependency hdl targets dep
245 = hPutStrLn hdl (unwords (map escapeSpaces targets) ++ " : "
248 -----------------------------
250 :: FilePath -- Original filename; e.g. "foo.o"
251 -> [String] -- Extra suffices e.g. ["x","y"]
252 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
253 -- Note that that the extra bit gets inserted *before* the old suffix
254 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
256 -- NOTE: we used to have this comment
257 -- In order to construct hi files with alternate suffixes, we
258 -- now have to find the "basename" of the hi file. This is
259 -- difficult because we can't just split the hi filename
260 -- at the last dot - the hisuf might have dots in it. So we
261 -- check whether the hi filename ends in hisuf, and if it does,
262 -- we strip off hisuf, otherwise we strip everything after the
264 -- But I'm not sure we care about hisufs with dots in them.
265 -- Lots of other things will break first!
267 insertSuffixes file_name extras
268 = file_name : [ basename `joinFileExt` (extra ++ "_" ++ suffix) | extra <- extras ]
270 (basename, suffix) = splitFilename file_name
273 -----------------------------------------------------------------
276 -- Complete the makefile, close the tmp file etc
278 -----------------------------------------------------------------
280 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
283 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
284 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
286 -- write the magic marker into the tmp file
287 hPutStrLn tmp_hdl depEndMarker
293 -- slurp the rest of the original makefile and copy it into the output
299 catchJust ioErrors slurp
300 (\e -> if isEOFError e then return () else ioError e)
304 hClose tmp_hdl -- make sure it's flushed
306 -- Create a backup of the original makefile
307 when (isJust makefile_hdl)
308 (SysTools.copy dflags ("Backing up " ++ makefile)
309 makefile (makefile++".bak"))
311 -- Copy the new makefile in place
312 SysTools.copy dflags "Installing new makefile" tmp_file makefile
315 -----------------------------------------------------------------
317 -----------------------------------------------------------------
319 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
320 dumpModCycles dflags mod_summaries
321 | not (dopt Opt_D_dump_mod_cycles dflags)
325 = putMsg dflags (ptext SLIT("No module cycles"))
328 = putMsg dflags (hang (ptext SLIT("Module cycles found:")) 2 pp_cycles)
331 cycles :: [[ModSummary]]
332 cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
334 pp_cycles = vcat [ (ptext SLIT("---------- Cycle") <+> int n <+> ptext SLIT("----------"))
335 $$ pprCycle c $$ text ""
336 | (n,c) <- [1..] `zip` cycles ]
338 pprCycle :: [ModSummary] -> SDoc
339 -- Print a cycle, but show only the imports within the cycle
340 pprCycle summaries = pp_group (CyclicSCC summaries)
342 cycle_mods :: [ModuleName] -- The modules in this cycle
343 cycle_mods = map (moduleName . ms_mod) summaries
345 pp_group (AcyclicSCC ms) = pp_ms ms
346 pp_group (CyclicSCC mss)
347 = ASSERT( not (null boot_only) )
348 -- The boot-only list must be non-empty, else there would
349 -- be an infinite chain of non-boot imoprts, and we've
350 -- already checked for that in processModDeps
351 pp_ms loop_breaker $$ vcat (map pp_group groups)
353 (boot_only, others) = partition is_boot_only mss
354 is_boot_only ms = not (any in_group (ms_imps ms))
355 in_group (L _ m) = m `elem` group_mods
356 group_mods = map (moduleName . ms_mod) mss
358 loop_breaker = head boot_only
359 all_others = tail boot_only ++ others
360 groups = GHC.topSortModuleGraph True all_others Nothing
362 pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
363 <+> (pp_imps empty (ms_imps summary) $$
364 pp_imps (ptext SLIT("{-# SOURCE #-}")) (ms_srcimps summary))
366 mod_str = moduleNameString (moduleName (ms_mod summary))
368 pp_imps :: SDoc -> [Located ModuleName] -> SDoc
369 pp_imps what [] = empty
371 = case [m | L _ m <- lms, m `elem` cycle_mods] of
373 ms -> what <+> ptext SLIT("imports") <+>
376 -----------------------------------------------------------------
380 -----------------------------------------------------------------
383 GLOBAL_VAR(v_Dep_makefile, "Makefile", String);
384 GLOBAL_VAR(v_Dep_include_pkg_deps, False, Bool);
385 GLOBAL_VAR(v_Dep_exclude_mods, [], [ModuleName]);
386 GLOBAL_VAR(v_Dep_suffixes, [], [String]);
387 GLOBAL_VAR(v_Dep_warnings, True, Bool);
389 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
390 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"
392 -- for compatibility with the old mkDependHS, we accept options of the form
393 -- -optdep-f -optdep.depend, etc.
395 [ ( "s", SepArg (consIORef v_Dep_suffixes) )
396 , ( "f", SepArg (writeIORef v_Dep_makefile) )
397 , ( "w", NoArg (writeIORef v_Dep_warnings False) )
399 , ( "-include-prelude", NoArg (writeIORef v_Dep_include_pkg_deps True) )
400 -- -include-prelude is the old name for -include-pkg-deps, kept around
401 -- for backward compatibility, but undocumented
403 , ( "-include-pkg-deps", NoArg (writeIORef v_Dep_include_pkg_deps True) )
404 , ( "-exclude-module=", Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )
405 , ( "x", Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )