1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
use std::fmt;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Expr {
    Any(Any),
    All(All),
    Not(Not),
    Atom(Pred),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Any(pub Vec<Expr>);

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct All(pub Vec<Expr>);

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Not(pub Box<Expr>);

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Pred {
    TargetFamily(String),
    TargetVendor(String),
    TargetArch(String),
    TargetOs(String),
    TargetEnv(String),
    TargetPointerWidth(String),
}

impl From<Pred> for Expr {
    fn from(x: Pred) -> Self {
        Expr::Atom(x)
    }
}

impl From<Not> for Expr {
    fn from(x: Not) -> Self {
        Expr::Not(x)
    }
}

impl From<Any> for Expr {
    fn from(x: Any) -> Self {
        Expr::Any(x)
    }
}

impl From<All> for Expr {
    fn from(x: All) -> Self {
        Expr::All(x)
    }
}

impl From<Vec<Expr>> for Any {
    fn from(x: Vec<Expr>) -> Self {
        Any(x)
    }
}

impl From<Vec<Expr>> for All {
    fn from(x: Vec<Expr>) -> Self {
        All(x)
    }
}

impl From<Box<Expr>> for Not {
    fn from(x: Box<Expr>) -> Self {
        Not(x)
    }
}

impl From<Expr> for Not {
    fn from(x: Expr) -> Self {
        Not(Box::new(x))
    }
}

macro_rules! impl_from_tuple {
    ($ty:ty, ($tt:tt,)) => {
        impl_from_tuple!(@expand $ty, ($tt,));
    };
    ($ty:ty, ($x:tt, $($xs:tt,)+)) => {
        impl_from_tuple!($ty, ($($xs,)+));
        impl_from_tuple!(@expand $ty, ($x, $($xs,)+));
    };
    (@expand $ty:ty, ($($tt:tt,)+)) => {
        #[doc(hidden)] // too ugly
        #[allow(non_camel_case_types)]
        impl<$($tt),+> From<($($tt,)+)>  for $ty
        where
            $($tt: Into<Expr>,)+
        {
            fn from(($($tt,)+): ($($tt,)+)) -> Self {
                Self::from(vec![$(Into::into($tt)),+])
            }
        }
    };
}

impl_from_tuple!(
    Any,
    (
        x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, //
        x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, //
        x24, x25, x26, x27, x28, x29, x30, x31, x32, x33, x34, x35,
    )
);

impl_from_tuple!(
    All,
    (
        x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, //
        x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, //
        x24, x25, x26, x27, x28, x29, x30, x31, x32, x33, x34, x35,
    )
);

pub fn expr(x: impl Into<Expr>) -> Expr {
    x.into()
}

pub fn any(x: impl Into<Any>) -> Any {
    x.into()
}

pub fn all(x: impl Into<All>) -> All {
    x.into()
}

pub fn not(x: impl Into<Not>) -> Not {
    x.into()
}

pub fn target_family(s: impl Into<String>) -> Pred {
    Pred::TargetFamily(s.into())
}

pub fn target_vendor(s: impl Into<String>) -> Pred {
    Pred::TargetVendor(s.into())
}

pub fn target_arch(s: impl Into<String>) -> Pred {
    Pred::TargetArch(s.into())
}

pub fn target_os(s: impl Into<String>) -> Pred {
    Pred::TargetOs(s.into())
}

pub fn target_env(s: impl Into<String>) -> Pred {
    Pred::TargetEnv(s.into())
}

pub fn target_pointer_width(s: impl Into<String>) -> Pred {
    Pred::TargetPointerWidth(s.into())
}

impl fmt::Display for Expr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Expr::Any(x) => write!(f, "{x}"),
            Expr::All(x) => write!(f, "{x}"),
            Expr::Not(x) => write!(f, "{x}"),
            Expr::Atom(x) => write!(f, "{x}"),
        }
    }
}

impl fmt::Display for Any {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_list(f, "any", &self.0)
    }
}

impl fmt::Display for All {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_list(f, "all", &self.0)
    }
}

impl fmt::Display for Not {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "not({})", self.0)
    }
}

impl fmt::Display for Pred {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Pred::TargetFamily(s) => match s.as_str() {
                "unix" | "windows" | "wasm" => write!(f, "{s}"),
                _ => fmt_pred(f, "target_family", s),
            },
            Pred::TargetVendor(s) => fmt_pred(f, "target_vendor", s),
            Pred::TargetArch(s) => fmt_pred(f, "target_arch", s),
            Pred::TargetOs(s) => fmt_pred(f, "target_os", s),
            Pred::TargetEnv(s) => fmt_pred(f, "target_env", s),
            Pred::TargetPointerWidth(s) => fmt_pred(f, "target_pointer_width", s),
        }
    }
}

fn fmt_pred(f: &mut fmt::Formatter<'_>, key: &str, value: &str) -> fmt::Result {
    write!(f, "{key} = {value:?}")
}

fn fmt_list(f: &mut fmt::Formatter<'_>, name: &str, list: &[Expr]) -> fmt::Result {
    let (x, xs) = list.split_first().expect("empty predicate list");
    write!(f, "{name}({x}")?;
    for x in xs {
        write!(f, ", {x}")?;
    }
    write!(f, ")")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cfg_string() {
        {
            let cfg = expr(target_family("unix"));
            let expected = "unix";
            assert_eq!(cfg.to_string(), expected);
        }
        {
            let cfg = expr(any((target_os("linux"), target_os("android"))));
            let expected = r#"any(target_os = "linux", target_os = "android")"#;
            assert_eq!(cfg.to_string(), expected);
        }
    }
}