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

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

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

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

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

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

            
56
32811
        new_children
57
105054
    }
58

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

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

            
67
32342
    if !changed {
68
31996
        return Err(RuleNotApplicable);
69
346
    }
70

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

            
73
346
    Ok(Reduction::pure(new_expr))
74
468783
}