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(..) )
25 import SysTools ( newTempName )
26 import qualified SysTools
28 import Digraph ( SCC(..) )
38 import MonadUtils ( liftIO )
40 import System.Directory
41 import System.FilePath
43 import System.IO.Error ( isEOFError )
44 import Control.Monad ( when )
45 import Data.Maybe ( isJust )
47 -----------------------------------------------------------------
51 -----------------------------------------------------------------
53 doMkDependHS :: GhcMonad m => [FilePath] -> m ()
54 doMkDependHS srcs = do
56 dflags <- GHC.getSessionDynFlags
57 files <- liftIO $ beginMkDependHS dflags
59 -- Do the downsweep to find all the modules
60 targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
61 GHC.setTargets targets
62 let excl_mods = depExcludeMods dflags
63 mod_summaries <- GHC.depanal excl_mods True {- Allow dup roots -}
65 -- Sort into dependency order
66 -- There should be no cycles
67 let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
69 -- Print out the dependencies if wanted
70 liftIO $ debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
72 -- Prcess them one by one, dumping results into makefile
73 -- and complaining about cycles
75 mapM (liftIO . processDeps dflags hsc_env excl_mods (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
161 -> Handle -- Write dependencies to here
164 -- Write suitable dependencies to handle
168 -- If the dependency is on something other than a .hi file:
169 -- this.o this.p_o ... : dep
171 -- this.o ... : dep.hi
172 -- this.p_o ... : dep.p_hi
174 -- (where .o is $osuf, and the other suffixes come from
175 -- the cmdline -s options).
177 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
179 processDeps _ _ _ _ (CyclicSCC nodes)
180 = -- There shouldn't be any cycles; report them
181 ghcError (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
183 processDeps dflags hsc_env excl_mods hdl (AcyclicSCC node)
184 = do { let extra_suffixes = depSuffixes dflags
185 include_pkg_deps = depIncludePkgDeps dflags
186 src_file = msHsFilePath node
187 obj_file = msObjFilePath node
188 obj_files = insertSuffixes obj_file extra_suffixes
190 do_imp loc is_boot pkg_qual imp_mod
191 = do { mb_hi <- findDependency hsc_env loc pkg_qual imp_mod
192 is_boot include_pkg_deps
194 Nothing -> return () ;
196 { let hi_files = insertSuffixes hi_file extra_suffixes
197 write_dep (obj,hi) = writeDependency hdl [obj] hi
199 -- Add one dependency for each suffix;
202 ; mapM_ write_dep (obj_files `zip` hi_files) }}}
205 -- Emit std dependency of the object(s) on the source file
206 -- Something like A.o : A.hs
207 ; writeDependency hdl obj_files src_file
209 -- Emit a dependency for each import
211 ; let do_imps is_boot idecls = sequence_
212 [ do_imp loc is_boot (ideclPkgQual i) mod
214 let mod = unLoc (ideclName i),
215 mod `notElem` excl_mods ]
217 ; do_imps True (ms_srcimps node)
218 ; do_imps False (ms_imps node)
220 ; when (dopt Opt_ImplicitPrelude (ms_hspp_opts node)) $
221 do_imp noSrcSpan False Nothing pRELUDE_NAME
225 findDependency :: HscEnv
227 -> Maybe FastString -- package qualifier, if any
228 -> ModuleName -- Imported module
229 -> IsBootInterface -- Source import
230 -> Bool -- Record dependency on package modules
231 -> IO (Maybe FilePath) -- Interface file file
232 findDependency hsc_env srcloc pkg imp is_boot include_pkg_deps
233 = do { -- Find the module; this will be fast because
234 -- we've done it once during downsweep
235 r <- findImportedModule hsc_env imp pkg
238 -- Home package: just depend on the .hi or hi-boot file
239 | isJust (ml_hs_file loc) || include_pkg_deps
240 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
242 -- Not in this package: we don't need a dependency
246 fail -> throwOneError $ mkPlainErrMsg srcloc $
247 cannotFindModule (hsc_dflags hsc_env) imp fail
250 -----------------------------
251 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
252 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
254 writeDependency hdl targets dep
255 = hPutStrLn hdl (unwords (map forOutput targets) ++ " : " ++ forOutput dep)
256 where forOutput = escapeSpaces . reslash Forwards . normalise
258 -----------------------------
260 :: FilePath -- Original filename; e.g. "foo.o"
261 -> [String] -- Extra suffices e.g. ["x","y"]
262 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
263 -- Note that that the extra bit gets inserted *before* the old suffix
264 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
266 -- NOTE: we used to have this comment
267 -- In order to construct hi files with alternate suffixes, we
268 -- now have to find the "basename" of the hi file. This is
269 -- difficult because we can't just split the hi filename
270 -- at the last dot - the hisuf might have dots in it. So we
271 -- check whether the hi filename ends in hisuf, and if it does,
272 -- we strip off hisuf, otherwise we strip everything after the
274 -- But I'm not sure we care about hisufs with dots in them.
275 -- Lots of other things will break first!
277 insertSuffixes file_name extras
278 = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ]
280 (basename, suffix) = case splitExtension file_name of
281 -- Drop the "." from the extension
282 (b, s) -> (b, drop 1 s)
285 -----------------------------------------------------------------
288 -- Complete the makefile, close the tmp file etc
290 -----------------------------------------------------------------
292 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
295 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
296 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
298 -- write the magic marker into the tmp file
299 hPutStrLn tmp_hdl depEndMarker
305 -- slurp the rest of the original makefile and copy it into the output
312 (\e -> if isEOFError e then return () else ioError e)
316 hClose tmp_hdl -- make sure it's flushed
318 -- Create a backup of the original makefile
319 when (isJust makefile_hdl)
320 (SysTools.copy dflags ("Backing up " ++ makefile)
321 makefile (makefile++".bak"))
323 -- Copy the new makefile in place
324 SysTools.copy dflags "Installing new makefile" tmp_file makefile
327 -----------------------------------------------------------------
329 -----------------------------------------------------------------
331 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
332 dumpModCycles dflags mod_summaries
333 | not (dopt Opt_D_dump_mod_cycles dflags)
337 = putMsg dflags (ptext (sLit "No module cycles"))
340 = putMsg dflags (hang (ptext (sLit "Module cycles found:")) 2 pp_cycles)
343 cycles :: [[ModSummary]]
344 cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
346 pp_cycles = vcat [ (ptext (sLit "---------- Cycle") <+> int n <+> ptext (sLit "----------"))
347 $$ pprCycle c $$ text ""
348 | (n,c) <- [1..] `zip` cycles ]
350 pprCycle :: [ModSummary] -> SDoc
351 -- Print a cycle, but show only the imports within the cycle
352 pprCycle summaries = pp_group (CyclicSCC summaries)
354 cycle_mods :: [ModuleName] -- The modules in this cycle
355 cycle_mods = map (moduleName . ms_mod) summaries
357 pp_group (AcyclicSCC ms) = pp_ms ms
358 pp_group (CyclicSCC mss)
359 = ASSERT( not (null boot_only) )
360 -- The boot-only list must be non-empty, else there would
361 -- be an infinite chain of non-boot imoprts, and we've
362 -- already checked for that in processModDeps
363 pp_ms loop_breaker $$ vcat (map pp_group groups)
365 (boot_only, others) = partition is_boot_only mss
366 is_boot_only ms = not (any in_group (map (ideclName.unLoc) (ms_imps ms)))
367 in_group (L _ m) = m `elem` group_mods
368 group_mods = map (moduleName . ms_mod) mss
370 loop_breaker = head boot_only
371 all_others = tail boot_only ++ others
372 groups = GHC.topSortModuleGraph True all_others Nothing
374 pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
375 <+> (pp_imps empty (map (ideclName.unLoc) (ms_imps summary)) $$
376 pp_imps (ptext (sLit "{-# SOURCE #-}")) (map (ideclName.unLoc) (ms_srcimps summary)))
378 mod_str = moduleNameString (moduleName (ms_mod summary))
380 pp_imps :: SDoc -> [Located ModuleName] -> SDoc
383 = case [m | L _ m <- lms, m `elem` cycle_mods] of
385 ms -> what <+> ptext (sLit "imports") <+>
388 -----------------------------------------------------------------
392 -----------------------------------------------------------------
394 depStartMarker, depEndMarker :: String
395 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
396 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"