1
//! Generic normalising rules for associative-commutative operators.
2

            
3
use std::mem::Discriminant;
4

            
5
use crate::shared::utils::{single_vec_child, with_single_vec_child};
6
use conjure_cp::ast::{AbstractLiteral, Expression as Expr, SymbolTable};
7
use conjure_cp::rule_engine::{
8
    ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect, register_rule,
9
};
10

            
11
/// Normalises associative_commutative operations.
12
///
13
/// For now, this just removes nested expressions by associativity.
14
///
15
/// ```text
16
/// v(v(a,b,...),c,d,...) ~> v(a,b,c,d)
17
/// v(a,b,[c,d],...)      ~> v(a,b,c,d)
18
/// where v is an AC vector operator
19
/// ```
20
///
21
/// The second form arises when a comprehension standing for several terms is expanded in place:
22
/// the expansion lands as a matrix literal among the operands, and an AC operator's operand list
23
/// is flat by definition.
24
#[register_rule("Base", 8900, [And, Or, Product, Sum])]
25
9533408
fn normalise_associative_commutative(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
26
9533408
    if !expr.is_associative_commutative_operator() {
27
9415
        return Err(RuleNotApplicable);
28
9523993
    }
29

            
30
9523993
    if !has_direct_nested_ac_child(expr) {
31
9295424
        return Err(RuleNotApplicable);
32
228569
    }
33

            
34
    // remove nesting deeply
35
1240995
    fn recurse_deeply(
36
1240995
        root_discriminant: Discriminant<Expr>,
37
1240995
        expr: Expr,
38
1240995
        changed: &mut bool,
39
1240995
    ) -> Vec<Expr> {
40
        // A matrix literal among the operands is spliced in, whatever the operator.
41
1240995
        if let Expr::AbstractLiteral(_, AbstractLiteral::Matrix(children, _)) = &expr {
42
            *changed = true;
43
            return children
44
                .clone()
45
                .into_iter()
46
                .flat_map(|child| recurse_deeply(root_discriminant, child, changed))
47
                .collect();
48
1240995
        }
49

            
50
        // if expr a different expression type, stop recursing
51
1240995
        if std::mem::discriminant(&expr) != root_discriminant {
52
747803
            return vec![expr];
53
493192
        }
54

            
55
493192
        let Some(children) = single_vec_child(&expr) else {
56
294
            return vec![expr];
57
        };
58
492898
        let old_len = children.len();
59

            
60
492898
        let new_children = children
61
492898
            .into_iter()
62
1012426
            .flat_map(|child| recurse_deeply(root_discriminant, child, changed))
63
            .collect::<Vec<_>>();
64
492898
        if new_children.len() != old_len {
65
200147
            *changed = true;
66
292751
        }
67

            
68
492898
        new_children
69
1240995
    }
70

            
71
228569
    if single_vec_child(expr).is_none() {
72
        return Err(RuleNotApplicable);
73
228569
    }
74

            
75
228569
    let mut changed = false;
76
228569
    let new_children = recurse_deeply(std::mem::discriminant(expr), expr.clone(), &mut changed);
77

            
78
228569
    if !changed {
79
45199
        return Err(RuleNotApplicable);
80
183370
    }
81

            
82
183370
    let new_expr = with_single_vec_child(expr, new_children);
83

            
84
183370
    Ok(RuleEffect::pure(new_expr))
85
9533408
}
86

            
87
9523993
fn has_direct_nested_ac_child(expr: &Expr) -> bool {
88
9523993
    let root_discriminant = std::mem::discriminant(expr);
89
9523993
    ac_children(expr).is_some_and(|children| {
90
197615803
        children.iter().any(|child| {
91
197615803
            std::mem::discriminant(child) == root_discriminant
92
197387234
                || matches!(
93
197387234
                    child,
94
                    Expr::AbstractLiteral(_, AbstractLiteral::Matrix(_, _))
95
                )
96
197615803
        })
97
9204577
    })
98
9523993
}
99

            
100
9523993
fn ac_children(expr: &Expr) -> Option<&[Expr]> {
101
9523993
    let matrix = match expr {
102
        Expr::And(_, matrix)
103
        | Expr::Or(_, matrix)
104
        | Expr::Product(_, matrix)
105
9523993
        | Expr::Sum(_, matrix) => matrix.as_ref(),
106
        _ => return None,
107
    };
108

            
109
9523993
    match matrix {
110
9204577
        Expr::AbstractLiteral(_, AbstractLiteral::Matrix(children, _)) => Some(children),
111
319416
        _ => None,
112
    }
113
9523993
}