[project @ 2003-11-17 14:23:30 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / DriverMkDepend.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverMkDepend.hs,v 1.31 2003/11/17 14:23:38 simonmar Exp $
3 --
4 -- GHC Driver
5 --
6 -- (c) Simon Marlow 2000
7 --
8 -----------------------------------------------------------------------------
9
10 module DriverMkDepend (
11         doMkDependHSPhase, beginMkDependHS, endMkDependHS
12   ) where
13
14 #include "HsVersions.h"
15
16 import GetImports       ( getImports )
17 import DriverState      
18 import DriverUtil
19 import DriverFlags
20 import SysTools         ( newTempName )
21 import qualified SysTools
22 import Module           ( ModuleName, ModLocation(..),
23                           moduleNameUserString, isHomeModule )
24 import Finder           ( findModule, hiBootExt, hiBootVerExt,
25                           mkHomeModLocation )
26 import Util             ( global )
27 import Panic
28
29 import DATA_IOREF       ( IORef, readIORef, writeIORef )
30 import EXCEPTION
31
32 import Directory
33 import IO
34 import Monad            ( when )
35 import Maybe            ( isJust )
36
37 #if __GLASGOW_HASKELL__ <= 408
38 import Panic            ( catchJust, ioErrors )
39 #endif
40
41 -------------------------------------------------------------------------------
42 -- mkdependHS
43
44         -- flags
45 GLOBAL_VAR(v_Dep_makefile,              "Makefile", String);
46 GLOBAL_VAR(v_Dep_include_prelude,       False, Bool);
47 GLOBAL_VAR(v_Dep_exclude_mods,          ["GHC.Prim"], [String]);
48 GLOBAL_VAR(v_Dep_suffixes,              [], [String]);
49 GLOBAL_VAR(v_Dep_warnings,              True, Bool);
50
51         -- global vars
52 GLOBAL_VAR(v_Dep_makefile_hdl,  error "dep_makefile_hdl", Maybe Handle);
53 GLOBAL_VAR(v_Dep_tmp_file,      error "dep_tmp_file", String);
54 GLOBAL_VAR(v_Dep_tmp_hdl,       error "dep_tmp_hdl", Handle);
55 GLOBAL_VAR(v_Dep_dir_contents,  error "dep_dir_contents", [(String,[String])]);
56
57 depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies"
58 depEndMarker   = "# DO NOT DELETE: End of Haskell dependencies"
59
60 -- for compatibility with the old mkDependHS, we accept options of the form
61 -- -optdep-f -optdep.depend, etc.
62 dep_opts = 
63    [ (  "s",                    SepArg (add v_Dep_suffixes) )
64    , (  "f",                    SepArg (writeIORef v_Dep_makefile) )
65    , (  "w",                    NoArg (writeIORef v_Dep_warnings False) )
66    , (  "-include-prelude",     NoArg (writeIORef v_Dep_include_prelude True) )
67    , (  "-exclude-module=",       Prefix (add v_Dep_exclude_mods) )
68    , (  "x",                      Prefix (add v_Dep_exclude_mods) )
69    ]
70
71 beginMkDependHS :: IO ()
72 beginMkDependHS = do
73
74         -- slurp in the mkdependHS-style options
75   flags <- getStaticOpts v_Opt_dep
76   _ <- processArgs dep_opts flags []
77
78         -- open a new temp file in which to stuff the dependency info
79         -- as we go along.
80   dep_file <- newTempName "dep"
81   writeIORef v_Dep_tmp_file dep_file
82   tmp_hdl <- openFile dep_file WriteMode
83   writeIORef v_Dep_tmp_hdl tmp_hdl
84
85         -- open the makefile
86   makefile <- readIORef v_Dep_makefile
87   exists <- doesFileExist makefile
88   if not exists
89         then do 
90            writeIORef v_Dep_makefile_hdl Nothing
91            return ()
92
93         else do
94            makefile_hdl <- openFile makefile ReadMode
95            writeIORef v_Dep_makefile_hdl (Just makefile_hdl)
96
97                 -- slurp through until we get the magic start string,
98                 -- copying the contents into dep_makefile
99            let slurp = do
100                 l <- hGetLine makefile_hdl
101                 if (l == depStartMarker)
102                         then return ()
103                         else do hPutStrLn tmp_hdl l; slurp
104          
105                 -- slurp through until we get the magic end marker,
106                 -- throwing away the contents
107            let chuck = do
108                 l <- hGetLine makefile_hdl
109                 if (l == depEndMarker)
110                         then return ()
111                         else chuck
112          
113            catchJust ioErrors slurp 
114                 (\e -> if isEOFError e then return () else ioError e)
115            catchJust ioErrors chuck
116                 (\e -> if isEOFError e then return () else ioError e)
117
118
119         -- write the magic marker into the tmp file
120   hPutStrLn tmp_hdl depStartMarker
121
122         -- cache the contents of all the import directories, for future
123         -- reference.
124   import_dirs <- readIORef v_Import_paths
125   pkg_import_dirs <- getPackageImportPath
126   import_dir_contents <- mapM softGetDirectoryContents import_dirs
127   pkg_import_dir_contents <- mapM softGetDirectoryContents pkg_import_dirs
128   writeIORef v_Dep_dir_contents 
129         (zip import_dirs import_dir_contents ++
130          zip pkg_import_dirs pkg_import_dir_contents)
131
132   return ()
133
134
135 doMkDependHSPhase basename suff input_fn
136  = do src <- readFile input_fn
137       let (import_sources, import_normals, mod_name) = getImports src
138       let orig_fn = basename ++ '.':suff
139       (_, location') <- mkHomeModLocation mod_name orig_fn
140
141       -- take -ohi into account if present
142       ohi <- readIORef v_Output_hi
143       let location | Just fn <- ohi = location'{ ml_hi_file = fn }
144                    | otherwise      = location'
145
146       deps_sources <- mapM (findDependency True  orig_fn) import_sources
147       deps_normals <- mapM (findDependency False orig_fn) import_normals
148       let deps = deps_sources ++ deps_normals
149
150       osuf <- readIORef v_Object_suf
151       extra_suffixes <- readIORef v_Dep_suffixes
152       let suffixes = map (++ ('_':osuf)) extra_suffixes
153           obj_file = ml_obj_file location
154           objs = obj_file : map (replaceFilenameSuffix obj_file) suffixes
155
156         -- Handle for file that accumulates dependencies 
157       hdl <- readIORef v_Dep_tmp_hdl
158
159         -- std dependency of the object(s) on the source file
160       hPutStrLn hdl (unwords (map escapeSpaces objs) ++ " : " ++
161                      escapeSpaces (basename ++ '.':suff))
162
163       let genDep (dep, False {- not an hi file -}) = 
164              hPutStrLn hdl (unwords (map escapeSpaces objs) ++ " : " ++
165                             escapeSpaces dep)
166           genDep (dep, True  {- is an hi file -}) = do
167              hisuf <- readIORef v_Hi_suf
168              let dep_base = remove_suffix '.' dep
169                  deps = (dep_base ++ hisuf)
170                         : map (\suf -> dep_base ++ suf ++ '_':hisuf) extra_suffixes
171                   -- length objs should be == length deps
172              sequence_ (zipWith (\o d -> hPutStrLn hdl (escapeSpaces o ++ " : " ++ escapeSpaces d)) objs deps)
173
174       sequence_ (map genDep [ d | Just d <- deps ])
175       return location
176
177 -- add the lines to dep_makefile:
178            -- always:
179                    -- this.o : this.hs
180
181            -- if the dependency is on something other than a .hi file:
182                    -- this.o this.p_o ... : dep
183            -- otherwise
184                    -- if the import is {-# SOURCE #-}
185                            -- this.o this.p_o ... : dep.hi-boot[-$vers]
186                            
187                    -- else
188                            -- this.o ...   : dep.hi
189                            -- this.p_o ... : dep.p_hi
190                            -- ...
191    
192            -- (where .o is $osuf, and the other suffixes come from
193            -- the cmdline -s options).
194    
195
196
197 endMkDependHS :: IO ()
198 endMkDependHS = do
199   makefile     <- readIORef v_Dep_makefile
200   makefile_hdl <- readIORef v_Dep_makefile_hdl
201   tmp_file     <- readIORef v_Dep_tmp_file
202   tmp_hdl      <- readIORef v_Dep_tmp_hdl
203
204         -- write the magic marker into the tmp file
205   hPutStrLn tmp_hdl depEndMarker
206
207   case makefile_hdl of
208      Nothing  -> return ()
209      Just hdl -> do
210
211           -- slurp the rest of the original makefile and copy it into the output
212         let slurp = do
213                 l <- hGetLine hdl
214                 hPutStrLn tmp_hdl l
215                 slurp
216          
217         catchJust ioErrors slurp 
218                 (\e -> if isEOFError e then return () else ioError e)
219
220         hClose hdl
221
222   hClose tmp_hdl  -- make sure it's flushed
223
224         -- Create a backup of the original makefile
225   when (isJust makefile_hdl)
226        (SysTools.copy ("Backing up " ++ makefile) makefile (makefile++".bak"))
227
228         -- Copy the new makefile in place
229   SysTools.copy "Installing new makefile" tmp_file makefile
230
231
232 findDependency :: Bool -> FilePath -> ModuleName -> IO (Maybe (String, Bool))
233 findDependency is_source src imp = do
234    excl_mods <- readIORef v_Dep_exclude_mods
235    include_prelude <- readIORef v_Dep_include_prelude
236    let imp_mod = moduleNameUserString imp
237    if imp_mod `elem` excl_mods 
238       then return Nothing
239       else do
240         r <- findModule imp
241         case r of 
242            Right (mod,loc)
243                 -- not in this package: we don't need a dependency
244                 | not (isHomeModule mod) && not include_prelude
245                 -> return Nothing
246
247                 -- normal import: just depend on the .hi file
248                 | not is_source
249                 -> return (Just (ml_hi_file loc, not is_source))
250
251                 -- if it's a source import, we want to generate a dependency
252                 -- on the .hi-boot file, not the .hi file
253                 | otherwise
254                 -> let hi_file = ml_hi_file loc
255                        boot_hi_file = replaceFilenameSuffix hi_file hiBootExt 
256                        boot_ver_hi_file = replaceFilenameSuffix hi_file hiBootVerExt 
257                    in do
258                    b <- doesFileExist boot_ver_hi_file
259                    if b 
260                      then return (Just (boot_ver_hi_file, not is_source))
261                      else do
262                         b <- doesFileExist boot_hi_file
263                         if b 
264                            then return (Just (boot_hi_file, not is_source))
265                            else return (Just (hi_file, not is_source))
266
267            Left _ -> throwDyn (ProgramError 
268                 (src ++ ": " ++ "can't locate import `" ++ imp_mod ++ "'" ++
269                  if is_source then " (SOURCE import)" else ""))