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

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

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

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

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

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

            
56
31575
        new_children
57
100806
    }
58

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

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

            
67
31110
    if !changed {
68
30768
        return Err(RuleNotApplicable);
69
342
    }
70

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

            
73
342
    Ok(Reduction::pure(new_expr))
74
448997
}