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