[project @ 2005-04-05 09:06:36 by krasimir]
[ghc-hetmet.git] / ghc / 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         ( DynFlags( verbosity, opt_dep ), getOpts )
18 import Util             ( escapeSpaces, splitFilename )
19 import HscTypes         ( HscEnv, IsBootInterface, msObjFilePath, msHsFilePath )
20 import Packages         ( PackageIdH(..) )
21 import SysTools         ( newTempName )
22 import qualified SysTools
23 import Module           ( Module, ModLocation(..), mkModule, moduleUserString,
24                           addBootSuffix_maybe )
25 import Digraph          ( SCC(..) )
26 import Finder           ( findModule, FindResult(..) )
27 import Util             ( global, consIORef )
28 import Outputable
29 import Panic
30 import CmdLineParser
31
32 import DATA_IOREF       ( IORef, readIORef, writeIORef )
33 import EXCEPTION
34
35 import Directory
36 import IO
37 import Monad            ( when )
38 import Maybe            ( isJust )
39
40 #if __GLASGOW_HASKELL__ <= 408
41 import Panic            ( catchJust, ioErrors )
42 #endif
43 import ErrUtils         ( debugTraceMsg )
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 GHC.guessTarget srcs
59         ; GHC.setTargets session targets
60         ; excl_mods <- readIORef v_Dep_exclude_mods
61         ; GHC.depanal session excl_mods
62         ; mod_summaries <- GHC.getModuleGraph session
63
64                 -- Sort into dependency order
65                 -- There should be no cycles
66         ; let sorted = GHC.topSortModuleGraph False mod_summaries Nothing
67
68                 -- Print out the dependencies if wanted
69         ; debugTraceMsg dflags 2 (showSDoc (text "Module dependencies" $$ ppr sorted))
70                 
71                 -- Prcess them one by one, dumping results into makefile
72                 -- and complaining about cycles
73         ; mapM (processDeps session (mkd_tmp_hdl files)) sorted
74
75                 -- Tidy up
76         ; endMkDependHS dflags files }
77
78 -----------------------------------------------------------------
79 --
80 --              beginMkDependHs
81 --      Create a temporary file, 
82 --      find the Makefile, 
83 --      slurp through it, etc
84 --
85 -----------------------------------------------------------------
86
87 data MkDepFiles 
88   = MkDep { mkd_make_file :: FilePath,          -- Name of the makefile
89             mkd_make_hdl  :: Maybe Handle,      -- Handle for the open makefile 
90             mkd_tmp_file  :: FilePath,          -- Name of the temporary file
91             mkd_tmp_hdl   :: Handle }           -- Handle of the open temporary file
92
93 beginMkDependHS :: DynFlags -> IO MkDepFiles
94         
95 beginMkDependHS dflags = do
96         -- slurp in the mkdependHS-style options
97   let flags = getOpts dflags opt_dep
98   _ <- processArgs dep_opts flags
99
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   makefile <- readIORef v_Dep_makefile
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 :: Session
152             -> Handle           -- Write dependencies to here
153             -> SCC ModSummary
154             -> IO ()
155 -- Write suitable dependencies to handle
156 -- Always:
157 --                      this.o : this.hs
158 --
159 -- If the dependency is on something other than a .hi file:
160 --                      this.o this.p_o ... : dep
161 -- otherwise
162 --                      this.o ...   : dep.hi
163 --                      this.p_o ... : dep.p_hi
164 --                      ...
165 -- (where .o is $osuf, and the other suffixes come from
166 -- the cmdline -s options).
167 --
168 -- For {-# SOURCE #-} imports the "hi" will be "hi-boot".
169
170 processDeps session hdl (CyclicSCC nodes)
171   =     -- There shouldn't be any cycles; report them   
172     throwDyn (ProgramError (showSDoc $ GHC.cyclicModuleErr nodes))
173
174 processDeps session hdl (AcyclicSCC node)
175   = do  { extra_suffixes   <- readIORef v_Dep_suffixes
176         ; hsc_env <- GHC.sessionHscEnv session
177         ; include_pkg_deps <- readIORef v_Dep_include_pkg_deps
178         ; let src_file  = msHsFilePath node
179               obj_file  = msObjFilePath node
180               obj_files = insertSuffixes obj_file extra_suffixes
181
182               do_imp is_boot imp_mod
183                 = do { mb_hi <- findDependency hsc_env src_file imp_mod 
184                                                is_boot include_pkg_deps
185                      ; case mb_hi of {
186                            Nothing      -> return () ;
187                            Just hi_file -> do
188                      { let hi_files = insertSuffixes hi_file extra_suffixes
189                            write_dep (obj,hi) = writeDependency hdl [obj] hi
190
191                         -- Add one dependency for each suffix; 
192                         -- e.g.         A.o   : B.hi
193                         --              A.x_o : B.x_hi
194                      ; mapM_ write_dep (obj_files `zip` hi_files) }}}
195
196              
197                 -- Emit std dependency of the object(s) on the source file
198                 -- Something like       A.o : A.hs
199         ; writeDependency hdl obj_files src_file
200
201                 -- Emit a dependency for each import
202         ; mapM_ (do_imp True)  (ms_srcimps node)        -- SOURCE imports
203         ; mapM_ (do_imp False) (ms_imps node)           -- regular imports
204         }
205
206
207 findDependency  :: HscEnv
208                 -> FilePath             -- Importing module: used only for error msg
209                 -> Module               -- Imported module
210                 -> IsBootInterface      -- Source import
211                 -> Bool                 -- Record dependency on package modules
212                 -> IO (Maybe FilePath)  -- Interface file file
213 findDependency hsc_env src imp is_boot include_pkg_deps
214   = do  {       -- Find the module; this will be fast because
215                 -- we've done it once during downsweep
216           r <- findModule hsc_env imp True {-explicit-}
217         ; case r of 
218             Found loc pkg
219                 -- Not in this package: we don't need a dependency
220                 | ExtPackage _ <- pkg, not include_pkg_deps
221                 -> return Nothing
222
223                 -- Home package: just depend on the .hi or hi-boot file
224                 | otherwise
225                 -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))
226
227             _ -> panic "findDependency"
228         }
229
230 -----------------------------
231 writeDependency :: Handle -> [FilePath] -> FilePath -> IO ()
232 -- (writeDependency h [t1,t2] dep) writes to handle h the dependency
233 --      t1 t2 : dep
234 writeDependency hdl targets dep
235   = hPutStrLn hdl (unwords (map escapeSpaces targets) ++ " : "
236                    ++ escapeSpaces dep)
237
238 -----------------------------
239 insertSuffixes  
240         :: FilePath     -- Original filename;   e.g. "foo.o"
241         -> [String]     -- Extra suffices       e.g. ["x","y"]
242         -> [FilePath]   -- Zapped filenames     e.g. ["foo.o", "foo.x_o", "foo.y_o"]
243         -- Note that that the extra bit gets inserted *before* the old suffix
244         -- We assume the old suffix contains no dots, so we can strip it with removeSuffix
245
246         -- NOTE: we used to have this comment
247                 -- In order to construct hi files with alternate suffixes, we
248                 -- now have to find the "basename" of the hi file.  This is
249                 -- difficult because we can't just split the hi filename
250                 -- at the last dot - the hisuf might have dots in it.  So we
251                 -- check whether the hi filename ends in hisuf, and if it does,
252                 -- we strip off hisuf, otherwise we strip everything after the
253                 -- last dot.
254         -- But I'm not sure we care about hisufs with dots in them. 
255         -- Lots of other things will break first!
256
257 insertSuffixes file_name extras
258   = file_name : [ basename ++ "." ++ extra ++ "_" ++ suffix | extra <- extras ]
259   where
260     (basename, suffix) = splitFilename file_name
261
262
263 -----------------------------------------------------------------
264 --
265 --              endMkDependHs
266 --      Complete the makefile, close the tmp file etc
267 --
268 -----------------------------------------------------------------
269
270 endMkDependHS :: DynFlags -> MkDepFiles -> IO ()
271
272 endMkDependHS dflags 
273    (MkDep { mkd_make_file = makefile, mkd_make_hdl =  makefile_hdl,
274             mkd_tmp_file  = tmp_file, mkd_tmp_hdl  =  tmp_hdl }) 
275   = do
276   -- write the magic marker into the tmp file
277   hPutStrLn tmp_hdl depEndMarker
278
279   case makefile_hdl of
280      Nothing  -> return ()
281      Just hdl -> do
282
283           -- slurp the rest of the original makefile and copy it into the output
284         let slurp = do
285                 l <- hGetLine hdl
286                 hPutStrLn tmp_hdl l
287                 slurp
288          
289         catchJust ioErrors slurp 
290                 (\e -> if isEOFError e then return () else ioError e)
291
292         hClose hdl
293
294   hClose tmp_hdl  -- make sure it's flushed
295
296         -- Create a backup of the original makefile
297   when (isJust makefile_hdl)
298        (SysTools.copy dflags ("Backing up " ++ makefile) 
299           makefile (makefile++".bak"))
300
301         -- Copy the new makefile in place
302   SysTools.copy dflags "Installing new makefile" tmp_file makefile
303
304
305 -----------------------------------------------------------------
306 --
307 --              Flags
308 --
309 -----------------------------------------------------------------
310
311         -- Flags
312 GLOBAL_VAR(v_Dep_makefile,              "Makefile", String);
313 GLOBAL_VAR(v_Dep_include_pkg_deps,      False, Bool);
314 GLOBAL_VAR(v_Dep_exclude_mods,          [], [Module]);
315 GLOBAL_VAR(v_Dep_suffixes,              [], [String]);
316 GLOBAL_VAR(v_Dep_warnings,              True, Bool);
317
318 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
319 depEndMarker   = "# DO NOT DELETE: End of Haskell dependencies"
320
321 -- for compatibility with the old mkDependHS, we accept options of the form
322 -- -optdep-f -optdep.depend, etc.
323 dep_opts = 
324    [ (  "s",                    SepArg (consIORef v_Dep_suffixes) )
325    , (  "f",                    SepArg (writeIORef v_Dep_makefile) )
326    , (  "w",                    NoArg (writeIORef v_Dep_warnings False) )
327    , (  "-include-prelude",     NoArg (writeIORef v_Dep_include_pkg_deps True) )
328    , (  "-include-pkg-deps",    NoArg (writeIORef v_Dep_include_pkg_deps True) )
329    , (  "-exclude-module=",     Prefix (consIORef v_Dep_exclude_mods . mkModule) )
330    , (  "x",                    Prefix (consIORef v_Dep_exclude_mods . mkModule) )
331    ]