First step for getting rid of the old -optdep flags
[ghc-hetmet.git] / compiler / main / DriverMkDepend.hs
1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
3
4 -----------------------------------------------------------------------------
5 --
6 -- Makefile Dependency Generation
7 --
8 -- (c) The University of Glasgow 2005
9 --
10 -----------------------------------------------------------------------------
11
12 module DriverMkDepend (
13         doMkDependHS
14   ) where
15
16 #include "HsVersions.h"
17
18 import qualified GHC
19 import GHC              ( Session, ModSummary(..) )
20 import DynFlags
21 import Util
22 import HscTypes         ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath )
23 import SysTools         ( newTempName )
24 import qualified SysTools
25 import Module
26 import Digraph          ( SCC(..) )
27 import Finder           ( findImportedModule, FindResult(..) )
28 import Outputable
29 import Panic
30 import SrcLoc
31 import Data.List
32 import FastString
33
34 import ErrUtils         ( debugTraceMsg, putMsg )
35
36 import Control.Exception
37 import System.Exit      ( ExitCode(..), exitWith )
38 import System.Directory
39 import System.FilePath
40 import System.IO
41 import System.IO.Error  ( isEOFError )
42 import Control.Monad    ( when )
43 import Data.Maybe       ( isJust )
44
45 -----------------------------------------------------------------
46 --
47 --              The main function
48 --
49 -----------------------------------------------------------------
50
51 doMkDependHS :: Session -> [FilePath] -> IO ()
52 doMkDependHS session srcs
53   = do  {       -- Initialisation
54           dflags <- GHC.getSessionDynFlags session
55         ; files <- beginMkDependHS dflags
56
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 -}
62         ; case r of
63             Nothing -> exitWith (ExitFailure 1)
64             Just mod_summaries -> do {
65
66                 -- Sort into dependency order
67                 -- There should be no cycles
68           let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
69
70                 -- Print out the dependencies if wanted
71         ; debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted)
72
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
76
77                 -- If -ddump-mod-cycles, show cycles in the module graph
78         ; dumpModCycles dflags mod_summaries
79
80                 -- Tidy up
81         ; endMkDependHS dflags files }}
82
83 -----------------------------------------------------------------
84 --
85 --              beginMkDependHs
86 --      Create a temporary file,
87 --      find the Makefile,
88 --      slurp through it, etc
89 --
90 -----------------------------------------------------------------
91
92 data MkDepFiles
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
97
98 beginMkDependHS :: DynFlags -> IO MkDepFiles
99 beginMkDependHS dflags = do
100         -- open a new temp file in which to stuff the dependency info
101         -- as we go along.
102   tmp_file <- newTempName dflags "dep"
103   tmp_hdl <- openFile tmp_file WriteMode
104
105         -- open the makefile
106   let makefile = depMakefile dflags
107   exists <- doesFileExist makefile
108   mb_make_hdl <-
109         if not exists
110         then return Nothing
111         else do
112            makefile_hdl <- openFile makefile ReadMode
113
114                 -- slurp through until we get the magic start string,
115                 -- copying the contents into dep_makefile
116            let slurp = do
117                 l <- hGetLine makefile_hdl
118                 if (l == depStartMarker)
119                         then return ()
120                         else do hPutStrLn tmp_hdl l; slurp
121
122                 -- slurp through until we get the magic end marker,
123                 -- throwing away the contents
124            let chuck = do
125                 l <- hGetLine makefile_hdl
126                 if (l == depEndMarker)
127                         then return ()
128                         else chuck
129
130            catchJust ioErrors slurp
131                 (\e -> if isEOFError e then return () else ioError e)
132            catchJust ioErrors chuck
133                 (\e -> if isEOFError e then return () else ioError e)
134
135            return (Just makefile_hdl)
136
137
138         -- write the magic marker into the tmp file
139   hPutStrLn tmp_hdl depStartMarker
140
141   return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
142                   mkd_tmp_file  = tmp_file, mkd_tmp_hdl  = tmp_hdl})
143
144
145 -----------------------------------------------------------------
146 --
147 --              processDeps
148 --
149 -----------------------------------------------------------------
150
151 processDeps :: DynFlags
152             -> Session
153             -> [ModuleName]
154             -> Handle           -- Write dependencies to here
155             -> SCC ModSummary
156             -> IO ()
157 -- Write suitable dependencies to handle
158 -- Always:
159 --                      this.o : this.hs
160 --
161 -- If the dependency is on something other than a .hi file:
162 --                      this.o this.p_o ... : dep
163 -- otherwise
164 --                      this.o ...   : dep.hi
165 --                      this.p_o ... : dep.p_hi
166 --                      ...
167 -- (where .o is $osuf, and the other suffixes come from
168 -- the cmdline -s options).
169 --
170 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
171
172 processDeps _ _ _ _ (CyclicSCC nodes)
173   =     -- There shouldn't be any cycles; report them
174     throwDyn (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
175
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
183
184               do_imp is_boot imp_mod
185                 = do { mb_hi <- findDependency hsc_env src_file imp_mod
186                                                is_boot include_pkg_deps
187                      ; case mb_hi of {
188                            Nothing      -> return () ;
189                            Just hi_file -> do
190                      { let hi_files = insertSuffixes hi_file extra_suffixes
191                            write_dep (obj,hi) = writeDependency hdl [obj] hi
192
193                         -- Add one dependency for each suffix;
194                         -- e.g.         A.o   : B.hi
195                         --              A.x_o : B.x_hi
196                      ; mapM_ write_dep (obj_files `zip` hi_files) }}}
197
198
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
202
203                 -- Emit a dependency for each import
204
205         -- SOURCE imports
206         ; mapM_ (do_imp True)
207                 (filter (`notElem` excl_mods) (map unLoc (ms_srcimps node)))
208
209         -- regular imports
210         ; mapM_ (do_imp False)
211                 (filter (`notElem` excl_mods) (map unLoc (ms_imps node)))
212         }
213
214
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
225         ; case r of
226             Found loc _
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)))
230
231                 -- Not in this package: we don't need a dependency
232                 | otherwise
233                 -> return Nothing
234
235             _ -> panic "findDependency"
236         }
237
238 -----------------------------
239 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
240 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
241 --      t1 t2 : dep
242 writeDependency hdl targets dep
243   = hPutStrLn hdl (unwords (map forOutput targets) ++ " : " ++ forOutput dep)
244     where forOutput = escapeSpaces . reslash Forwards . normalise
245
246 -----------------------------
247 insertSuffixes
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
253
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
261                 -- last dot.
262         -- But I'm not sure we care about hisufs with dots in them.
263         -- Lots of other things will break first!
264
265 insertSuffixes file_name extras
266   = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ]
267   where
268     (basename, suffix) = case splitExtension file_name of
269                          -- Drop the "." from the extension
270                          (b, s) -> (b, drop 1 s)
271
272
273 -----------------------------------------------------------------
274 --
275 --              endMkDependHs
276 --      Complete the makefile, close the tmp file etc
277 --
278 -----------------------------------------------------------------
279
280 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
281
282 endMkDependHS dflags
283    (MkDep { mkd_make_file = makefile, mkd_make_hdl =  makefile_hdl,
284             mkd_tmp_file  = tmp_file, mkd_tmp_hdl  =  tmp_hdl })
285   = do
286   -- write the magic marker into the tmp file
287   hPutStrLn tmp_hdl depEndMarker
288
289   case makefile_hdl of
290      Nothing  -> return ()
291      Just hdl -> do
292
293           -- slurp the rest of the original makefile and copy it into the output
294         let slurp = do
295                 l <- hGetLine hdl
296                 hPutStrLn tmp_hdl l
297                 slurp
298
299         catchJust ioErrors slurp
300                 (\e -> if isEOFError e then return () else ioError e)
301
302         hClose hdl
303
304   hClose tmp_hdl  -- make sure it's flushed
305
306         -- Create a backup of the original makefile
307   when (isJust makefile_hdl)
308        (SysTools.copy dflags ("Backing up " ++ makefile)
309           makefile (makefile++".bak"))
310
311         -- Copy the new makefile in place
312   SysTools.copy dflags "Installing new makefile" tmp_file makefile
313
314
315 -----------------------------------------------------------------
316 --              Module cycles
317 -----------------------------------------------------------------
318
319 dumpModCycles :: DynFlags -> [ModSummary] -> IO ()
320 dumpModCycles dflags mod_summaries
321   | not (dopt Opt_D_dump_mod_cycles dflags)
322   = return ()
323
324   | null cycles
325   = putMsg dflags (ptext (sLit "No module cycles"))
326
327   | otherwise
328   = putMsg dflags (hang (ptext (sLit "Module cycles found:")) 2 pp_cycles)
329   where
330
331     cycles :: [[ModSummary]]
332     cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ]
333
334     pp_cycles = vcat [ (ptext (sLit "---------- Cycle") <+> int n <+> ptext (sLit "----------"))
335                         $$ pprCycle c $$ text ""
336                      | (n,c) <- [1..] `zip` cycles ]
337
338 pprCycle :: [ModSummary] -> SDoc
339 -- Print a cycle, but show only the imports within the cycle
340 pprCycle summaries = pp_group (CyclicSCC summaries)
341   where
342     cycle_mods :: [ModuleName]  -- The modules in this cycle
343     cycle_mods = map (moduleName . ms_mod) summaries
344
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)
352         where
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
357
358           loop_breaker = head boot_only
359           all_others   = tail boot_only ++ others
360           groups = GHC.topSortModuleGraph True all_others Nothing
361
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))
365         where
366           mod_str = moduleNameString (moduleName (ms_mod summary))
367
368     pp_imps :: SDoc -> [Located ModuleName] -> SDoc
369     pp_imps _    [] = empty
370     pp_imps what lms
371         = case [m | L _ m <- lms, m `elem` cycle_mods] of
372             [] -> empty
373             ms -> what <+> ptext (sLit "imports") <+>
374                                 pprWithCommas ppr ms
375
376 -----------------------------------------------------------------
377 --
378 --              Flags
379 --
380 -----------------------------------------------------------------
381
382 depStartMarker, depEndMarker :: String
383 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
384 depEndMarker   = "# DO NOT DELETE: End of Haskell dependencies"
385