codegen_cfg/
ast.rs

1use std::fmt;
2
3pub use bool_logic::ast::All;
4pub use bool_logic::ast::Any;
5pub use bool_logic::ast::Not;
6pub use bool_logic::ast::Var;
7
8pub type Expr = bool_logic::ast::Expr<Pred>;
9
10pub fn expr(x: impl Into<Expr>) -> Expr {
11    x.into()
12}
13
14pub fn any(x: impl Into<Any<Pred>>) -> Any<Pred> {
15    x.into()
16}
17
18pub fn all(x: impl Into<All<Pred>>) -> All<Pred> {
19    x.into()
20}
21
22pub fn not(x: impl Into<Not<Pred>>) -> Not<Pred> {
23    x.into()
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Pred {
28    pub key: String,
29    pub value: Option<String>,
30}
31
32impl From<Pred> for Expr {
33    fn from(x: Pred) -> Self {
34        Expr::Var(Var(x))
35    }
36}
37
38pub fn flag(s: impl Into<String>) -> Pred {
39    Pred {
40        key: s.into(),
41        value: None,
42    }
43}
44
45pub fn key_value(s: impl Into<String>, v: impl Into<String>) -> Pred {
46    Pred {
47        key: s.into(),
48        value: Some(v.into()),
49    }
50}
51
52pub fn target_family(s: impl Into<String>) -> Pred {
53    key_value("target_family", s)
54}
55
56pub fn target_vendor(s: impl Into<String>) -> Pred {
57    key_value("target_vendor", s)
58}
59
60pub fn target_arch(s: impl Into<String>) -> Pred {
61    key_value("target_arch", s)
62}
63
64pub fn target_os(s: impl Into<String>) -> Pred {
65    key_value("target_os", s)
66}
67
68pub fn target_env(s: impl Into<String>) -> Pred {
69    key_value("target_env", s)
70}
71
72pub fn target_pointer_width(s: impl Into<String>) -> Pred {
73    key_value("target_pointer_width", s)
74}
75
76impl fmt::Display for Pred {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        let key = self.key.as_str();
79        match &self.value {
80            Some(value) => write!(f, "{key} = {value:?}"),
81            None => write!(f, "{key}"),
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn cfg_string() {
92        {
93            let cfg = expr(target_family("unix"));
94            let expected = r#"target_family = "unix""#;
95            assert_eq!(cfg.to_string(), expected);
96        }
97        {
98            let cfg = expr(any((target_os("linux"), target_os("android"))));
99            let expected = r#"any(target_os = "linux", target_os = "android")"#;
100            assert_eq!(cfg.to_string(), expected);
101        }
102    }
103}