Add -ddump-mod-cycles to -M behaviour
[ghc-hetmet.git] / compiler / main / DriverMkDepend.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Makefile Dependency Generation
4 --
5 -- (c) The University of Glasgow 2005
6 --
7 -----------------------------------------------------------------------------
8
9 module DriverMkDepend (
10         doMkDependHS
11   ) where
12
13 #include "HsVersions.h"
14
15 import qualified GHC
16 import GHC              ( Session, ModSummary(..) )
17 import DynFlags
18 import Util             ( escapeSpaces, splitFilename, joinFileExt )
19 import HscTypes         ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath )
20 import SysTools         ( newTempName )
21 import qualified SysTools
22 import Module
23 import Digraph          ( SCC(..) )
24 import Finder           ( findImportedModule, FindResult(..) )
25 import Util             ( global, consIORef )
26 import Outputable
27 import Panic
28 import SrcLoc
29 import Data.List
30 import CmdLineParser
31
32 #if __GLASGOW_HASKELL__ <= 408
33 import Panic            ( catchJust, ioErrors )
34 #endif
35 import ErrUtils         ( debugTraceMsg, putMsg )
36
37 import Data.IORef       ( IORef, readIORef, writeIORef )
38 import Control.Exception
39 import System.Exit      ( ExitCode(..), exitWith )
40 import System.Directory
41 import System.IO
42 import SYSTEM_IO_ERROR  ( isEOFError )
43 import Control.Monad    ( when )
44 import Data.Maybe       ( isJust )
45
46 -----------------------------------------------------------------
47 --
48 --              The main function
49 --
50 -----------------------------------------------------------------
51
52 doMkDependHS :: Session -> [FilePath] -> IO ()
53 doMkDependHS session srcs
54   = do  {       -- Initialisation
55           dflags <- GHC.getSessionDynFlags session
56         ; files <- beginMkDependHS dflags
57
58                 -- Do the downsweep to find all the modules
59         ; targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs
60         ; GHC.setTargets session targets
61         ; excl_mods <- readIORef v_Dep_exclude_mods
62         ; r <- GHC.depanal session excl_mods True {- Allow dup roots -}
63         ; case r of
64             Nothing -> exitWith (ExitFailure 1)
65             Just mod_summaries -> do {
66
67                 -- Sort into dependency order
68                 -- There should be no cycles
69           let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
70
71                 -- Print out the dependencies if wanted
72         ; debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
73
74                 -- Prcess them one by one, dumping results into makefile
75                 -- and complaining about cycles
76         ; mapM (processDeps session excl_mods (mkd_tmp_hdl files)) sorted
77
78                 -- If -ddump-mod-cycles, show cycles in the module graph
79         ; dumpModCycles dflags mod_summaries
80
81                 -- Tidy up
82         ; endMkDependHS dflags files }}
83
84 -----------------------------------------------------------------
85 --
86 --              beginMkDependHs
87 --      Create a temporary file, 
88 --      find the Makefile, 
89 --      slurp through it, etc
90 --
91 -----------------------------------------------------------------
92
93 data MkDepFiles 
94   = MkDep { mkd_make_file :: FilePath,          -- Name of the makefile
95             mkd_make_hdl  :: Maybe Handle,      -- Handle for the open makefile 
96             mkd_tmp_file  :: FilePath,          -- Name of the temporary file
97             mkd_tmp_hdl   :: Handle }           -- Handle of the open temporary file
98
99 beginMkDependHS :: DynFlags -> IO MkDepFiles
100         
101 beginMkDependHS dflags = do
102         -- slurp in the mkdependHS-style options
103   let flags = getOpts dflags opt_dep
104   _ <- processArgs dep_opts flags
105
106         -- open a new temp file in which to stuff the dependency info
107         -- as we go along.
108   tmp_file <- newTempName dflags "dep"
109   tmp_hdl <- openFile tmp_file WriteMode
110
111         -- open the makefile
112   makefile <- readIORef v_Dep_makefile
113   exists <- doesFileExist makefile
114   mb_make_hdl <- 
115         if not exists
116         then return Nothing
117         else do
118            makefile_hdl <- openFile makefile ReadMode
119
120                 -- slurp through until we get the magic start string,
121                 -- copying the contents into dep_makefile
122            let slurp = do
123                 l <- hGetLine makefile_hdl
124                 if (l == depStartMarker)
125                         then return ()
126                         else do hPutStrLn tmp_hdl l; slurp
127          
128                 -- slurp through until we get the magic end marker,
129                 -- throwing away the contents
130            let chuck = do
131                 l <- hGetLine makefile_hdl
132                 if (l == depEndMarker)
133                         then return ()
134                         else chuck
135          
136            catchJust ioErrors slurp 
137                 (\e -> if isEOFError e then return () else ioError e)
138            catchJust ioErrors chuck
139                 (\e -> if isEOFError e then return () else ioError e)
140
141            return (Just makefile_hdl)
142
143
144         -- write the magic marker into the tmp file
145   hPutStrLn tmp_hdl depStartMarker
146
147   return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl, 
148                   mkd_tmp_file  = tmp_file, mkd_tmp_hdl  = tmp_hdl})
149
150
151 -----------------------------------------------------------------
152 --
153 --              processDeps
154 --
155 -----------------------------------------------------------------
156
157 processDeps :: Session
158             -> [ModuleName]
159             -> Handle           -- Write dependencies to here
160             -> SCC ModSummary
161             -> IO ()
162 -- Write suitable dependencies to handle
163 -- Always:
164 --                      this.o : this.hs
165 --
166 -- If the dependency is on something other than a .hi file:
167 --                      this.o this.p_o ... : dep
168 -- otherwise
169 --                      this.o ...   : dep.hi
170 --                      this.p_o ... : dep.p_hi
171 --                      ...
172 -- (where .o is $osuf, and the other suffixes come from
173 -- the cmdline -s options).
174 --
175 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
176
177 processDeps session excl_mods hdl (CyclicSCC nodes)
178   =     -- There shouldn't be any cycles; report them   
179     throwDyn (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
180
181 processDeps session excl_mods hdl (AcyclicSCC node)
182   = do  { extra_suffixes   <- readIORef v_Dep_suffixes
183         ; hsc_env <- GHC.sessionHscEnv session
184         ; include_pkg_deps <- readIORef v_Dep_include_pkg_deps
185         ; let src_file  = msHsFilePath node
186               obj_file  = msObjFilePath node
187               obj_files = insertSuffixes obj_file extra_suffixes
188
189               do_imp is_boot imp_mod
190                 = do { mb_hi <- findDependency hsc_env src_file imp_mod 
191                                                is_boot include_pkg_deps
192                      ; case mb_hi of {
193                            Nothing      -> return () ;
194                            Just hi_file -> do
195                      { let hi_files = insertSuffixes hi_file extra_suffixes
196                            write_dep (obj,hi) = writeDependency hdl [obj] hi
197
198                         -- Add one dependency for each suffix; 
199                         -- e.g.         A.o   : B.hi
200                         --              A.x_o : B.x_hi
201                      ; mapM_ write_dep (obj_files `zip` hi_files) }}}
202
203              
204                 -- Emit std dependency of the object(s) on the source file
205                 -- Something like       A.o : A.hs
206         ; writeDependency hdl obj_files src_file
207
208                 -- Emit a dependency for each import
209
210         -- SOURCE imports
211         ; mapM_ (do_imp True)  
212                 (filter (`notElem` excl_mods) (map unLoc (ms_srcimps node)))
213
214         -- regular imports
215         ; mapM_ (do_imp False)
216                 (filter (`notElem` excl_mods) (map unLoc (ms_imps node)))
217         }
218
219
220 findDependency  :: HscEnv
221                 -> FilePath             -- Importing module: used only for error msg
222                 -> ModuleName           -- Imported module
223                 -> IsBootInterface      -- Source import
224                 -> Bool                 -- Record dependency on package modules
225                 -> IO (Maybe FilePath)  -- Interface file file
226 findDependency hsc_env src imp is_boot include_pkg_deps
227   = do  {       -- Find the module; this will be fast because
228                 -- we've done it once during downsweep
229           r <- findImportedModule hsc_env imp Nothing
230         ; case r of 
231             Found loc mod
232                 -- Home package: just depend on the .hi or hi-boot file
233                 | isJust (ml_hs_file loc)
234                 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
235
236                 -- Not in this package: we don't need a dependency
237                 | otherwise
238                 -> return Nothing
239
240             _ -> panic "findDependency"
241         }
242
243 -----------------------------
244 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
245 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
246 --      t1 t2 : dep
247 writeDependency hdl targets dep
248   = hPutStrLn hdl (unwords (map escapeSpaces targets) ++ " : "
249                    ++ escapeSpaces dep)
250
251 -----------------------------
252 insertSuffixes  
253         :: FilePath     -- Original filename;   e.g. "foo.o"
254         -> [String]     -- Extra suffices       e.g. ["x","y"]
255         -> [FilePath]   -- Zapped filenames     e.g. ["foo.o", "foo.x_o", "foo.y_o"]
256         -- Note that that the extra bit gets inserted *before* the old suffix
257         -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
258
259         -- NOTE: we used to have this comment
260                 -- In order to construct hi files with alternate suffixes, we
261                 -- now have to find the "basename" of the hi file.  This is
262                 -- difficult because we can't just split the hi filename
263                 -- at the last dot - the hisuf might have dots in it.  So we
264                 -- check whether the hi filename ends in hisuf, and if it does,
265                 -- we strip off hisuf, otherwise we strip everything after the
266                 -- last dot.
267         -- But I'm not sure we care about hisufs with dots in them. 
268         -- Lots of other things will break first!
269
270 insertSuffixes file_name extras
271   = file_name : [ basename `joinFileExt` (extra ++ "_" ++ suffix) | extra <- extras ]
272   where
273     (basename, suffix) = splitFilename file_name
274
275
276 -----------------------------------------------------------------
277 --
278 --              endMkDependHs
279 --      Complete the makefile, close the tmp file etc
280 --
281 -----------------------------------------------------------------
282
283 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
284
285 endMkDependHS dflags 
286    (MkDep { mkd_make_file = makefile, mkd_make_hdl =  makefile_hdl,
287             mkd_tmp_file  = tmp_file, mkd_tmp_hdl  =  tmp_hdl }) 
288   = do
289   -- write the magic marker into the tmp file
290   hPutStrLn tmp_hdl depEndMarker
291
292   case makefile_hdl of
293      Nothing  -> return ()
294      Just hdl -> do
295
296           -- slurp the rest of the original makefile and copy it into the output
297         let slurp = do
298                 l <- hGetLine hdl
299                 hPutStrLn tmp_hdl l
300                 slurp
301          
302         catchJust ioErrors slurp 
303                 (\e -> if isEOFError e then return () else ioError e)
304
305         hClose hdl
306
307   hClose tmp_hdl  -- make sure it's flushed
308
309         -- Create a backup of the original makefile
310   when (isJust makefile_hdl)
311        (SysTools.copy dflags ("Backing up " ++ makefile) 
312           makefile (makefile++".bak"))
313
314         -- Copy the new makefile in place
315   SysTools.copy dflags "Installing new makefile" tmp_file makefile
316
317
318 -----------------------------------------------------------------
319 --              Module cycles
320 -----------------------------------------------------------------
321
322 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
323 dumpModCycles dflags mod_summaries
324   | not (dopt Opt_D_dump_mod_cycles dflags) 
325   = return ()
326
327   | null cycles
328   = putMsg dflags (ptext SLIT("No module cycles"))
329
330   | otherwise
331   = putMsg dflags (hang (ptext SLIT("Module cycles found:")) 2 pp_cycles)
332   where
333
334     cycles :: [[ModSummary]]
335     cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
336
337     pp_cycles = vcat [ (ptext SLIT("---------- Cycle") <+> int n <+> ptext SLIT("----------")) 
338                         $$ pprCycle c $$ text ""
339                      | (n,c) <- [1..] `zip` cycles ]
340
341 pprCycle :: [ModSummary] -> SDoc
342 -- Print a cycle, but show only the imports within the cycle
343 pprCycle summaries = pp_group (CyclicSCC summaries)
344   where
345     cycle_mods :: [ModuleName]  -- The modules in this cycle
346     cycle_mods = map (moduleName . ms_mod) summaries
347
348     pp_group (AcyclicSCC ms) = pp_ms ms
349     pp_group (CyclicSCC mss) 
350         = ASSERT( not (null boot_only) )
351                 -- The boot-only list must be non-empty, else there would
352                 -- be an infinite chain of non-boot imoprts, and we've
353                 -- already checked for that in processModDeps
354           pp_ms loop_breaker $$ vcat (map pp_group groups)
355         where
356           (boot_only, others) = partition is_boot_only mss
357           is_boot_only ms = not (any in_group (ms_imps ms))
358           in_group (L _ m) = m `elem` group_mods
359           group_mods = map (moduleName . ms_mod) mss
360           
361           loop_breaker = head boot_only
362           all_others   = tail boot_only ++ others
363           groups = GHC.topSortModuleGraph True all_others Nothing
364
365     pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' '))
366                        <+> (pp_imps empty (ms_imps summary) $$
367                             pp_imps (ptext SLIT("{-# SOURCE #-}")) (ms_srcimps summary))
368         where
369           mod_str = moduleNameString (moduleName (ms_mod summary))
370
371     pp_imps :: SDoc -> [Located ModuleName] -> SDoc
372     pp_imps what [] = empty
373     pp_imps what lms 
374         = case [m | L _ m <- lms, m `elem` cycle_mods] of
375             [] -> empty
376             ms -> what <+> ptext SLIT("imports") <+> 
377                                 pprWithCommas ppr ms
378
379 -----------------------------------------------------------------
380 --
381 --              Flags
382 --
383 -----------------------------------------------------------------
384
385         -- Flags
386 GLOBAL_VAR(v_Dep_makefile,              "Makefile", String);
387 GLOBAL_VAR(v_Dep_include_pkg_deps,      False, Bool);
388 GLOBAL_VAR(v_Dep_exclude_mods,          [], [ModuleName]);
389 GLOBAL_VAR(v_Dep_suffixes,              [], [String]);
390 GLOBAL_VAR(v_Dep_warnings,              True, Bool);
391
392 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
393 depEndMarker   = "# DO NOT DELETE: End of Haskell dependencies"
394
395 -- for compatibility with the old mkDependHS, we accept options of the form
396 -- -optdep-f -optdep.depend, etc.
397 dep_opts = 
398    [ (  "s",                    SepArg (consIORef v_Dep_suffixes) )
399    , (  "f",                    SepArg (writeIORef v_Dep_makefile) )
400    , (  "w",                    NoArg (writeIORef v_Dep_warnings False) )
401    , (  "-include-prelude",     NoArg (writeIORef v_Dep_include_pkg_deps True) )
402    , (  "-include-pkg-deps",    NoArg (writeIORef v_Dep_include_pkg_deps True) )
403    , (  "-exclude-module=",     Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )
404    , (  "x",                    Prefix (consIORef v_Dep_exclude_mods . mkModuleName) )
405    ]