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 ( ModSummary(..), GhcMonad )
20 import HsSyn ( ImportDecl(..) )
24 import SysTools ( newTempName )
25 import qualified SysTools
27 import Digraph ( SCC(..) )
37 -- import MonadUtils ( liftIO )
39 import System.Directory
40 import System.FilePath
42 import System.IO.Error ( isEOFError )
43 import Control.Monad ( when )
44 import Data.Maybe ( isJust )
46 -----------------------------------------------------------------
50 -----------------------------------------------------------------
52 doMkDependHS :: GhcMonad m => [FilePath] -> m ()
53 doMkDependHS srcs = do
55 dflags <- GHC.getSessionDynFlags
56 files <- liftIO $ beginMkDependHS dflags
58 -- Do the downsweep to find all the modules
59 targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
60 GHC.setTargets targets
61 let excl_mods = depExcludeMods dflags
62 mod_summaries <- GHC.depanal excl_mods True {- Allow dup roots -}
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 liftIO $ debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
71 -- Prcess them one by one, dumping results into makefile
72 -- and complaining about cycles
74 root <- liftIO getCurrentDirectory
75 mapM_ (liftIO . processDeps dflags hsc_env excl_mods root (mkd_tmp_hdl files)) sorted
77 -- If -ddump-mod-cycles, show cycles in the module graph
78 liftIO $ dumpModCycles dflags mod_summaries
81 liftIO $ endMkDependHS dflags files
83 -- Unconditional exiting is a bad idea. If an error occurs we'll get an
84 --exception; if that is not caught it's fine, but at least we have a
85 --chance to find out exactly what went wrong. Uncomment the following
86 --line if you disagree.
88 --`GHC.ghcCatch` \_ -> io $ exitWith (ExitFailure 1)
90 -----------------------------------------------------------------
93 -- Create a temporary file,
95 -- slurp through it, etc
97 -----------------------------------------------------------------
100 = MkDep { mkd_make_file :: FilePath, -- Name of the makefile
101 mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile
102 mkd_tmp_file :: FilePath, -- Name of the temporary file
103 mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
105 beginMkDependHS :: DynFlags -> IO MkDepFiles
106 beginMkDependHS dflags = do
107 -- open a new temp file in which to stuff the dependency info
109 tmp_file <- newTempName dflags "dep"
110 tmp_hdl <- openFile tmp_file WriteMode
113 let makefile = depMakefile dflags
114 exists <- doesFileExist makefile
119 makefile_hdl <- openFile makefile ReadMode
121 -- slurp through until we get the magic start string,
122 -- copying the contents into dep_makefile
124 l <- hGetLine makefile_hdl
125 if (l == depStartMarker)
127 else do hPutStrLn tmp_hdl l; slurp
129 -- slurp through until we get the magic end marker,
130 -- throwing away the contents
132 l <- hGetLine makefile_hdl
133 if (l == depEndMarker)
138 (\e -> if isEOFError e then return () else ioError e)
140 (\e -> if isEOFError e then return () else ioError e)
142 return (Just makefile_hdl)
145 -- write the magic marker into the tmp file
146 hPutStrLn tmp_hdl depStartMarker
148 return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
149 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
152 -----------------------------------------------------------------
156 -----------------------------------------------------------------
158 processDeps :: DynFlags
162 -> Handle -- Write dependencies to here
165 -- Write suitable dependencies to handle
169 -- If the dependency is on something other than a .hi file:
170 -- this.o this.p_o ... : dep
172 -- this.o ... : dep.hi
173 -- this.p_o ... : dep.p_hi
175 -- (where .o is $osuf, and the other suffixes come from
176 -- the cmdline -s options).
178 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
180 processDeps _ _ _ _ _ (CyclicSCC nodes)
181 = -- There shouldn't be any cycles; report them
182 ghcError (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
184 processDeps dflags hsc_env excl_mods root hdl (AcyclicSCC node)
185 = do { let extra_suffixes = depSuffixes dflags
186 include_pkg_deps = depIncludePkgDeps dflags
187 src_file = msHsFilePath node
188 obj_file = msObjFilePath node
189 obj_files = insertSuffixes obj_file extra_suffixes
191 do_imp loc is_boot pkg_qual imp_mod
192 = do { mb_hi <- findDependency hsc_env loc pkg_qual imp_mod
193 is_boot include_pkg_deps
195 Nothing -> return () ;
197 { let hi_files = insertSuffixes hi_file extra_suffixes
198 write_dep (obj,hi) = writeDependency root hdl [obj] hi
200 -- Add one dependency for each suffix;
203 ; mapM_ write_dep (obj_files `zip` hi_files) }}}
206 -- Emit std dependency of the object(s) on the source file
207 -- Something like A.o : A.hs
208 ; writeDependency root hdl obj_files src_file
210 -- Emit a dependency for each import
212 ; let do_imps is_boot idecls = sequence_
213 [ do_imp loc is_boot (ideclPkgQual i) mod
215 let mod = unLoc (ideclName i),
216 mod `notElem` excl_mods ]
218 ; do_imps True (ms_srcimps node)
219 ; do_imps False (ms_imps node)
223 findDependency :: HscEnv
225 -> Maybe FastString -- package qualifier, if any
226 -> ModuleName -- Imported module
227 -> IsBootInterface -- Source import
228 -> Bool -- Record dependency on package modules
229 -> IO (Maybe FilePath) -- Interface file file
230 findDependency hsc_env srcloc pkg imp is_boot include_pkg_deps
231 = do { -- Find the module; this will be fast because
232 -- we've done it once during downsweep
233 r <- findImportedModule hsc_env imp pkg
236 -- Home package: just depend on the .hi or hi-boot file
237 | isJust (ml_hs_file loc) || include_pkg_deps
238 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
240 -- Not in this package: we don't need a dependency
244 fail -> throwOneError $ mkPlainErrMsg srcloc $
245 cannotFindModule (hsc_dflags hsc_env) imp fail
248 -----------------------------
249 writeDependency :: FilePath -> Handle -> [FilePath] -> FilePath -> IO ()
250 -- (writeDependency r h [t1,t2] dep) writes to handle h the dependency
252 writeDependency root hdl targets dep
253 = do let -- We need to avoid making deps on
255 -- on cygwin as make gets confused by the :
256 -- Making relative deps avoids some instances of this.
257 dep' = makeRelative root dep
258 forOutput = escapeSpaces . reslash Forwards . normalise
259 output = unwords (map forOutput targets) ++ " : " ++ forOutput dep'
262 -----------------------------
264 :: FilePath -- Original filename; e.g. "foo.o"
265 -> [String] -- Extra suffices e.g. ["x","y"]
266 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
267 -- Note that that the extra bit gets inserted *before* the old suffix
268 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
270 -- NOTE: we used to have this comment
271 -- In order to construct hi files with alternate suffixes, we
272 -- now have to find the "basename" of the hi file. This is
273 -- difficult because we can't just split the hi filename
274 -- at the last dot - the hisuf might have dots in it. So we
275 -- check whether the hi filename ends in hisuf, and if it does,
276 -- we strip off hisuf, otherwise we strip everything after the
278 -- But I'm not sure we care about hisufs with dots in them.
279 -- Lots of other things will break first!
281 insertSuffixes file_name extras
282 = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ]
284 (basename, suffix) = case splitExtension file_name of
285 -- Drop the "." from the extension
286 (b, s) -> (b, drop 1 s)
289 -----------------------------------------------------------------
292 -- Complete the makefile, close the tmp file etc
294 -----------------------------------------------------------------
296 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
299 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
300 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
302 -- write the magic marker into the tmp file
303 hPutStrLn tmp_hdl depEndMarker
309 -- slurp the rest of the original makefile and copy it into the output
316 (\e -> if isEOFError e then return () else ioError e)
320 hClose tmp_hdl -- make sure it's flushed
322 -- Create a backup of the original makefile
323 when (isJust makefile_hdl)
324 (SysTools.copy dflags ("Backing up " ++ makefile)
325 makefile (makefile++".bak"))
327 -- Copy the new makefile in place
328 SysTools.copy dflags "Installing new makefile" tmp_file makefile
331 -----------------------------------------------------------------
333 -----------------------------------------------------------------
335 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
336 dumpModCycles dflags mod_summaries
337 | not (dopt Opt_D_dump_mod_cycles dflags)
341 = putMsg dflags (ptext (sLit "No module cycles"))
344 = putMsg dflags (hang (ptext (sLit "Module cycles found:")) 2 pp_cycles)
347 cycles :: [[ModSummary]]
348 cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
350 pp_cycles = vcat [ (ptext (sLit "---------- Cycle") <+> int n <+> ptext (sLit "----------"))
351 $$ pprCycle c $$ blankLine
352 | (n,c) <- [1..] `zip` cycles ]
354 pprCycle :: [ModSummary] -> SDoc
355 -- Print a cycle, but show only the imports within the cycle
356 pprCycle summaries = pp_group (CyclicSCC summaries)
358 cycle_mods :: [ModuleName] -- The modules in this cycle
359 cycle_mods = map (moduleName . ms_mod) summaries
361 pp_group (AcyclicSCC ms) = pp_ms ms
362 pp_group (CyclicSCC mss)
363 = ASSERT( not (null boot_only) )
364 -- The boot-only list must be non-empty, else there would
365 -- be an infinite chain of non-boot imoprts, and we've
366 -- already checked for that in processModDeps
367 pp_ms loop_breaker $$ vcat (map pp_group groups)
369 (boot_only, others) = partition is_boot_only mss
370 is_boot_only ms = not (any in_group (map (ideclName.unLoc) (ms_imps ms)))
371 in_group (L _ m) = m `elem` group_mods
372 group_mods = map (moduleName . ms_mod) mss
374 loop_breaker = head boot_only
375 all_others = tail boot_only ++ others
376 groups = GHC.topSortModuleGraph True all_others Nothing
378 pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
379 <+> (pp_imps empty (map (ideclName.unLoc) (ms_imps summary)) $$
380 pp_imps (ptext (sLit "{-# SOURCE #-}")) (map (ideclName.unLoc) (ms_srcimps summary)))
382 mod_str = moduleNameString (moduleName (ms_mod summary))
384 pp_imps :: SDoc -> [Located ModuleName] -> SDoc
387 = case [m | L _ m <- lms, m `elem` cycle_mods] of
389 ms -> what <+> ptext (sLit "imports") <+>
392 -----------------------------------------------------------------
396 -----------------------------------------------------------------
398 depStartMarker, depEndMarker :: String
399 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
400 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"