Oracles.hs 11.2 KB
Newer Older
1
{-# LANGUAGE TypeFamilies, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses #-}
2
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving, ConstraintKinds #-}
3
4
5
6
7
8
9
10

module Oracles (
    module Control.Monad,
    module Development.Shake.Rule,
    module Prelude,
    Builder (..), Flag (..), Option (..),
    path, with, run, argPath,
    option, argOption,
11
    Condition, test, when, unless, not, (&&), (||),
12
    packagaDataOption, PackageDataKey (..),
13
14
15
16
    oracleRules
    ) where

import Development.Shake.Rule
17
import Development.Shake.Config
18
19
20
21
22
23
import Development.Shake.Classes
import Control.Monad hiding (when, unless)
import qualified Data.HashMap.Strict as M
import qualified Prelude
import Prelude hiding (not, (&&), (||))
import Base
24
import Util
25
import Config
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

data Builder = Ar | Ld | Gcc | Alex | Happy | HsColour | GhcCabal | GhcPkg Stage | Ghc Stage

path :: Builder -> Action FilePath
path builder = do
    let key = case builder of
            Ar            -> "ar"
            Ld            -> "ld"
            Gcc           -> "gcc"
            Alex          -> "alex"
            Happy         -> "happy"
            HsColour      -> "hscolour"
            GhcCabal      -> "ghc-cabal"
            Ghc Stage0    -> "system-ghc"     -- Ghc Stage0 is the bootstrapping compiler 
            Ghc Stage1    -> "ghc-stage1"     -- Ghc StageN, N > 0, is the one built on stage (N - 1)
            Ghc Stage2    -> "ghc-stage2"
            Ghc Stage3    -> "ghc-stage3"
            GhcPkg Stage0 -> "system-ghc-pkg" -- GhcPkg Stage0 is the bootstrapping GhcPkg 
            GhcPkg _      -> "ghc-pkg"        -- GhcPkg StageN, N > 0, is the one built on stage 0 (TODO: need only Stage1?)
45
    cfgPath <- askConfigWithDefault key $
46
47
48
        error $ "\nCannot find path to '"
        ++ key
        ++ "' in configuration files."
49
50
51
52
53
    let cfgPathExe = if cfgPath /= "" then cfgPath -<.> exe else ""
    windows <- test WindowsHost
    if (windows && "/" `isPrefixOf` cfgPathExe)
    then do
        root <- option Root
54
        return $ root ++ (drop 1 $ cfgPathExe)
55
56
    else
        return cfgPathExe
57
58
59
60
61
62

argPath :: Builder -> Args
argPath builder = do
    path <- path builder
    arg [path]

63
64
65
66
67
-- When LaxDeps flag is set (by adding 'lax-dependencies = YES' to user.config),
-- dependencies on the GHC executable are turned into order-only dependencies to
-- avoid needless recompilation when making changes to GHC's sources. In certain
-- situations this can lead to build failures, in which case you should reset
-- the flag (at least temporarily).
68
needBuilder :: Builder -> Action ()
69
needBuilder ghc @ (Ghc stage) = do
70
    target  <- path ghc
71
    laxDeps <- test LaxDeps
72
73
    if laxDeps then orderOnly [target] else need [target]

74
needBuilder builder = do 
75
76
77
    target <- path builder
    need [target]

78
-- Action 'with Gcc' returns an argument '--with-gcc=/path/to/gcc' and needs the builder 
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
with :: Builder -> Args
with builder = do 
    let prefix = case builder of 
            Ar       -> "--with-ar="
            Ld       -> "--with-ld="
            Gcc      -> "--with-gcc="
            Ghc _    -> "--with-ghc="
            Alex     -> "--with-alex="
            Happy    -> "--with-happy="
            GhcPkg _ -> "--with-ghc-pkg="
            HsColour -> "--with-hscolour="
    suffix <- path builder
    needBuilder builder
    return [prefix ++ suffix]

run :: Builder -> Args -> Action ()
run builder args = do
    needBuilder builder
    exe   <- path builder
    args' <- args
    cmd [exe :: FilePath] args'

data Option = TargetOS | TargetArch | TargetPlatformFull
            | ConfCcArgs Stage | ConfGccLinkerArgs Stage | ConfLdLinkerArgs Stage | ConfCppArgs Stage
            | IconvIncludeDirs | IconvLibDirs | GmpIncludeDirs | GmpLibDirs
104
            | SrcHcOpts
105
            | HostOsCpp | Root
106
107

option :: Option -> Action String
108
109
110
111
option Root = do
    windows <- test WindowsHost
    if (windows)
    then do
112
        Stdout out <- quietly $ cmd ["cygpath", "-m", "/"]
113
114
115
116
        return $ dropWhileEnd isSpace out
    else
        return "/"

117
118
119
120
121
122
123
124
125
126
127
128
option opt = askConfig $ case opt of 
    TargetOS                -> "target-os"
    TargetArch              -> "target-arch"
    TargetPlatformFull      -> "target-platform-full"
    ConfCcArgs        stage -> "conf-cc-args-stage-"         ++ (show . fromEnum) stage
    ConfCppArgs       stage -> "conf-cpp-args-stage-"        ++ (show . fromEnum) stage
    ConfGccLinkerArgs stage -> "conf-gcc-linker-args-stage-" ++ (show . fromEnum) stage
    ConfLdLinkerArgs  stage -> "conf-ld-linker-args-stage-"  ++ (show . fromEnum) stage
    IconvIncludeDirs        -> "iconv-include-dirs"
    IconvLibDirs            -> "iconv-lib-dirs"
    GmpIncludeDirs          -> "gmp-include-dirs"
    GmpLibDirs              -> "gmp-lib-dirs"
129
    SrcHcOpts               -> "src-hc-opts"
130
131
132
133
134
135
136
    HostOsCpp               -> "host-os-cpp"

argOption :: Option -> Args
argOption opt = do
    opt' <- option opt
    arg [opt']

137
data Flag = LaxDeps | DynamicGhcPrograms | GhcWithInterpreter | HsColourSrcs
138
          | GccIsClang | GccLt46 | CrossCompiling | Validating | PlatformSupportsSharedLibs
139
          | WindowsHost | SupportsPackageKey
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

test :: Flag -> Action Bool
test GhcWithInterpreter = do
    os   <- option TargetOS
    arch <- option TargetArch
    return $
        os `elem` ["mingw32", "cygwin32", "linux", "solaris2", "freebsd", "dragonfly", "netbsd", "openbsd", "darwin", "kfreebsdgnu"]
        &&
        arch `elem` ["i386", "x86_64", "powerpc", "sparc", "sparc64", "arm"]

test PlatformSupportsSharedLibs = do
    platform <- option TargetPlatformFull
    return $ platform `notElem` [ "powerpc-unknown-linux", "x86_64-unknown-mingw32", "i386-unknown-mingw32" ] -- TODO: i386-unknown-solaris2?

test HsColourSrcs = do
    hscolour <- path HsColour
    return $ hscolour /= ""

158
159
160
161
test WindowsHost = do
    hostOsCpp <- option HostOsCpp
    return $ hostOsCpp `elem` ["mingw32", "cygwin32"]

162
163
test flag = do
    (key, defaultValue) <- return $ case flag of
164
165
166
167
168
169
170
        LaxDeps            -> ("lax-dependencies"     , False) -- TODO: move flags to a separate file
        DynamicGhcPrograms -> ("dynamic-ghc-programs" , False)
        GccIsClang         -> ("gcc-is-clang"         , False)
        GccLt46            -> ("gcc-lt-46"            , False)
        CrossCompiling     -> ("cross-compiling"      , False)
        Validating         -> ("validating"           , False)
        SupportsPackageKey -> ("supports-package-key" , False)
171
172
    let defaultString = if defaultValue then "YES" else "NO"
    value <- askConfigWithDefault key $
173
        do putLoud $ "\nFlag '" -- TODO: Give the warning *only once* per key
174
175
176
177
178
179
180
181
                ++ key
                ++ "' not set in configuration files. "
                ++ "Proceeding with default value '"
                ++ defaultString
                ++ "'.\n"
           return defaultString
    return $ value == "YES"

182
183
type Condition = Action Bool

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
class ToCondition a where
    toCondition :: a -> Condition

instance ToCondition Condition where
    toCondition = id

instance ToCondition Bool where
    toCondition = return

instance ToCondition Flag where
    toCondition = test

when :: (ToCondition a, Monoid m) => a -> Action m -> Action m
when x args = do
    bool <- toCondition x
    if bool then args else mempty

unless :: (ToCondition a, Monoid m) => a -> Action m -> Action m
unless x args = do
    bool <- toCondition x
    if bool then mempty else args

class Not a where
    type NotResult a
    not :: a -> NotResult a

instance Not Bool where
    type NotResult Bool = Bool
    not = Prelude.not

instance Not Condition where
    type NotResult Condition = Condition
    not x = not <$> (toCondition x)

instance Not Flag where
    type NotResult Flag = Condition
    not x = not (toCondition x)

class AndOr a b where
    type AndOrResult a b
    (&&) :: a -> b -> AndOrResult a b
    (||) :: a -> b -> AndOrResult a b

infixr 3 &&
infixr 2 ||

instance AndOr Bool Bool where
    type AndOrResult Bool Bool = Bool
    (&&) = (Prelude.&&)
    (||) = (Prelude.||)

instance ToCondition a => AndOr Condition a where
    type AndOrResult Condition a = Condition
    x && y = (Prelude.&&) <$> toCondition x <*> toCondition y
    x || y = (Prelude.||) <$> toCondition x <*> toCondition y

instance ToCondition a => AndOr Flag a where
    type AndOrResult Flag a = Condition
    x && y = toCondition x && y
    x || y = toCondition x || y

newtype ConfigKey = ConfigKey String deriving (Show, Typeable, Eq, Hashable, Binary, NFData)

askConfigWithDefault :: String -> Action String -> Action String
askConfigWithDefault key defaultAction = do
249
    maybeValue <- askOracle $ ConfigKey key 
250
251
    case maybeValue of
        Just value -> return value
Andrey Mokhov's avatar
Andrey Mokhov committed
252
        Nothing    -> defaultAction
253
254

askConfig :: String -> Action String
Andrey Mokhov's avatar
Andrey Mokhov committed
255
256
askConfig key = askConfigWithDefault key $
    error $ "\nCannot find key '" ++ key ++ "' in configuration files."
257

258
259
260
261
262
263
264
265
newtype PackageDataPair = PackageDataPair (FilePath, String)
                        deriving (Show, Typeable, Eq, Hashable, Binary, NFData)

packagaDataOptionWithDefault :: FilePath -> String -> Action String -> Action String
packagaDataOptionWithDefault file key defaultAction = do
    maybeValue <- askOracle $ PackageDataPair (file, key) 
    case maybeValue of
        Just value -> return value
Andrey Mokhov's avatar
Andrey Mokhov committed
266
        Nothing    -> defaultAction
267

268
269
data PackageDataKey = Modules | SrcDirs | PackageKey | IncludeDirs | Deps | DepKeys
                    deriving Show
270
271
272

packagaDataOption :: FilePath -> PackageDataKey -> Action String
packagaDataOption file key = do
273
274
275
276
277
278
279
280
281
    let (keyName, ifEmpty) = case key of
           Modules     -> ("MODULES"     , "" )
           SrcDirs     -> ("HS_SRC_DIRS" , ".")
           PackageKey  -> ("PACKAGE_KEY" , "" )
           IncludeDirs -> ("INCLUDE_DIRS", ".")
           Deps        -> ("DEPS"        , "" )
           DepKeys     -> ("DEP_KEYS"    , "" )
        keyFullName = replaceSeparators '_' $ takeDirectory file ++ "_" ++ keyName
    res <- packagaDataOptionWithDefault file keyFullName $
Andrey Mokhov's avatar
Andrey Mokhov committed
282
        error $ "\nCannot find key '" ++ keyName ++ "' in " ++ file ++ "."
283
    return $ if res == "" then ifEmpty else res
284

285
286
287
oracleRules :: Rules ()
oracleRules = do
    cfg <- newCache $ \() -> do
288
        unless (doesFileExist $ cfgPath </> "default.config.in") $ do
289
            error $ "\nDefault configuration file '"
290
                ++ (cfgPath </> "default.config.in")
291
292
                ++ "' is missing; unwilling to proceed."
            return ()
293
294
295
        need [cfgPath </> "default.config"]
        cfgDefault <- liftIO $ readConfigFile $ cfgPath </> "default.config"
        existsUser <- doesFileExist $ cfgPath </> "user.config"
296
        cfgUser    <- if existsUser
297
                      then liftIO $ readConfigFile $ cfgPath </> "user.config"
298
299
                      else do
                          putLoud $ "\nUser defined configuration file '"
300
                              ++ (cfgPath </> "user.config")
301
302
303
                              ++ "' is missing; proceeding with default configuration.\n"
                          return M.empty
        return $ cfgUser `M.union` cfgDefault
304
305
306
307
308
309
310
311

    addOracle $ \(ConfigKey key) -> M.lookup key <$> cfg ()

    pkgData <- newCache $ \file -> do
        need [file]
        liftIO $ readConfigFile file

    addOracle $ \(PackageDataPair (file, key)) -> M.lookup key <$> pkgData file
312
    return ()