Initial commit; code copied from the base package
[ghc-prim.git] / Setup.hs
1
2 -- We need to do some ugly hacks here because of GHC magic
3
4 module Main (main) where
5
6 import Control.Monad
7 import Data.List
8 import Distribution.PackageDescription
9 import Distribution.Simple
10 import Distribution.Simple.LocalBuildInfo
11 import Distribution.Simple.Utils
12 import System.Cmd
13 import System.FilePath
14 import System.Exit
15 import System.Directory
16 import Control.Exception (try)
17
18 main :: IO ()
19 main = do let hooks = defaultUserHooks {
20                   buildHook = build_primitive_sources
21                             $ buildHook defaultUserHooks,
22                   makefileHook = build_primitive_sources
23                                $ makefileHook defaultUserHooks,
24                   haddockHook = build_primitive_sources
25                                $ haddockHook defaultUserHooks }
26           defaultMainWithHooks hooks
27
28 type Hook a = PackageDescription -> LocalBuildInfo -> UserHooks -> a -> IO ()
29
30 build_primitive_sources :: Hook a -> Hook a
31 build_primitive_sources f pd lbi uhs x
32  = do when (compilerFlavor (compiler lbi) == GHC) $ do
33           let genprimopcode = joinPath ["..", "..", "utils",
34                                         "genprimopcode", "genprimopcode"]
35               primops = joinPath ["..", "..", "compiler", "prelude",
36                                   "primops.txt"]
37               primhs = joinPath ["GHC", "Prim.hs"]
38               primopwrappers = joinPath ["GHC", "PrimopWrappers.hs"]
39               primhs_tmp = addExtension primhs "tmp"
40               primopwrappers_tmp = addExtension primopwrappers "tmp"
41           maybeExit $ system (genprimopcode ++ " --make-haskell-source < "
42                            ++ primops ++ " > " ++ primhs_tmp)
43           maybeUpdateFile primhs_tmp primhs
44           maybeExit $ system (genprimopcode ++ " --make-haskell-wrappers < "
45                            ++ primops ++ " > " ++ primopwrappers_tmp)
46           maybeUpdateFile primopwrappers_tmp primopwrappers
47       f pd lbi uhs x
48
49 -- Replace a file only if the new version is different from the old.
50 -- This prevents make from doing unnecessary work after we run 'setup makefile'
51 maybeUpdateFile :: FilePath -> FilePath -> IO ()
52 maybeUpdateFile source target = do
53   r <- rawSystem "cmp" ["-s" {-quiet-}, source, target]
54   case r of
55     ExitSuccess   -> removeFile source
56     ExitFailure _ -> do try (removeFile target); renameFile source target
57