1
//! Generic normalising rules for associative-commutative operators.
2

            
3
use std::collections::VecDeque;
4
use std::mem::Discriminant;
5

            
6
use conjure_cp::ast::{Expression as Expr, SymbolTable};
7
use conjure_cp::rule_engine::{
8
    ApplicationError::RuleNotApplicable, ApplicationResult, Reduction, register_rule,
9
};
10
use uniplate::Biplate;
11

            
12
/// Normalises associative_commutative operations.
13
///
14
/// For now, this just removes nested expressions by associativity.
15
///
16
/// ```text
17
/// v(v(a,b,...),c,d,...) ~> v(a,b,c,d)
18
/// where v is an AC vector operator
19
/// ```
20
#[register_rule(("Base", 8900))]
21
1350318
fn normalise_associative_commutative(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
22
1350318
    if !expr.is_associative_commutative_operator() {
23
1221609
        return Err(RuleNotApplicable);
24
128709
    }
25

            
26
    // remove nesting deeply
27
404859
    fn recurse_deeply(
28
404859
        root_discriminant: Discriminant<Expr>,
29
404859
        expr: Expr,
30
404859
        changed: &mut bool,
31
404859
    ) -> Vec<Expr> {
32
        // if expr a different expression type, stop recursing
33
404859
        if std::mem::discriminant(&expr) != root_discriminant {
34
278304
            return vec![expr];
35
126555
        }
36

            
37
126555
        let child_vecs: VecDeque<Vec<Expr>> = expr.children_bi();
38

            
39
        // empty expression
40
126555
        if child_vecs.is_empty() {
41
            return vec![expr];
42
126555
        }
43

            
44
        // go deeper
45
126555
        let children = child_vecs[0].clone();
46
126555
        let old_len = children.len();
47

            
48
126555
        let new_children = children
49
126555
            .into_iter()
50
280212
            .flat_map(|child| recurse_deeply(root_discriminant, child, changed))
51
126555
            .collect::<Vec<_>>();
52
126555
        if new_children.len() != old_len {
53
1608
            *changed = true;
54
124947
        }
55

            
56
126555
        new_children
57
404859
    }
58

            
59
128709
    let child_vecs: VecDeque<Vec<Expr>> = expr.children_bi();
60
128709
    if child_vecs.is_empty() {
61
4062
        return Err(RuleNotApplicable);
62
124647
    }
63

            
64
124647
    let mut changed = false;
65
124647
    let new_children = recurse_deeply(std::mem::discriminant(expr), expr.clone(), &mut changed);
66

            
67
124647
    if !changed {
68
123183
        return Err(RuleNotApplicable);
69
1464
    }
70

            
71
1464
    let new_expr = expr.with_children_bi(vec![new_children].into());
72

            
73
1464
    Ok(Reduction::pure(new_expr))
74
1350318
}