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