1
//! Select native encodings beneath asserted conjunctions without flattening the worklist.
2
use conjure_cp::ast::{
3
    AbstractLiteral, Expression as Expr, Metadata, Moo, SatEncodingDecision, SymbolTable,
4
};
5
use conjure_cp::rule_engine::{ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect};
6

            
7
/// Extract one asserted decision, preserving conjunctions and other Boolean contexts.
8
27223702
pub(super) fn select_asserted(
9
27223702
    expr: &Expr,
10
27223702
    symbols: &SymbolTable,
11
27223702
    select: impl Fn(&Expr) -> Option<SatEncodingDecision>,
12
27223702
) -> ApplicationResult {
13
27223702
    let Expr::Root(_, children) = expr else {
14
81
        return Err(RuleNotApplicable);
15
    };
16
27223621
    for (index, child) in children.iter().enumerate() {
17
224927215
        let Some((replacement, decision)) = select_conjunct(child, &select) else {
18
220854596
            continue;
19
        };
20
4072619
        let mut children = children.clone();
21
4072619
        if replacement == true.into() {
22
3868202
            children.remove(index);
23
        } else {
24
204417
            children[index] = replacement;
25
        }
26
4072619
        return Ok(RuleEffect::sat(
27
4072619
            Expr::Root(Metadata::new(), children),
28
4072619
            vec![decision],
29
4072619
            symbols.clone(),
30
4072619
        ));
31
    }
32
23151002
    Err(RuleNotApplicable)
33
27223702
}
34

            
35
246203224
fn select_conjunct(
36
246203224
    expr: &Expr,
37
246203224
    select: &impl Fn(&Expr) -> Option<SatEncodingDecision>,
38
246203224
) -> Option<(Expr, SatEncodingDecision)> {
39
246203224
    if let Some(decision) = select(expr) {
40
4072619
        return Some((true.into(), decision));
41
242130605
    }
42
242130605
    let Expr::And(metadata, inner) = expr else {
43
231703232
        return None;
44
    };
45
    let Expr::AbstractLiteral(matrix_metadata, AbstractLiteral::Matrix(entries, domain)) =
46
10427373
        inner.as_ref()
47
    else {
48
3715029
        return None;
49
    };
50
6712344
    for (index, entry) in entries.iter().enumerate() {
51
21276009
        let Some((replacement, decision)) = select_conjunct(entry, select) else {
52
21065850
            continue;
53
        };
54
210159
        let mut entries = entries.clone();
55
210159
        entries[index] = replacement;
56
        // Keep the same matrix labels and size; evaluator normalisation removes true later.
57
210159
        let inner = Expr::AbstractLiteral(
58
210159
            matrix_metadata.clone(),
59
210159
            AbstractLiteral::Matrix(entries, domain.clone()),
60
210159
        );
61
210159
        return Some((Expr::And(metadata.clone(), Moo::new(inner)), decision));
62
    }
63
6502185
    None
64
246203224
}