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"
20 import HsSyn ( ImportDecl(..) )
24 import SysTools ( newTempName )
25 import qualified SysTools
27 import Digraph ( SCC(..) )
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 :: GhcMonad m => [FilePath] -> m ()
52 doMkDependHS srcs = do
54 dflags <- GHC.getSessionDynFlags
55 files <- liftIO $ beginMkDependHS dflags
57 -- Do the downsweep to find all the modules
58 targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
59 GHC.setTargets targets
60 let excl_mods = depExcludeMods dflags
61 mod_summaries <- GHC.depanal excl_mods True {- Allow dup roots -}
63 -- Sort into dependency order
64 -- There should be no cycles
65 let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
67 -- Print out the dependencies if wanted
68 liftIO $ debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
70 -- Prcess them one by one, dumping results into makefile
71 -- and complaining about cycles
73 root <- liftIO getCurrentDirectory
74 mapM_ (liftIO . processDeps dflags hsc_env excl_mods root (mkd_tmp_hdl files)) sorted
76 -- If -ddump-mod-cycles, show cycles in the module graph
77 liftIO $ dumpModCycles dflags mod_summaries
80 liftIO $ endMkDependHS dflags files
82 -- Unconditional exiting is a bad idea. If an error occurs we'll get an
83 --exception; if that is not caught it's fine, but at least we have a
84 --chance to find out exactly what went wrong. Uncomment the following
85 --line if you disagree.
87 --`GHC.ghcCatch` \_ -> io $ exitWith (ExitFailure 1)
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
105 beginMkDependHS dflags = do
106 -- open a new temp file in which to stuff the dependency info
108 tmp_file <- newTempName dflags "dep"
109 tmp_hdl <- openFile tmp_file WriteMode
112 let makefile = depMakefile dflags
113 exists <- doesFileExist makefile
118 makefile_hdl <- openFile makefile ReadMode
120 -- slurp through until we get the magic start string,
121 -- copying the contents into dep_makefile
123 l <- hGetLine makefile_hdl
124 if (l == depStartMarker)
126 else do hPutStrLn tmp_hdl l; slurp
128 -- slurp through until we get the magic end marker,
129 -- throwing away the contents
131 l <- hGetLine makefile_hdl
132 if (l == depEndMarker)
137 (\e -> if isEOFError e then return () else ioError e)
139 (\e -> if isEOFError e then return () else ioError e)
141 return (Just makefile_hdl)
144 -- write the magic marker into the tmp file
145 hPutStrLn tmp_hdl depStartMarker
147 return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
148 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
151 -----------------------------------------------------------------
155 -----------------------------------------------------------------
157 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 root 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 root 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 root 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)
222 findDependency :: HscEnv
224 -> Maybe FastString -- package qualifier, if any
225 -> ModuleName -- Imported module
226 -> IsBootInterface -- Source import
227 -> Bool -- Record dependency on package modules
228 -> IO (Maybe FilePath) -- Interface file file
229 findDependency hsc_env srcloc pkg imp is_boot include_pkg_deps
230 = do { -- Find the module; this will be fast because
231 -- we've done it once during downsweep
232 r <- findImportedModule hsc_env imp pkg
235 -- Home package: just depend on the .hi or hi-boot file
236 | isJust (ml_hs_file loc) || include_pkg_deps
237 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
239 -- Not in this package: we don't need a dependency
243 fail -> throwOneError $ mkPlainErrMsg srcloc $
244 cannotFindModule (hsc_dflags hsc_env) imp fail
247 -----------------------------
248 writeDependency :: FilePath -> Handle -> [FilePath] -> FilePath -> IO ()
249 -- (writeDependency r h [t1,t2] dep) writes to handle h the dependency
251 writeDependency root hdl targets dep
252 = do let -- We need to avoid making deps on
254 -- on cygwin as make gets confused by the :
255 -- Making relative deps avoids some instances of this.
256 dep' = makeRelative root dep
257 forOutput = escapeSpaces . reslash Forwards . normalise
258 output = unwords (map forOutput targets) ++ " : " ++ forOutput dep'
261 -----------------------------
263 :: FilePath -- Original filename; e.g. "foo.o"
264 -> [String] -- Extra suffices e.g. ["x","y"]
265 -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"]
266 -- Note that that the extra bit gets inserted *before* the old suffix
267 -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
269 -- NOTE: we used to have this comment
270 -- In order to construct hi files with alternate suffixes, we
271 -- now have to find the "basename" of the hi file. This is
272 -- difficult because we can't just split the hi filename
273 -- at the last dot - the hisuf might have dots in it. So we
274 -- check whether the hi filename ends in hisuf, and if it does,
275 -- we strip off hisuf, otherwise we strip everything after the
277 -- But I'm not sure we care about hisufs with dots in them.
278 -- Lots of other things will break first!
280 insertSuffixes file_name extras
281 = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ]
283 (basename, suffix) = case splitExtension file_name of
284 -- Drop the "." from the extension
285 (b, s) -> (b, drop 1 s)
288 -----------------------------------------------------------------
291 -- Complete the makefile, close the tmp file etc
293 -----------------------------------------------------------------
295 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
298 (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl,
299 mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl })
301 -- write the magic marker into the tmp file
302 hPutStrLn tmp_hdl depEndMarker
308 -- slurp the rest of the original makefile and copy it into the output
315 (\e -> if isEOFError e then return () else ioError e)
319 hClose tmp_hdl -- make sure it's flushed
321 -- Create a backup of the original makefile
322 when (isJust makefile_hdl)
323 (SysTools.copy dflags ("Backing up " ++ makefile)
324 makefile (makefile++".bak"))
326 -- Copy the new makefile in place
327 SysTools.copy dflags "Installing new makefile" tmp_file makefile
330 -----------------------------------------------------------------
332 -----------------------------------------------------------------
334 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
335 dumpModCycles dflags mod_summaries
336 | not (dopt Opt_D_dump_mod_cycles dflags)
340 = putMsg dflags (ptext (sLit "No module cycles"))
343 = putMsg dflags (hang (ptext (sLit "Module cycles found:")) 2 pp_cycles)
346 cycles :: [[ModSummary]]
347 cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
349 pp_cycles = vcat [ (ptext (sLit "---------- Cycle") <+> int n <+> ptext (sLit "----------"))
350 $$ pprCycle c $$ blankLine
351 | (n,c) <- [1..] `zip` cycles ]
353 pprCycle :: [ModSummary] -> SDoc
354 -- Print a cycle, but show only the imports within the cycle
355 pprCycle summaries = pp_group (CyclicSCC summaries)
357 cycle_mods :: [ModuleName] -- The modules in this cycle
358 cycle_mods = map (moduleName . ms_mod) summaries
360 pp_group (AcyclicSCC ms) = pp_ms ms
361 pp_group (CyclicSCC mss)
362 = ASSERT( not (null boot_only) )
363 -- The boot-only list must be non-empty, else there would
364 -- be an infinite chain of non-boot imoprts, and we've
365 -- already checked for that in processModDeps
366 pp_ms loop_breaker $$ vcat (map pp_group groups)
368 (boot_only, others) = partition is_boot_only mss
369 is_boot_only ms = not (any in_group (map (ideclName.unLoc) (ms_imps ms)))
370 in_group (L _ m) = m `elem` group_mods
371 group_mods = map (moduleName . ms_mod) mss
373 loop_breaker = head boot_only
374 all_others = tail boot_only ++ others
375 groups = GHC.topSortModuleGraph True all_others Nothing
377 pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
378 <+> (pp_imps empty (map (ideclName.unLoc) (ms_imps summary)) $$
379 pp_imps (ptext (sLit "{-# SOURCE #-}")) (map (ideclName.unLoc) (ms_srcimps summary)))
381 mod_str = moduleNameString (moduleName (ms_mod summary))
383 pp_imps :: SDoc -> [Located ModuleName] -> SDoc
386 = case [m | L _ m <- lms, m `elem` cycle_mods] of
388 ms -> what <+> ptext (sLit "imports") <+>
391 -----------------------------------------------------------------
395 -----------------------------------------------------------------
397 depStartMarker, depEndMarker :: String
398 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
399 depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"