1
//! Materialise linear operands through equalities handled by the selected PB provider.
2
use conjure_cp::ast::{Expression as Expr, Metadata, Moo, Reference, SATIntEncoding, SymbolTable};
3
use conjure_cp::rule_engine::{
4
    ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect, register_rule,
5
};
6
use uniplate::Uniplate;
7

            
8
/// Leave linear comparisons intact; only circuits need an intermediate represented value.
9
#[register_rule("SAT", 9450, [Root])]
10
3179810
fn materialise_linear_operand(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
11
3179810
    let mut path = Vec::new();
12
3179810
    let input = find_operand(expr, false, &mut path).ok_or(RuleNotApplicable)?;
13
6723
    let domain = input.domain_of().ok_or(RuleNotApplicable)?;
14
6723
    let mut symbols = symbols.clone();
15
6723
    let result: Expr = Reference::new(symbols.gen_find_auxiliary(&domain)).into();
16
6723
    let definition = Expr::Eq(Metadata::new(), Moo::new(result.clone()), Moo::new(input));
17
6723
    let rewritten = replace_at(expr, &path, result);
18
6723
    Ok(RuleEffect::new(rewritten, vec![definition], symbols))
19
3179810
}
20

            
21
223760052
fn find_operand(expr: &Expr, needed: bool, path: &mut Vec<usize>) -> Option<Expr> {
22
    // Code bits contain no numeric operands; binders must be expanded before hoisting.
23
223760052
    if matches!(
24
223760052
        expr,
25
        Expr::Atomic(..) | Expr::SATInt(..) | Expr::Comprehension(..)
26
    ) {
27
114960375
        return None;
28
108799677
    }
29
108799677
    if needed
30
1090980
        && is_linear_operation(expr)
31
14643
        && !free_negation(expr)
32
14643
        && super::pseudo_boolean::integer_view(expr).is_some_and(|view| !view.terms.is_empty())
33
    {
34
6723
        return Some(expr.clone());
35
108792954
    }
36
108792954
    let nonlinear = matches!(
37
108792954
        expr,
38
        Expr::Abs(..)
39
            | Expr::Min(..)
40
            | Expr::Max(..)
41
            | Expr::SafeDiv(..)
42
            | Expr::SafeMod(..)
43
            | Expr::SafePow(..)
44
105367581
    ) || (matches!(expr, Expr::Product(..))
45
257247
        && super::pseudo_boolean::integer_view(expr).is_none());
46
    // List wrappers pass the enclosing operation's requirement to each numeric operand.
47
108792954
    let children_needed = nonlinear
48
105139179
        || (needed
49
432432
            && matches!(
50
432432
                expr,
51
                Expr::AbstractLiteral(_, conjure_cp::ast::AbstractLiteral::Matrix(..))
52
            ));
53
108792954
    for (index, child) in expr.children().iter().enumerate() {
54
220580242
        path.push(index);
55
220580242
        if let Some(found) = find_operand(child, children_needed, path) {
56
26748
            return Some(found);
57
220553494
        }
58
220553494
        path.pop();
59
    }
60
108766206
    None
61
223760052
}
62

            
63
1090980
fn is_linear_operation(expr: &Expr) -> bool {
64
1090980
    matches!(
65
1090980
        expr,
66
        Expr::Sum(..) | Expr::Minus(..) | Expr::Neg(..) | Expr::Product(..)
67
    )
68
1090980
}
69

            
70
14643
fn free_negation(expr: &Expr) -> bool {
71
14643
    matches!(expr, Expr::Neg(_, input)
72
1080
        if matches!(input.as_ref(), Expr::SATInt(_, SATIntEncoding::Direct | SATIntEncoding::Order, ..)))
73
14643
}
74

            
75
33471
fn replace_at(expr: &Expr, path: &[usize], replacement: Expr) -> Expr {
76
33471
    let Some((&index, tail)) = path.split_first() else {
77
6723
        return replacement;
78
    };
79
26748
    let mut children = expr.children();
80
26748
    children[index] = replace_at(&children[index], tail, replacement);
81
26748
    expr.with_children(children)
82
33471
}