2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
8 -----------------------------------------------------------------------------
10 -- Makefile Dependency Generation
12 -- (c) The University of Glasgow 2005
14 -----------------------------------------------------------------------------
16 module DriverMkDepend (
20 #include "HsVersions.h"
23 import GHC ( Session, ModSummary(..) )
26 import HscTypes ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath )
27 import SysTools ( newTempName )
28 import qualified SysTools
30 import Digraph ( SCC(..) )
31 import Finder ( findImportedModule, FindResult(..) )
32 import Util ( global, consIORef )
39 import ErrUtils ( debugTraceMsg, putMsg )
41 import Data.IORef ( IORef, readIORef, writeIORef )
42 import Control.Exception
43 import System.Exit ( ExitCode(..), exitWith )
44 import System.Directory
45 import System.FilePath
47 import SYSTEM_IO_ERROR ( isEOFError )
48 import Control.Monad ( when )
49 import Data.Maybe ( isJust )
51 -----------------------------------------------------------------
55 -----------------------------------------------------------------
57 doMkDependHS :: Session -> [FilePath] -> IO ()
58 doMkDependHS session srcs
59 = do { -- Initialisation
60 dflags <- GHC.getSessionDynFlags session
61 ; files <- beginMkDependHS dflags
63 -- Do the downsweep to find all the modules
64 ; targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
65 ; GHC.setTargets session targets
66 ; excl_mods <- readIORef v_Dep_exclude_mods
67 ; r <- GHC.depanal session excl_mods True {- Allow dup roots -}
69 Nothing -> exitWith (ExitFailure 1)
70 Just mod_summaries -> do {
72 -- Sort into dependency order
73 -- There should be no cycles
74 let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
76 -- Print out the dependencies if wanted
77 ; debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
79 -- Prcess them one by one, dumping results into makefile
80 -- and complaining about cycles
81 ; mapM (processDeps session excl_mods (mkd_tmp_hdl files)) sorted
83 -- If -ddump-mod-cycles, show cycles in the module graph
84 ; dumpModCycles dflags mod_summaries
87 ; endMkDependHS dflags files }}
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
106 beginMkDependHS dflags = do
107 -- slurp in the mkdependHS-style options
108 let flags = getOpts dflags opt_dep
109 _ <- processArgs dep_opts flags
111 -- open a new temp file in which to stuff the dependency info
113 tmp_file <- newTempName dflags "dep"
114 tmp_hdl <- openFile tmp_file WriteMode
117 makefile <- readIORef v_Dep_makefile
118 exists <- doesFileExist makefile
123 makefile_hdl <- openFile makefile ReadMode
125 -- slurp through until we get the magic start string,
126 -- copying the contents into dep_makefile
128 l <- hGetLine makefile_hdl
129 if (l == depStartMarker)
131 else do hPutStrLn tmp_hdl l; slurp
133 -- slurp through until we get the magic end marker,
134 -- throwing away the contents
136 l <- hGetLine makefile_hdl
137 if (l == depEndMarker)
141 catchJust ioErrors slurp
142 (\e -> if isEOFError e then return () else ioError e)
143 catchJust ioErrors chuck
144 (\e -> if isEOFError e then return () else ioError e)
146 return (Just makefile_hdl)
149 -- write the magic marker into the tmp file
150 hPutStrLn tmp_hdl depStartMarker
152 return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
153 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
156 -----------------------------------------------------------------
160 -----------------------------------------------------------------
162 processDeps :: Session
164 -> Handle -- Write dependencies to here
167 -- Write suitable dependencies to handle
171 -- If the dependency is on something other than a .hi file:
172 -- this.o this.p_o ... : dep
174 -- this.o ... : dep.hi
175 -- this.p_o ... : dep.p_hi
177 -- (where .o is $osuf, and the other suffixes come from
178 -- the cmdline -s options).
180 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
182 processDeps session excl_mods hdl (CyclicSCC nodes)
183 = -- There shouldn't be any cycles; report them
184 throwDyn (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
186 processDeps session excl_mods hdl (AcyclicSCC node)
187 = do { extra_suffixes <- readIORef v_Dep_suffixes
188 ; hsc_env <- GHC.sessionHscEnv session
189 ; include_pkg_deps <- readIORef v_Dep_include_pkg_deps
190 ; let src_file = msHsFilePath node
191 obj_file = msObjFilePath node
192 obj_files = insertSuffixes obj_file extra_suffixes
194 do_imp is_boot imp_mod
195 = do { mb_hi <- findDependency hsc_env src_file imp_mod
196 is_boot include_pkg_deps
198 Nothing -> return () ;
200 { let hi_files = insertSuffixes hi_file extra_suffixes
201 write_dep (obj,hi) = writeDependency hdl [obj] hi
203 -- Add one dependency for each suffix;
206 ; mapM_ write_dep (obj_files `zip` hi_files) }}}
209 -- Emit std dependency of the object(s) on the source file
210 -- Something like A.o : A.hs
211 ; writeDependency hdl obj_files src_file
213 -- Emit a dependency for each import
216 ; mapM_ (do_imp True)
217 (filter (`notElem` excl_mods) (map unLoc (ms_srcimps node)))
220 ; mapM_ (do_imp False)
221 (filter (`notElem` excl_mods) (map unLoc (ms_imps node)))
225 findDependency :: HscEnv
226 -> FilePath -- Importing module: used only for error msg
227 -> ModuleName -- Imported module
228 -> IsBootInterface -- Source import
229 -> Bool -- Record dependency on package modules
230 -> IO (Maybe FilePath) -- Interface file file
231 findDependency hsc_env src imp is_boot include_pkg_deps
232 = do { -- Find the module; this will be fast because
233 -- we've done it once during downsweep
234 r <- findImportedModule hsc_env imp Nothing
237 -- Home package: just depend on the .hi or hi-boot file
238 | isJust (ml_hs_file loc)
239 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
241 -- Not in this package: we don't need a dependency
245 _ -> panic "findDependency"
248 -----------------------------
249 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
250 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
252 writeDependency hdl targets dep
253 = hPutStrLn hdl (unwords (map forOutput targets) ++ " : " ++ forOutput dep)
254 where forOutput = escapeSpaces . reslash Forwards . normalise
256 -----------------------------
258 :: FilePath -- Original filename; e.g. "foo.o"
259 -> [String] -- Extra suffices e.g. ["x","y"]
260 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
261 -- Note that that the extra bit gets inserted *before* the old suffix
262 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
264 -- NOTE: we used to have this comment
265 -- In order to construct hi files with alternate suffixes, we
266 -- now have to find the "basename" of the hi file. This is
267 -- difficult because we can't just split the hi filename
268 -- at the last dot - the hisuf might have dots in it. So we
269 -- check whether the hi filename ends in hisuf, and if it does,
270 -- we strip off hisuf, otherwise we strip everything after the
272 -- But I'm not sure we care about hisufs with dots in them.
273 -- Lots of other things will break first!
275 insertSuffixes file_name extras
276 = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ]
278 (basename, suffix) = case splitExtension file_name of
279 -- Drop the "." from the extension
280 (b, s) -> (b, drop 1 s)
283 -----------------------------------------------------------------
286 -- Complete the makefile, close the tmp file etc
288 -----------------------------------------------------------------
290 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
293 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
294 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
296 -- write the magic marker into the tmp file
297 hPutStrLn tmp_hdl depEndMarker
303 -- slurp the rest of the original makefile and copy it into the output
309 catchJust ioErrors slurp
310 (\e -> if isEOFError e then return () else ioError e)
314 hClose tmp_hdl -- make sure it's flushed
316 -- Create a backup of the original makefile
317 when (isJust makefile_hdl)
318 (SysTools.copy dflags ("Backing up " ++ makefile)
319 makefile (makefile++".bak"))
321 -- Copy the new makefile in place
322 SysTools.copy dflags "Installing new makefile" tmp_file makefile
325 -----------------------------------------------------------------
327 -----------------------------------------------------------------
329 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
330 dumpModCycles dflags mod_summaries
331 | not (dopt Opt_D_dump_mod_cycles dflags)
335 = putMsg dflags (ptext SLIT("No module cycles"))
338 = putMsg dflags (hang (ptext SLIT("Module cycles found:")) 2 pp_cycles)
341 cycles :: [[ModSummary]]
342 cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
344 pp_cycles = vcat [ (ptext SLIT("---------- Cycle") <+> int n <+> ptext SLIT("----------"))
345 $$ pprCycle c $$ text ""
346 | (n,c) <- [1..] `zip` cycles ]
348 pprCycle :: [ModSummary] -> SDoc
349 -- Print a cycle, but show only the imports within the cycle
350 pprCycle summaries = pp_group (CyclicSCC summaries)
352 cycle_mods :: [ModuleName] -- The modules in this cycle
353 cycle_mods = map (moduleName . ms_mod) summaries
355 pp_group (AcyclicSCC ms) = pp_ms ms
356 pp_group (CyclicSCC mss)
357 = ASSERT( not (null boot_only) )
358 -- The boot-only list must be non-empty, else there would
359 -- be an infinite chain of non-boot imoprts, and we've
360 -- already checked for that in processModDeps
361 pp_ms loop_breaker $$ vcat (map pp_group groups)
363 (boot_only, others) = partition is_boot_only mss
364 is_boot_only ms = not (any in_group (ms_imps ms))
365 in_group (L _ m) = m `elem` group_mods
366 group_mods = map (moduleName . ms_mod) mss
368 loop_breaker = head boot_only
369 all_others = tail boot_only ++ others
370 groups = GHC.topSortModuleGraph True all_others Nothing
372 pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
373 <+> (pp_imps empty (ms_imps summary) $$
374 pp_imps (ptext SLIT("{-# SOURCE #-}")) (ms_srcimps summary))
376 mod_str = moduleNameString (moduleName (ms_mod summary))
378 pp_imps :: SDoc -> [Located ModuleName] -> SDoc
379 pp_imps what [] = empty
381 = case [m | L _ m <- lms, m `elem` cycle_mods] of
383 ms -> what <+> ptext SLIT("imports") <+>
386 -----------------------------------------------------------------
390 -----------------------------------------------------------------
393 GLOBAL_VAR(v_Dep_makefile, "Makefile", String);
394 GLOBAL_VAR(v_Dep_include_pkg_deps, False, Bool);
395 GLOBAL_VAR(v_Dep_exclude_mods, [], [ModuleName]);
396 GLOBAL_VAR(v_Dep_suffixes, [], [String]);
397 GLOBAL_VAR(v_Dep_warnings, True, Bool);
399 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
400 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"
402 -- for compatibility with the old mkDependHS, we accept options of the form
403 -- -optdep-f -optdep.depend, etc.
405 [ ( "s", SepArg (consIORef v_Dep_suffixes) )
406 , ( "f", SepArg (writeIORef v_Dep_makefile) )
407 , ( "w", NoArg (writeIORef v_Dep_warnings False) )
409 , ( "-include-prelude", NoArg (writeIORef v_Dep_include_pkg_deps True) )
410 -- -include-prelude is the old name for -include-pkg-deps, kept around
411 -- for backward compatibility, but undocumented
413 , ( "-include-pkg-deps", NoArg (writeIORef v_Dep_include_pkg_deps True) )
414 , ( "-exclude-module=", Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )
415 , ( "x", Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )