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(..) )
17 import DynFlags ( DynFlags( verbosity, opt_dep ), getOpts )
18 import Util ( escapeSpaces, splitFilename, joinFileExt )
19 import HscTypes ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath )
20 import Packages ( PackageIdH(..) )
21 import SysTools ( newTempName )
22 import qualified SysTools
23 import Module ( Module, ModLocation(..), mkModule, moduleUserString,
25 import Digraph ( SCC(..) )
26 import Finder ( findModule, FindResult(..) )
27 import Util ( global, consIORef )
30 import SrcLoc ( unLoc )
33 #if __GLASGOW_HASKELL__ <= 408
34 import Panic ( catchJust, ioErrors )
36 import ErrUtils ( debugTraceMsg, printErrorsAndWarnings )
38 import DATA_IOREF ( IORef, readIORef, writeIORef )
41 import System ( ExitCode(..), exitWith )
45 import Maybe ( isJust )
47 -----------------------------------------------------------------
51 -----------------------------------------------------------------
53 doMkDependHS :: Session -> [FilePath] -> IO ()
54 doMkDependHS session srcs
55 = do { -- Initialisation
56 dflags <- GHC.getSessionDynFlags session
57 ; files <- beginMkDependHS dflags
59 -- Do the downsweep to find all the modules
60 ; targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
61 ; GHC.setTargets session targets
62 ; excl_mods <- readIORef v_Dep_exclude_mods
63 ; r <- GHC.depanal session excl_mods True {- Allow dup roots -}
65 Nothing -> exitWith (ExitFailure 1)
66 Just mod_summaries -> do {
68 -- Sort into dependency order
69 -- There should be no cycles
70 let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
72 -- Print out the dependencies if wanted
73 ; debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
75 -- Prcess them one by one, dumping results into makefile
76 -- and complaining about cycles
77 ; mapM (processDeps session excl_mods (mkd_tmp_hdl files)) sorted
80 ; endMkDependHS dflags files }}
82 -----------------------------------------------------------------
85 -- Create a temporary file,
87 -- slurp through it, etc
89 -----------------------------------------------------------------
92 = MkDep { mkd_make_file :: FilePath, -- Name of the makefile
93 mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile
94 mkd_tmp_file :: FilePath, -- Name of the temporary file
95 mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
97 beginMkDependHS :: DynFlags -> IO MkDepFiles
99 beginMkDependHS dflags = do
100 -- slurp in the mkdependHS-style options
101 let flags = getOpts dflags opt_dep
102 _ <- processArgs dep_opts flags
104 -- open a new temp file in which to stuff the dependency info
106 tmp_file <- newTempName dflags "dep"
107 tmp_hdl <- openFile tmp_file WriteMode
110 makefile <- readIORef v_Dep_makefile
111 exists <- doesFileExist makefile
116 makefile_hdl <- openFile makefile ReadMode
118 -- slurp through until we get the magic start string,
119 -- copying the contents into dep_makefile
121 l <- hGetLine makefile_hdl
122 if (l == depStartMarker)
124 else do hPutStrLn tmp_hdl l; slurp
126 -- slurp through until we get the magic end marker,
127 -- throwing away the contents
129 l <- hGetLine makefile_hdl
130 if (l == depEndMarker)
134 catchJust ioErrors slurp
135 (\e -> if isEOFError e then return () else ioError e)
136 catchJust ioErrors chuck
137 (\e -> if isEOFError e then return () else ioError e)
139 return (Just makefile_hdl)
142 -- write the magic marker into the tmp file
143 hPutStrLn tmp_hdl depStartMarker
145 return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
146 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
149 -----------------------------------------------------------------
153 -----------------------------------------------------------------
155 processDeps :: Session
157 -> Handle -- Write dependencies to here
160 -- Write suitable dependencies to handle
164 -- If the dependency is on something other than a .hi file:
165 -- this.o this.p_o ... : dep
167 -- this.o ... : dep.hi
168 -- this.p_o ... : dep.p_hi
170 -- (where .o is $osuf, and the other suffixes come from
171 -- the cmdline -s options).
173 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
175 processDeps session excl_mods hdl (CyclicSCC nodes)
176 = -- There shouldn't be any cycles; report them
177 throwDyn (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
179 processDeps session excl_mods hdl (AcyclicSCC node)
180 = do { extra_suffixes <- readIORef v_Dep_suffixes
181 ; hsc_env <- GHC.sessionHscEnv session
182 ; include_pkg_deps <- readIORef v_Dep_include_pkg_deps
183 ; let src_file = msHsFilePath node
184 obj_file = msObjFilePath node
185 obj_files = insertSuffixes obj_file extra_suffixes
187 do_imp is_boot imp_mod
188 = do { mb_hi <- findDependency hsc_env src_file imp_mod
189 is_boot include_pkg_deps
191 Nothing -> return () ;
193 { let hi_files = insertSuffixes hi_file extra_suffixes
194 write_dep (obj,hi) = writeDependency hdl [obj] hi
196 -- Add one dependency for each suffix;
199 ; mapM_ write_dep (obj_files `zip` hi_files) }}}
202 -- Emit std dependency of the object(s) on the source file
203 -- Something like A.o : A.hs
204 ; writeDependency hdl obj_files src_file
206 -- Emit a dependency for each import
209 ; mapM_ (do_imp True)
210 (filter (`notElem` excl_mods) (map unLoc (ms_srcimps node)))
213 ; mapM_ (do_imp False)
214 (filter (`notElem` excl_mods) (map unLoc (ms_imps node)))
218 findDependency :: HscEnv
219 -> FilePath -- Importing module: used only for error msg
220 -> Module -- Imported module
221 -> IsBootInterface -- Source import
222 -> Bool -- Record dependency on package modules
223 -> IO (Maybe FilePath) -- Interface file file
224 findDependency hsc_env src imp is_boot include_pkg_deps
225 = do { -- Find the module; this will be fast because
226 -- we've done it once during downsweep
227 r <- findModule hsc_env imp True {-explicit-}
230 -- Not in this package: we don't need a dependency
231 | ExtPackage _ <- pkg, not include_pkg_deps
234 -- Home package: just depend on the .hi or hi-boot file
236 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
238 _ -> panic "findDependency"
241 -----------------------------
242 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
243 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
245 writeDependency hdl targets dep
246 = hPutStrLn hdl (unwords (map escapeSpaces targets) ++ " : "
249 -----------------------------
251 :: FilePath -- Original filename; e.g. "foo.o"
252 -> [String] -- Extra suffices e.g. ["x","y"]
253 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
254 -- Note that that the extra bit gets inserted *before* the old suffix
255 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
257 -- NOTE: we used to have this comment
258 -- In order to construct hi files with alternate suffixes, we
259 -- now have to find the "basename" of the hi file. This is
260 -- difficult because we can't just split the hi filename
261 -- at the last dot - the hisuf might have dots in it. So we
262 -- check whether the hi filename ends in hisuf, and if it does,
263 -- we strip off hisuf, otherwise we strip everything after the
265 -- But I'm not sure we care about hisufs with dots in them.
266 -- Lots of other things will break first!
268 insertSuffixes file_name extras
269 = file_name : [ basename `joinFileExt` (extra ++ "_" ++ suffix) | extra <- extras ]
271 (basename, suffix) = splitFilename file_name
274 -----------------------------------------------------------------
277 -- Complete the makefile, close the tmp file etc
279 -----------------------------------------------------------------
281 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
284 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
285 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
287 -- write the magic marker into the tmp file
288 hPutStrLn tmp_hdl depEndMarker
294 -- slurp the rest of the original makefile and copy it into the output
300 catchJust ioErrors slurp
301 (\e -> if isEOFError e then return () else ioError e)
305 hClose tmp_hdl -- make sure it's flushed
307 -- Create a backup of the original makefile
308 when (isJust makefile_hdl)
309 (SysTools.copy dflags ("Backing up " ++ makefile)
310 makefile (makefile++".bak"))
312 -- Copy the new makefile in place
313 SysTools.copy dflags "Installing new makefile" tmp_file makefile
316 -----------------------------------------------------------------
320 -----------------------------------------------------------------
323 GLOBAL_VAR(v_Dep_makefile, "Makefile", String);
324 GLOBAL_VAR(v_Dep_include_pkg_deps, False, Bool);
325 GLOBAL_VAR(v_Dep_exclude_mods, [], [Module]);
326 GLOBAL_VAR(v_Dep_suffixes, [], [String]);
327 GLOBAL_VAR(v_Dep_warnings, True, Bool);
329 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
330 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"
332 -- for compatibility with the old mkDependHS, we accept options of the form
333 -- -optdep-f -optdep.depend, etc.
335 [ ( "s", SepArg (consIORef v_Dep_suffixes) )
336 , ( "f", SepArg (writeIORef v_Dep_makefile) )
337 , ( "w", NoArg (writeIORef v_Dep_warnings False) )
338 , ( "-include-prelude", NoArg (writeIORef v_Dep_include_pkg_deps True) )
339 , ( "-include-pkg-deps", NoArg (writeIORef v_Dep_include_pkg_deps True) )
340 , ( "-exclude-module=", Prefix (consIORef v_Dep_exclude_mods . mkModule) )
341 , ( "x", Prefix (consIORef v_Dep_exclude_mods . mkModule) )