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

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

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

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

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

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

            
56
7614
        new_children
57
25956
    }
58

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

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

            
67
7428
    if !changed {
68
7290
        return Err(RuleNotApplicable);
69
138
    }
70

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

            
73
138
    Ok(Reduction::pure(new_expr))
74
125024
}