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

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

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

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

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

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

            
56
        new_children
57
    }
58

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

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

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

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

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