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 ( Session, ModSummary(..) )
22 import HscTypes ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath )
23 import SysTools ( newTempName )
24 import qualified SysTools
26 import Digraph ( SCC(..) )
27 import Finder ( findImportedModule, FindResult(..) )
35 import ErrUtils ( debugTraceMsg, putMsg )
37 import System.Exit ( ExitCode(..), exitWith )
38 import System.Directory
39 import System.FilePath
41 import System.IO.Error ( isEOFError )
42 import Control.Monad ( when )
43 import Data.Maybe ( isJust )
45 -----------------------------------------------------------------
49 -----------------------------------------------------------------
51 doMkDependHS :: Session -> [FilePath] -> IO ()
52 doMkDependHS session srcs
53 = do { -- Initialisation
54 dflags <- GHC.getSessionDynFlags session
55 ; files <- beginMkDependHS dflags
57 -- Do the downsweep to find all the modules
58 ; targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
59 ; GHC.setTargets session targets
60 ; let excl_mods = depExcludeMods dflags
61 ; r <- GHC.depanal session excl_mods True {- Allow dup roots -}
63 Nothing -> exitWith (ExitFailure 1)
64 Just mod_summaries -> do {
66 -- Sort into dependency order
67 -- There should be no cycles
68 let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
70 -- Print out the dependencies if wanted
71 ; debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
73 -- Prcess them one by one, dumping results into makefile
74 -- and complaining about cycles
75 ; mapM (processDeps dflags session excl_mods (mkd_tmp_hdl files)) sorted
77 -- If -ddump-mod-cycles, show cycles in the module graph
78 ; dumpModCycles dflags mod_summaries
81 ; endMkDependHS dflags files }}
83 -----------------------------------------------------------------
86 -- Create a temporary file,
88 -- slurp through it, etc
90 -----------------------------------------------------------------
93 = MkDep { mkd_make_file :: FilePath, -- Name of the makefile
94 mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile
95 mkd_tmp_file :: FilePath, -- Name of the temporary file
96 mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
98 beginMkDependHS :: DynFlags -> IO MkDepFiles
99 beginMkDependHS dflags = do
100 -- open a new temp file in which to stuff the dependency info
102 tmp_file <- newTempName dflags "dep"
103 tmp_hdl <- openFile tmp_file WriteMode
106 let makefile = depMakefile dflags
107 exists <- doesFileExist makefile
112 makefile_hdl <- openFile makefile ReadMode
114 -- slurp through until we get the magic start string,
115 -- copying the contents into dep_makefile
117 l <- hGetLine makefile_hdl
118 if (l == depStartMarker)
120 else do hPutStrLn tmp_hdl l; slurp
122 -- slurp through until we get the magic end marker,
123 -- throwing away the contents
125 l <- hGetLine makefile_hdl
126 if (l == depEndMarker)
131 (\e -> if isEOFError e then return () else ioError e)
133 (\e -> if isEOFError e then return () else ioError e)
135 return (Just makefile_hdl)
138 -- write the magic marker into the tmp file
139 hPutStrLn tmp_hdl depStartMarker
141 return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
142 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
145 -----------------------------------------------------------------
149 -----------------------------------------------------------------
151 processDeps :: DynFlags
154 -> Handle -- Write dependencies to here
157 -- Write suitable dependencies to handle
161 -- If the dependency is on something other than a .hi file:
162 -- this.o this.p_o ... : dep
164 -- this.o ... : dep.hi
165 -- this.p_o ... : dep.p_hi
167 -- (where .o is $osuf, and the other suffixes come from
168 -- the cmdline -s options).
170 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
172 processDeps _ _ _ _ (CyclicSCC nodes)
173 = -- There shouldn't be any cycles; report them
174 ghcError (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
176 processDeps dflags session excl_mods hdl (AcyclicSCC node)
177 = do { hsc_env <- GHC.sessionHscEnv session
178 ; let extra_suffixes = depSuffixes dflags
179 include_pkg_deps = depIncludePkgDeps dflags
180 src_file = msHsFilePath node
181 obj_file = msObjFilePath node
182 obj_files = insertSuffixes obj_file extra_suffixes
184 do_imp is_boot imp_mod
185 = do { mb_hi <- findDependency hsc_env src_file imp_mod
186 is_boot include_pkg_deps
188 Nothing -> return () ;
190 { let hi_files = insertSuffixes hi_file extra_suffixes
191 write_dep (obj,hi) = writeDependency hdl [obj] hi
193 -- Add one dependency for each suffix;
196 ; mapM_ write_dep (obj_files `zip` hi_files) }}}
199 -- Emit std dependency of the object(s) on the source file
200 -- Something like A.o : A.hs
201 ; writeDependency hdl obj_files src_file
203 -- Emit a dependency for each import
206 ; mapM_ (do_imp True)
207 (filter (`notElem` excl_mods) (map unLoc (ms_srcimps node)))
210 ; mapM_ (do_imp False)
211 (filter (`notElem` excl_mods) (map unLoc (ms_imps node)))
215 findDependency :: HscEnv
216 -> FilePath -- Importing module: used only for error msg
217 -> ModuleName -- Imported module
218 -> IsBootInterface -- Source import
219 -> Bool -- Record dependency on package modules
220 -> IO (Maybe FilePath) -- Interface file file
221 findDependency hsc_env _ imp is_boot _include_pkg_deps
222 = do { -- Find the module; this will be fast because
223 -- we've done it once during downsweep
224 r <- findImportedModule hsc_env imp Nothing
227 -- Home package: just depend on the .hi or hi-boot file
228 | isJust (ml_hs_file loc)
229 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
231 -- Not in this package: we don't need a dependency
235 _ -> panic "findDependency"
238 -----------------------------
239 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
240 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
242 writeDependency hdl targets dep
243 = hPutStrLn hdl (unwords (map forOutput targets) ++ " : " ++ forOutput dep)
244 where forOutput = escapeSpaces . reslash Forwards . normalise
246 -----------------------------
248 :: FilePath -- Original filename; e.g. "foo.o"
249 -> [String] -- Extra suffices e.g. ["x","y"]
250 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
251 -- Note that that the extra bit gets inserted *before* the old suffix
252 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
254 -- NOTE: we used to have this comment
255 -- In order to construct hi files with alternate suffixes, we
256 -- now have to find the "basename" of the hi file. This is
257 -- difficult because we can't just split the hi filename
258 -- at the last dot - the hisuf might have dots in it. So we
259 -- check whether the hi filename ends in hisuf, and if it does,
260 -- we strip off hisuf, otherwise we strip everything after the
262 -- But I'm not sure we care about hisufs with dots in them.
263 -- Lots of other things will break first!
265 insertSuffixes file_name extras
266 = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ]
268 (basename, suffix) = case splitExtension file_name of
269 -- Drop the "." from the extension
270 (b, s) -> (b, drop 1 s)
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
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
371 = case [m | L _ m <- lms, m `elem` cycle_mods] of
373 ms -> what <+> ptext (sLit "imports") <+>
376 -----------------------------------------------------------------
380 -----------------------------------------------------------------
382 depStartMarker, depEndMarker :: String
383 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
384 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"