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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use codegen_cfg::ast::*;
use codegen_cfg::bool_logic::transform::*;
use codegen_cfg::bool_logic::visit_mut::*;
use log::debug;
use rust_utils::iter::filter_map_collect_vec;
use rust_utils::vec::VecExt;

use std::cmp::Ordering::{self, *};
use std::mem;

use log::trace;

pub fn simplified_expr(x: impl Into<Expr>) -> Expr {
    let mut x = x.into();

    debug!("input:                              {x}");

    UnifyTargetFamily.visit_mut_expr(&mut x);
    trace!("after  UnifyTargetFamily:           {x}");

    for _ in 0..3 {
        FlattenSingle.visit_mut_expr(&mut x);
        trace!("after  FlattenSingle:               {x}");

        FlattenNestedList.visit_mut_expr(&mut x);
        trace!("after  FlattenNestedList:           {x}");

        DedupList.visit_mut_expr(&mut x);
        trace!("after  DedupList:                   {x}");

        EvalConst.visit_mut_expr(&mut x);
        trace!("after  EvalConst:                   {x}");

        SimplifyNestedList.visit_mut_expr(&mut x);
        trace!("after  SimplifyNestedList:          {x}");

        MergeAllOfNotAny.visit_mut_expr(&mut x);
        trace!("after  MergeAllOfNotAny:            {x}");

        SimplifyAllNotAny.visit_mut_expr(&mut x);
        trace!("after  SimplifyAllNotAny:           {x}");

        MergeAllOfAny.visit_mut_expr(&mut x);
        trace!("after  MergeAllOfAny:               {x}");

        ImplyByKey.visit_mut_expr(&mut x);
        trace!("after  ImplyByKey:                  {x}");

        SuppressTargetFamily.visit_mut_expr(&mut x);
        trace!("after  SuppressTargetFamily:        {x}");

        EvalConst.visit_mut_expr(&mut x);
        trace!("after  EvalConst:                   {x}");

        MergePattern.visit_mut_expr(&mut x);
        trace!("after  MergePattern:                {x}");

        EvalConst.visit_mut_expr(&mut x);
        trace!("after  EvalConst:                   {x}");

        SimplifyByShortCircuit.visit_mut_expr(&mut x);
        trace!("after  SimplifyByShortCircuit:      {x}");

        EvalConst.visit_mut_expr(&mut x);
        trace!("after  EvalConst:                   {x}");
    }

    SimplifyTargetFamily.visit_mut_expr(&mut x);
    trace!("after  SimplifyTargetFamily:        {x}");

    SortByPriority.visit_mut_expr(&mut x);
    trace!("after  SortByPriority:              {x}");

    SortByValue.visit_mut_expr(&mut x);
    trace!("after  SortByValue:                 {x}");

    debug!("output:                             {x}");

    x
}

struct SortByPriority;

impl SortByPriority {
    fn get_priority(x: &Expr) -> Option<u32> {
        Some(match x {
            Expr::Not(_) => 103,
            Expr::Any(_) => 101,
            Expr::All(_) => 102,
            Expr::Var(Var(pred)) => match pred.key.as_str() {
                "target_family" => 1,
                "target_arch" => 2,
                "target_vendor" => 3,
                "target_os" => 4,
                "target_env" => 5,
                "target_pointer_width" => 6,
                _ => 0,
            },
            Expr::Const(_) => panic!(),
        })
    }
}

impl VisitMut<Pred> for SortByPriority {
    fn visit_mut_expr(&mut self, expr: &mut Expr) {
        if let Some(list) = expr.as_mut_expr_list() {
            list.sort_by(|lhs, rhs| {
                let Some(lhs) = Self::get_priority(lhs) else {return Equal};
                let Some(rhs) = Self::get_priority(rhs) else {return Equal};
                lhs.cmp(&rhs)
            })
        }

        walk_mut_expr(self, expr);
    }
}

struct SortByValue;

impl SortByValue {
    fn cmp_var(lhs: &Expr, rhs: &Expr) -> Ordering {
        let Expr::Var(Var(lhs)) = lhs else { return Equal };
        let Expr::Var(Var(rhs)) = rhs else { return Equal };

        let ok = Ord::cmp(lhs.key.as_str(), rhs.key.as_str());

        match (lhs.value.as_deref(), rhs.value.as_deref()) {
            (None, None) => ok,
            (Some(lv), Some(rv)) => ok.then_with(|| Ord::cmp(lv, rv)),
            (None, Some(_)) => Less,
            (Some(_), None) => Greater,
        }
    }

    fn cmp_not(lhs: &Expr, rhs: &Expr) -> Ordering {
        let Expr::Not(Not(lhs)) = lhs else { return Equal };
        let Expr::Not(Not(rhs)) = rhs else { return Equal };

        Self::cmp_var(lhs, rhs)
    }
}

impl VisitMut<Pred> for SortByValue {
    fn visit_mut_expr(&mut self, expr: &mut Expr) {
        if let Some(list) = expr.as_mut_expr_list() {
            list.sort_by(Self::cmp_var);
            list.sort_by(Self::cmp_not);
        }

        walk_mut_expr(self, expr);
    }
}

struct UnifyTargetFamily;

impl VisitMut<Pred> for UnifyTargetFamily {
    fn visit_mut_var(&mut self, Var(pred): &mut Var<Pred>) {
        if pred.value.is_none() && matches!(pred.key.as_str(), "unix" | "windows" | "wasm") {
            *pred = key_value("target_family", pred.key.as_str());
        }
    }
}

struct SimplifyTargetFamily;

impl VisitMut<Pred> for SimplifyTargetFamily {
    fn visit_mut_var(&mut self, Var(pred): &mut Var<Pred>) {
        if pred.key == "target_family" {
            if let Some(value) = pred.value.as_deref() {
                if matches!(value, "unix" | "windows" | "wasm") {
                    *pred = flag(value);
                }
            }
        }
    }
}

struct ImplyByKey;

impl ImplyByKey {
    const UNIQUE_VALUED_KEYS: &[&'static str] = &[
        "target_family",
        "target_arch",
        "target_vendor",
        "target_os",
        "target_env",
        "target_pointer_width",
    ];

    fn fix_all(pos: &Pred, all: &mut [Expr]) {
        let pos_key = pos.key.as_str();
        let pos_value = pos.value.as_deref().unwrap();

        let fix = |x: &mut Expr| {
            if let Expr::Var(Var(var)) = x {
                if var.key == pos_key {
                    let var_value = var.value.as_deref().unwrap();
                    *x = Expr::Const(var_value == pos_value)
                }
            }
        };

        for expr in all {
            if let Expr::Not(Not(x)) = expr {
                if let Expr::Any(Any(not_any)) = &mut **x {
                    not_any.iter_mut().for_each(fix);
                } else {
                    fix(x);
                }
            }
        }
    }

    fn is_expr_any_pred(any: &[Expr], key: &str) -> bool {
        any.iter().all(|x| {
            if let Expr::Var(Var(var)) = x {
                var.key == key
            } else {
                false
            }
        })
    }
}

impl VisitMut<Pred> for ImplyByKey {
    fn visit_mut_all(&mut self, All(all): &mut All<Pred>) {
        walk_mut_expr_list(self, all);

        let mut i = 0;
        while i < all.len() {
            match &all[i] {
                Expr::Var(Var(pos)) => {
                    if Self::UNIQUE_VALUED_KEYS.contains(&pos.key.as_str()) {
                        assert!(pos.value.is_some());
                        Self::fix_all(&pos.clone(), all);
                    }
                }
                Expr::Any(Any(any)) => {
                    if Self::UNIQUE_VALUED_KEYS.iter().any(|k| Self::is_expr_any_pred(any, k)) {
                        for x in any.clone() {
                            let Expr::Var(Var(pos)) = x else { panic!() };
                            Self::fix_all(&pos, all)
                        }
                    }
                }
                _ => {}
            }
            i += 1;
        }
    }
}

struct SuppressTargetFamily;

impl SuppressTargetFamily {
    fn is_target_os_pred(x: &Expr) -> bool {
        match x {
            Expr::Var(Var(var)) => var.key == "target_os",
            _ => false,
        }
    }

    fn has_specified_target_os(x: &Expr) -> bool {
        if Self::is_target_os_pred(x) {
            return true;
        }

        if let Expr::Any(Any(any)) = x {
            return any.iter().all(Self::is_target_os_pred);
        }

        false
    }

    #[allow(clippy::match_like_matches_macro)]
    fn is_suppressed_target_family(pred: &Pred) -> bool {
        match (pred.key.as_str(), pred.value.as_deref()) {
            ("target_family", Some("unix")) => true,
            ("target_family", Some("windows")) => true,
            _ => false,
        }
    }
}

impl VisitMut<Pred> for SuppressTargetFamily {
    fn visit_mut_all(&mut self, All(all): &mut All<Pred>) {
        if all.iter().any(Self::has_specified_target_os) {
            all.remove_if(|x| match x {
                Expr::Var(Var(pred)) => Self::is_suppressed_target_family(pred),
                Expr::Not(Not(not)) => match &**not {
                    Expr::Var(Var(pred)) => Self::is_suppressed_target_family(pred),
                    _ => false,
                },
                _ => false,
            })
        }

        walk_mut_expr_list(self, all)
    }
}

struct MergePattern;

impl MergePattern {
    fn merge(any_list: &mut [Expr]) {
        let mut pattern_list = filter_map_collect_vec(any_list, |x| {
            if let Expr::All(All(all)) = x {
                if let [first, second] = all.as_mut_slice() {
                    if first.is_any() || first.is_var() {
                        return Some((first, second));
                    }
                }
            }
            None
        });

        if let [head, rest @ ..] = pattern_list.as_mut_slice() {
            let agg = match head.0 {
                Expr::Any(Any(any)) => any,
                Expr::Var(var) => {
                    *head.0 = expr(any((var.clone(),)));
                    head.0.as_mut_any().map(|x| &mut x.0).unwrap()
                }
                _ => panic!(),
            };

            for x in rest {
                let to_agg = if x.1 == head.1 {
                    &mut *x.0
                } else if x.0 == head.1 {
                    &mut *x.1
                } else {
                    continue;
                };

                match mem::replace(to_agg, Expr::Const(false)) {
                    Expr::Any(Any(any)) => agg.extend(any),
                    Expr::Var(var) => agg.push(expr(var.clone())),
                    other => *to_agg = other,
                }
            }

            if agg.len() == 1 {
                *head.0 = agg.pop().unwrap();
            }
        }
    }
}

impl VisitMut<Pred> for MergePattern {
    fn visit_mut_any(&mut self, Any(any_list): &mut Any<Pred>) {
        Self::merge(any_list);
        Self::merge(&mut any_list[1..]);
    }
}

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

    use codegen_cfg::parsing::parse;

    #[test]
    fn sort() {
        let mut expr = expr(all((not(flag("unix")), flag("unix"))));
        SortByPriority.visit_mut_expr(&mut expr);
        assert_eq!(expr.to_string(), "all(unix, not(unix))");
    }

    #[test]
    fn imply() {
        let s = r#"  all(target_os = "linux", not(target_os = "emscripten"))  "#;
        let mut expr = parse(s).unwrap();
        ImplyByKey.visit_mut_expr(&mut expr);
        assert_eq!(expr.to_string(), r#"all(target_os = "linux", not(false))"#)
    }
}