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
1347039
fn normalise_associative_commutative(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
22
1347039
    if !expr.is_associative_commutative_operator() {
23
1248291
        return Err(RuleNotApplicable);
24
98748
    }
25

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

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

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

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

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

            
56
94743
        new_children
57
302463
    }
58

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

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

            
67
93348
    if !changed {
68
92322
        return Err(RuleNotApplicable);
69
1026
    }
70

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

            
73
1026
    Ok(Reduction::pure(new_expr))
74
1347039
}