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 #if __GLASGOW_HASKELL__ <= 408
33 import Panic ( catchJust, ioErrors )
35 import ErrUtils ( debugTraceMsg, putMsg )
37 import Data.IORef ( IORef, readIORef, writeIORef )
38 import Control.Exception
39 import System.Exit ( ExitCode(..), exitWith )
40 import System.Directory
42 import SYSTEM_IO_ERROR ( isEOFError )
43 import Control.Monad ( when )
44 import Data.Maybe ( isJust )
46 -----------------------------------------------------------------
50 -----------------------------------------------------------------
52 doMkDependHS :: Session -> [FilePath] -> IO ()
53 doMkDependHS session srcs
54 = do { -- Initialisation
55 dflags <- GHC.getSessionDynFlags session
56 ; files <- beginMkDependHS dflags
58 -- Do the downsweep to find all the modules
59 ; targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
60 ; GHC.setTargets session targets
61 ; excl_mods <- readIORef v_Dep_exclude_mods
62 ; r <- GHC.depanal session excl_mods True {- Allow dup roots -}
64 Nothing -> exitWith (ExitFailure 1)
65 Just mod_summaries -> do {
67 -- Sort into dependency order
68 -- There should be no cycles
69 let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
71 -- Print out the dependencies if wanted
72 ; debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
74 -- Prcess them one by one, dumping results into makefile
75 -- and complaining about cycles
76 ; mapM (processDeps session excl_mods (mkd_tmp_hdl files)) sorted
78 -- If -ddump-mod-cycles, show cycles in the module graph
79 ; dumpModCycles dflags mod_summaries
82 ; endMkDependHS dflags files }}
84 -----------------------------------------------------------------
87 -- Create a temporary file,
89 -- slurp through it, etc
91 -----------------------------------------------------------------
94 = MkDep { mkd_make_file :: FilePath, -- Name of the makefile
95 mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile
96 mkd_tmp_file :: FilePath, -- Name of the temporary file
97 mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
99 beginMkDependHS :: DynFlags -> IO MkDepFiles
101 beginMkDependHS dflags = do
102 -- slurp in the mkdependHS-style options
103 let flags = getOpts dflags opt_dep
104 _ <- processArgs dep_opts flags
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 makefile <- readIORef v_Dep_makefile
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)
136 catchJust ioErrors slurp
137 (\e -> if isEOFError e then return () else ioError e)
138 catchJust ioErrors chuck
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 :: Session
159 -> Handle -- Write dependencies to here
162 -- Write suitable dependencies to handle
166 -- If the dependency is on something other than a .hi file:
167 -- this.o this.p_o ... : dep
169 -- this.o ... : dep.hi
170 -- this.p_o ... : dep.p_hi
172 -- (where .o is $osuf, and the other suffixes come from
173 -- the cmdline -s options).
175 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
177 processDeps session excl_mods hdl (CyclicSCC nodes)
178 = -- There shouldn't be any cycles; report them
179 throwDyn (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
181 processDeps session excl_mods hdl (AcyclicSCC node)
182 = do { extra_suffixes <- readIORef v_Dep_suffixes
183 ; hsc_env <- GHC.sessionHscEnv session
184 ; include_pkg_deps <- readIORef v_Dep_include_pkg_deps
185 ; let 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)))
220 findDependency :: HscEnv
221 -> FilePath -- Importing module: used only for error msg
222 -> ModuleName -- Imported module
223 -> IsBootInterface -- Source import
224 -> Bool -- Record dependency on package modules
225 -> IO (Maybe FilePath) -- Interface file file
226 findDependency hsc_env src imp is_boot include_pkg_deps
227 = do { -- Find the module; this will be fast because
228 -- we've done it once during downsweep
229 r <- findImportedModule hsc_env imp Nothing
232 -- Home package: just depend on the .hi or hi-boot file
233 | isJust (ml_hs_file loc)
234 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
236 -- Not in this package: we don't need a dependency
240 _ -> panic "findDependency"
243 -----------------------------
244 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
245 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
247 writeDependency hdl targets dep
248 = hPutStrLn hdl (unwords (map escapeSpaces targets) ++ " : "
251 -----------------------------
253 :: FilePath -- Original filename; e.g. "foo.o"
254 -> [String] -- Extra suffices e.g. ["x","y"]
255 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
256 -- Note that that the extra bit gets inserted *before* the old suffix
257 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
259 -- NOTE: we used to have this comment
260 -- In order to construct hi files with alternate suffixes, we
261 -- now have to find the "basename" of the hi file. This is
262 -- difficult because we can't just split the hi filename
263 -- at the last dot - the hisuf might have dots in it. So we
264 -- check whether the hi filename ends in hisuf, and if it does,
265 -- we strip off hisuf, otherwise we strip everything after the
267 -- But I'm not sure we care about hisufs with dots in them.
268 -- Lots of other things will break first!
270 insertSuffixes file_name extras
271 = file_name : [ basename `joinFileExt` (extra ++ "_" ++ suffix) | extra <- extras ]
273 (basename, suffix) = splitFilename file_name
276 -----------------------------------------------------------------
279 -- Complete the makefile, close the tmp file etc
281 -----------------------------------------------------------------
283 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
286 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
287 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
289 -- write the magic marker into the tmp file
290 hPutStrLn tmp_hdl depEndMarker
296 -- slurp the rest of the original makefile and copy it into the output
302 catchJust ioErrors slurp
303 (\e -> if isEOFError e then return () else ioError e)
307 hClose tmp_hdl -- make sure it's flushed
309 -- Create a backup of the original makefile
310 when (isJust makefile_hdl)
311 (SysTools.copy dflags ("Backing up " ++ makefile)
312 makefile (makefile++".bak"))
314 -- Copy the new makefile in place
315 SysTools.copy dflags "Installing new makefile" tmp_file makefile
318 -----------------------------------------------------------------
320 -----------------------------------------------------------------
322 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
323 dumpModCycles dflags mod_summaries
324 | not (dopt Opt_D_dump_mod_cycles dflags)
328 = putMsg dflags (ptext SLIT("No module cycles"))
331 = putMsg dflags (hang (ptext SLIT("Module cycles found:")) 2 pp_cycles)
334 cycles :: [[ModSummary]]
335 cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
337 pp_cycles = vcat [ (ptext SLIT("---------- Cycle") <+> int n <+> ptext SLIT("----------"))
338 $$ pprCycle c $$ text ""
339 | (n,c) <- [1..] `zip` cycles ]
341 pprCycle :: [ModSummary] -> SDoc
342 -- Print a cycle, but show only the imports within the cycle
343 pprCycle summaries = pp_group (CyclicSCC summaries)
345 cycle_mods :: [ModuleName] -- The modules in this cycle
346 cycle_mods = map (moduleName . ms_mod) summaries
348 pp_group (AcyclicSCC ms) = pp_ms ms
349 pp_group (CyclicSCC mss)
350 = ASSERT( not (null boot_only) )
351 -- The boot-only list must be non-empty, else there would
352 -- be an infinite chain of non-boot imoprts, and we've
353 -- already checked for that in processModDeps
354 pp_ms loop_breaker $$ vcat (map pp_group groups)
356 (boot_only, others) = partition is_boot_only mss
357 is_boot_only ms = not (any in_group (ms_imps ms))
358 in_group (L _ m) = m `elem` group_mods
359 group_mods = map (moduleName . ms_mod) mss
361 loop_breaker = head boot_only
362 all_others = tail boot_only ++ others
363 groups = GHC.topSortModuleGraph True all_others Nothing
365 pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
366 <+> (pp_imps empty (ms_imps summary) $$
367 pp_imps (ptext SLIT("{-# SOURCE #-}")) (ms_srcimps summary))
369 mod_str = moduleNameString (moduleName (ms_mod summary))
371 pp_imps :: SDoc -> [Located ModuleName] -> SDoc
372 pp_imps what [] = empty
374 = case [m | L _ m <- lms, m `elem` cycle_mods] of
376 ms -> what <+> ptext SLIT("imports") <+>
379 -----------------------------------------------------------------
383 -----------------------------------------------------------------
386 GLOBAL_VAR(v_Dep_makefile, "Makefile", String);
387 GLOBAL_VAR(v_Dep_include_pkg_deps, False, Bool);
388 GLOBAL_VAR(v_Dep_exclude_mods, [], [ModuleName]);
389 GLOBAL_VAR(v_Dep_suffixes, [], [String]);
390 GLOBAL_VAR(v_Dep_warnings, True, Bool);
392 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
393 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"
395 -- for compatibility with the old mkDependHS, we accept options of the form
396 -- -optdep-f -optdep.depend, etc.
398 [ ( "s", SepArg (consIORef v_Dep_suffixes) )
399 , ( "f", SepArg (writeIORef v_Dep_makefile) )
400 , ( "w", NoArg (writeIORef v_Dep_warnings False) )
401 , ( "-include-prelude", NoArg (writeIORef v_Dep_include_pkg_deps True) )
402 , ( "-include-pkg-deps", NoArg (writeIORef v_Dep_include_pkg_deps True) )
403 , ( "-exclude-module=", Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )
404 , ( "x", Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )